node-entry.js 903 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920
  1. /*
  2. @license
  3. Rollup.js v4.52.5
  4. Sat, 18 Oct 2025 06:53:02 GMT - commit 55a8fd5a70820f274921edf394efbbaa620f0962
  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, ArrowFunctionExpression as ArrowFunctionExpression$1, FunctionExpression as FunctionExpression$1, MemberExpression as MemberExpression$1, Identifier as Identifier$1, ImportExpression as ImportExpression$1, AwaitExpression as AwaitExpression$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, ExpressionStatement as ExpressionStatement$1, logMissingExport, normalize, getImportPath, logMissingNodeBuiltins, logReservedNamespace, error, 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, logSyntheticNamedExportsNeedNamespaceExport, logMissingEntryExport, logDuplicateExportError, logInvalidSourcemapForError, augmentCodeLocation, logInconsistentImportAttributes, logMissingJsxExport, logNamespaceConflict, logAmbiguousExternalNamespaces, logShimmedExport, parseAst, logInvalidFormatForTopLevelAwait, TemplateLiteral as TemplateLiteral$1, Literal as Literal$1, logCircularReexport, 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, logCannotAssignModuleToChunk, logAnonymousPluginCache, logDuplicatePluginName, logUnknownOption, LOGLEVEL_ERROR, logLevelPriority, LOGLEVEL_DEBUG, printQuotedStringList, logInvalidSetAssetSourceCall, logPluginError, logNoTransformMapOrAstWithoutCode, relativeId, logBadLoader, logExternalModulesCannotBeTransformedToModules, logInternalIdCannotBeExternal, isRelative, logUnresolvedImport, logUnresolvedImportTreatedAsExternal, logExternalSyntheticExports, logUnresolvedEntry, logUnresolvedImplicitDependant, logExternalModulesCannotBeIncludedInManualChunks, logEntryCannotBeExternal, logImplicitDependantCannotBeExternal, logNoAssetSourceSet, logFileReferenceIdNotFoundForFilename, logAssetReferenceIdNotFoundForSetSource, logAssetSourceAlreadySet, logInvalidRollupPhaseForChunkEmission, warnDeprecation, logChunkNotGeneratedForFileName, logAssetNotFinalisedForFileName, logFileNameConflict, URL_GENERATEBUNDLE, logInvalidLogPosition, logInputHookInOutputPlugin, logInvalidAddonPluginHook, logInvalidFunctionPluginHook, logImplicitDependantIsNotIncluded, logCircularDependency, augmentLogMessage, URL_JSX, URL_TREESHAKE_MODULESIDEEFFECTS, URL_TREESHAKE, 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 } 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.52.5";
  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 SymbolToStringTag = Symbol('Symbol.toStringTag');
  1672. const EMPTY_PATH = [];
  1673. const UNKNOWN_PATH = [UnknownKey];
  1674. // For deoptimizations, this means we are modifying an unknown property but did
  1675. // not lose track of the object or are creating a setter/getter;
  1676. // For assignment effects it means we do not check for setter/getter effects
  1677. // but only if something is mutated that is included, which is relevant for
  1678. // Object.defineProperty
  1679. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1680. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1681. const EntitiesKey = Symbol('Entities');
  1682. class EntityPathTracker {
  1683. constructor() {
  1684. this.entityPaths = Object.create(null, {
  1685. [EntitiesKey]: { value: new Set() }
  1686. });
  1687. }
  1688. trackEntityAtPathAndGetIfTracked(path, entity) {
  1689. const trackedEntities = this.getEntities(path);
  1690. if (trackedEntities.has(entity))
  1691. return true;
  1692. trackedEntities.add(entity);
  1693. return false;
  1694. }
  1695. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1696. const trackedEntities = this.getEntities(path);
  1697. if (trackedEntities.has(entity))
  1698. return returnIfTracked;
  1699. trackedEntities.add(entity);
  1700. const result = onUntracked();
  1701. trackedEntities.delete(entity);
  1702. return result;
  1703. }
  1704. getEntities(path) {
  1705. let currentPaths = this.entityPaths;
  1706. for (const pathSegment of path) {
  1707. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  1708. [EntitiesKey]: { value: new Set() }
  1709. });
  1710. }
  1711. return currentPaths[EntitiesKey];
  1712. }
  1713. }
  1714. const SHARED_RECURSION_TRACKER = new EntityPathTracker();
  1715. class DiscriminatedPathTracker {
  1716. constructor() {
  1717. this.entityPaths = Object.create(null, {
  1718. [EntitiesKey]: { value: new Map() }
  1719. });
  1720. }
  1721. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1722. let currentPaths = this.entityPaths;
  1723. for (const pathSegment of path) {
  1724. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  1725. [EntitiesKey]: { value: new Map() }
  1726. });
  1727. }
  1728. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  1729. if (trackedEntities.has(entity))
  1730. return true;
  1731. trackedEntities.add(entity);
  1732. return false;
  1733. }
  1734. }
  1735. const UNKNOWN_INCLUDED_PATH = Object.freeze({ [UnknownKey]: EMPTY_OBJECT });
  1736. class IncludedFullPathTracker {
  1737. constructor() {
  1738. this.includedPaths = null;
  1739. }
  1740. includePathAndGetIfIncluded(path) {
  1741. let included = true;
  1742. let parent = this;
  1743. let parentSegment = 'includedPaths';
  1744. let currentPaths = (this.includedPaths ||=
  1745. ((included = false), Object.create(null)));
  1746. for (const pathSegment of path) {
  1747. // This means from here, all paths are included
  1748. if (currentPaths[UnknownKey]) {
  1749. return true;
  1750. }
  1751. // Including UnknownKey automatically includes all nested paths.
  1752. // From above, we know that UnknownKey is not included yet.
  1753. if (typeof pathSegment === 'symbol') {
  1754. // Hopefully, this saves some memory over just setting
  1755. // currentPaths[UnknownKey] = EMPTY_OBJECT
  1756. parent[parentSegment] = UNKNOWN_INCLUDED_PATH;
  1757. return false;
  1758. }
  1759. parent = currentPaths;
  1760. parentSegment = pathSegment;
  1761. currentPaths = currentPaths[pathSegment] ||= ((included = false), Object.create(null));
  1762. }
  1763. return included;
  1764. }
  1765. }
  1766. const UNKNOWN_INCLUDED_TOP_LEVEL_PATH = Object.freeze({
  1767. [UnknownKey]: true
  1768. });
  1769. class IncludedTopLevelPathTracker {
  1770. constructor() {
  1771. this.includedPaths = null;
  1772. }
  1773. includePathAndGetIfIncluded(path) {
  1774. let included = true;
  1775. const includedPaths = (this.includedPaths ||=
  1776. ((included = false), Object.create(null)));
  1777. if (includedPaths[UnknownKey]) {
  1778. return true;
  1779. }
  1780. const [firstPathSegment, secondPathSegment] = path;
  1781. if (!firstPathSegment) {
  1782. return included;
  1783. }
  1784. if (typeof firstPathSegment === 'symbol') {
  1785. this.includedPaths = UNKNOWN_INCLUDED_TOP_LEVEL_PATH;
  1786. return false;
  1787. }
  1788. if (secondPathSegment) {
  1789. if (includedPaths[firstPathSegment] === UnknownKey) {
  1790. return true;
  1791. }
  1792. includedPaths[firstPathSegment] = UnknownKey;
  1793. return false;
  1794. }
  1795. if (includedPaths[firstPathSegment]) {
  1796. return true;
  1797. }
  1798. includedPaths[firstPathSegment] = true;
  1799. return false;
  1800. }
  1801. includeAllPaths(entity, context, basePath) {
  1802. const { includedPaths } = this;
  1803. if (includedPaths) {
  1804. if (includedPaths[UnknownKey]) {
  1805. entity.includePath([...basePath, UnknownKey], context);
  1806. }
  1807. else {
  1808. const inclusionEntries = Object.entries(includedPaths);
  1809. if (inclusionEntries.length === 0) {
  1810. entity.includePath(basePath, context);
  1811. }
  1812. else {
  1813. for (const [key, value] of inclusionEntries) {
  1814. entity.includePath(value === UnknownKey ? [...basePath, key, UnknownKey] : [...basePath, key], context);
  1815. }
  1816. }
  1817. }
  1818. }
  1819. }
  1820. }
  1821. /** @import { Node } from 'estree' */
  1822. /**
  1823. * @param {Node} node
  1824. * @param {Node} parent
  1825. * @returns {boolean}
  1826. */
  1827. function is_reference(node, parent) {
  1828. if (node.type === 'MemberExpression') {
  1829. return !node.computed && is_reference(node.object, node);
  1830. }
  1831. if (node.type !== 'Identifier') return false;
  1832. switch (parent?.type) {
  1833. // disregard `bar` in `foo.bar`
  1834. case 'MemberExpression':
  1835. return parent.computed || node === parent.object;
  1836. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  1837. case 'MethodDefinition':
  1838. return parent.computed;
  1839. // disregard the `meta` in `import.meta`
  1840. case 'MetaProperty':
  1841. return parent.meta === node;
  1842. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  1843. case 'PropertyDefinition':
  1844. return parent.computed || node === parent.value;
  1845. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  1846. case 'Property':
  1847. return parent.computed || node === parent.value;
  1848. // disregard the `bar` in `export { foo as bar }` or
  1849. // the foo in `import { foo as bar }`
  1850. case 'ExportSpecifier':
  1851. case 'ImportSpecifier':
  1852. return node === parent.local;
  1853. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  1854. case 'LabeledStatement':
  1855. case 'BreakStatement':
  1856. case 'ContinueStatement':
  1857. return false;
  1858. default:
  1859. return true;
  1860. }
  1861. }
  1862. function createInclusionContext() {
  1863. return {
  1864. brokenFlow: false,
  1865. hasBreak: false,
  1866. hasContinue: false,
  1867. includedCallArguments: new Set(),
  1868. includedLabels: new Set()
  1869. };
  1870. }
  1871. function createHasEffectsContext() {
  1872. return {
  1873. accessed: new EntityPathTracker(),
  1874. assigned: new EntityPathTracker(),
  1875. brokenFlow: false,
  1876. called: new DiscriminatedPathTracker(),
  1877. hasBreak: false,
  1878. hasContinue: false,
  1879. ignore: {
  1880. breaks: false,
  1881. continues: false,
  1882. labels: new Set(),
  1883. returnYield: false,
  1884. this: false
  1885. },
  1886. includedLabels: new Set(),
  1887. instantiated: new DiscriminatedPathTracker(),
  1888. replacedVariableInits: new Map()
  1889. };
  1890. }
  1891. function isFlagSet(flags, flag) {
  1892. return (flags & flag) !== 0;
  1893. }
  1894. function setFlag(flags, flag, value) {
  1895. return (flags & ~flag) | (-value & flag);
  1896. }
  1897. const UnknownValue = Symbol('Unknown Value');
  1898. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1899. const UnknownFalsyValue = Symbol('Unknown Falsy Value');
  1900. class ExpressionEntity {
  1901. constructor() {
  1902. this.flags = 0;
  1903. }
  1904. get included() {
  1905. return isFlagSet(this.flags, 1 /* Flag.included */);
  1906. }
  1907. set included(value) {
  1908. this.flags = setFlag(this.flags, 1 /* Flag.included */, value);
  1909. }
  1910. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  1911. deoptimizeInteraction(interaction);
  1912. }
  1913. deoptimizePath(_path) { }
  1914. /**
  1915. * If possible it returns a stringifyable literal value for this node that
  1916. * can be used for inlining or comparing values. Otherwise, it should return
  1917. * UnknownValue.
  1918. */
  1919. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1920. return UnknownValue;
  1921. }
  1922. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1923. return UNKNOWN_RETURN_EXPRESSION;
  1924. }
  1925. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1926. return true;
  1927. }
  1928. include(context, _includeChildrenRecursively, _options) {
  1929. if (!this.included)
  1930. this.includeNode(context);
  1931. }
  1932. includeNode(_context) {
  1933. this.included = true;
  1934. }
  1935. includePath(_path, context) {
  1936. if (!this.included)
  1937. this.includeNode(context);
  1938. }
  1939. /* We are both including and including an unknown path here as the former
  1940. * ensures that nested nodes are included while the latter ensures that all
  1941. * paths of the expression are included.
  1942. * */
  1943. includeCallArguments(interaction, context) {
  1944. includeInteraction(interaction, context);
  1945. }
  1946. shouldBeIncluded(_context) {
  1947. return true;
  1948. }
  1949. }
  1950. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1951. })();
  1952. const UNKNOWN_RETURN_EXPRESSION = [
  1953. UNKNOWN_EXPRESSION,
  1954. false
  1955. ];
  1956. const deoptimizeInteraction = (interaction) => {
  1957. for (const argument of interaction.args) {
  1958. argument?.deoptimizePath(UNKNOWN_PATH);
  1959. }
  1960. };
  1961. const includeInteraction = (interaction, context) => {
  1962. // We do not re-include the "this" argument as we expect this is already
  1963. // re-included at the call site
  1964. interaction.args[0]?.includePath(UNKNOWN_PATH, context);
  1965. includeInteractionWithoutThis(interaction, context);
  1966. };
  1967. const includeInteractionWithoutThis = ({ args }, context) => {
  1968. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  1969. const argument = args[argumentIndex];
  1970. if (argument) {
  1971. argument.includePath(UNKNOWN_PATH, context);
  1972. argument.include(context, false);
  1973. }
  1974. }
  1975. };
  1976. const INTERACTION_ACCESSED = 0;
  1977. const INTERACTION_ASSIGNED = 1;
  1978. const INTERACTION_CALLED = 2;
  1979. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1980. args: [null],
  1981. type: INTERACTION_ACCESSED
  1982. };
  1983. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  1984. args: [null, UNKNOWN_EXPRESSION],
  1985. type: INTERACTION_ASSIGNED
  1986. };
  1987. // While this is technically a call without arguments, we can compare against
  1988. // this reference in places where precise values or this argument would make a
  1989. // difference
  1990. const NODE_INTERACTION_UNKNOWN_CALL = {
  1991. args: [null],
  1992. type: INTERACTION_CALLED,
  1993. withNew: false
  1994. };
  1995. const PureFunctionKey = Symbol('PureFunction');
  1996. const getPureFunctions = ({ treeshake }) => {
  1997. const pureFunctions = Object.create(null);
  1998. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  1999. let currentFunctions = pureFunctions;
  2000. for (const pathSegment of functionName.split('.')) {
  2001. currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
  2002. }
  2003. currentFunctions[PureFunctionKey] = true;
  2004. }
  2005. return pureFunctions;
  2006. };
  2007. class Variable extends ExpressionEntity {
  2008. markReassigned() {
  2009. this.isReassigned = true;
  2010. }
  2011. constructor(name) {
  2012. super();
  2013. this.name = name;
  2014. this.alwaysRendered = false;
  2015. this.forbiddenNames = null;
  2016. this.globalName = null;
  2017. this.initReached = false;
  2018. this.isId = false;
  2019. this.kind = null;
  2020. this.renderBaseName = null;
  2021. this.renderName = null;
  2022. this.isReassigned = false;
  2023. this.onlyFunctionCallUsed = true;
  2024. }
  2025. /**
  2026. * Binds identifiers that reference this variable to this variable.
  2027. * Necessary to be able to change variable names.
  2028. */
  2029. addReference(_identifier) { }
  2030. /**
  2031. * Check if the identifier variable is only used as function call
  2032. * @returns true if the variable is only used as function call
  2033. */
  2034. getOnlyFunctionCallUsed() {
  2035. return this.onlyFunctionCallUsed;
  2036. }
  2037. /**
  2038. * Collect the places where the identifier variable is used
  2039. * @param usedPlace Where the variable is used
  2040. */
  2041. addUsedPlace(usedPlace) {
  2042. const isFunctionCall = usedPlace.parent.type === CallExpression$1 &&
  2043. usedPlace.parent.callee === usedPlace;
  2044. if (!isFunctionCall && usedPlace.parent.type !== ExportDefaultDeclaration$1) {
  2045. this.onlyFunctionCallUsed = false;
  2046. }
  2047. }
  2048. /**
  2049. * Prevent this variable from being renamed to this name to avoid name
  2050. * collisions
  2051. */
  2052. forbidName(name) {
  2053. (this.forbiddenNames ||= new Set()).add(name);
  2054. }
  2055. getBaseVariableName() {
  2056. return (this.renderedLikeHoisted?.getBaseVariableName() ||
  2057. this.renderBaseName ||
  2058. this.renderName ||
  2059. this.name);
  2060. }
  2061. getName(getPropertyAccess, useOriginalName) {
  2062. if (this.globalName) {
  2063. return this.globalName;
  2064. }
  2065. if (useOriginalName?.(this)) {
  2066. return this.name;
  2067. }
  2068. if (this.renderedLikeHoisted) {
  2069. return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
  2070. }
  2071. const name = this.renderName || this.name;
  2072. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  2073. }
  2074. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  2075. return type !== INTERACTION_ACCESSED || path.length > 0;
  2076. }
  2077. /**
  2078. * Marks this variable as being part of the bundle, which is usually the case
  2079. * when one of its identifiers becomes part of the bundle. Returns true if it
  2080. * has not been included previously. Once a variable is included, it should
  2081. * take care all its declarations are included.
  2082. */
  2083. includePath(path, context) {
  2084. this.included = true;
  2085. this.renderedLikeHoisted?.includePath(path, context);
  2086. }
  2087. /**
  2088. * Links the rendered name of this variable to another variable and includes
  2089. * this variable if the other variable is included.
  2090. */
  2091. renderLikeHoisted(variable) {
  2092. this.renderedLikeHoisted = variable;
  2093. }
  2094. markCalledFromTryStatement() { }
  2095. setRenderNames(baseName, name) {
  2096. this.renderBaseName = baseName;
  2097. this.renderName = name;
  2098. }
  2099. }
  2100. class ExternalVariable extends Variable {
  2101. constructor(module, name) {
  2102. super(name);
  2103. this.referenced = false;
  2104. this.module = module;
  2105. this.isNamespace = name === '*';
  2106. }
  2107. addReference(identifier) {
  2108. this.referenced = true;
  2109. if (this.name === 'default' || this.name === '*') {
  2110. this.module.suggestName(identifier.name);
  2111. }
  2112. }
  2113. hasEffectsOnInteractionAtPath(path, { type }) {
  2114. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  2115. }
  2116. includePath(path, context) {
  2117. super.includePath(path, context);
  2118. this.module.used = true;
  2119. }
  2120. }
  2121. function cacheObjectGetters(object, getterProperties) {
  2122. for (const property of getterProperties) {
  2123. const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
  2124. Object.defineProperty(object, property, {
  2125. get() {
  2126. const value = propertyGetter.call(object);
  2127. // This replaces the getter with a fixed value for subsequent calls
  2128. Object.defineProperty(object, property, { value });
  2129. return value;
  2130. }
  2131. });
  2132. }
  2133. }
  2134. const RESERVED_NAMES = new Set([
  2135. 'await',
  2136. 'break',
  2137. 'case',
  2138. 'catch',
  2139. 'class',
  2140. 'const',
  2141. 'continue',
  2142. 'debugger',
  2143. 'default',
  2144. 'delete',
  2145. 'do',
  2146. 'else',
  2147. 'enum',
  2148. 'eval',
  2149. 'export',
  2150. 'extends',
  2151. 'false',
  2152. 'finally',
  2153. 'for',
  2154. 'function',
  2155. 'if',
  2156. 'implements',
  2157. 'import',
  2158. 'in',
  2159. 'instanceof',
  2160. 'interface',
  2161. 'let',
  2162. 'NaN',
  2163. 'new',
  2164. 'null',
  2165. 'package',
  2166. 'private',
  2167. 'protected',
  2168. 'public',
  2169. 'return',
  2170. 'static',
  2171. 'super',
  2172. 'switch',
  2173. 'this',
  2174. 'throw',
  2175. 'true',
  2176. 'try',
  2177. 'typeof',
  2178. 'undefined',
  2179. 'var',
  2180. 'void',
  2181. 'while',
  2182. 'with',
  2183. 'yield'
  2184. ]);
  2185. const illegalCharacters = /[^\w$]/g;
  2186. const startsWithDigit = (value) => /\d/.test(value[0]);
  2187. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES.has(value) || value === 'arguments';
  2188. function isLegal(value) {
  2189. if (needsEscape(value)) {
  2190. return false;
  2191. }
  2192. return !illegalCharacters.test(value);
  2193. }
  2194. function makeLegal(value) {
  2195. value = value
  2196. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  2197. .replace(illegalCharacters, '_');
  2198. if (needsEscape(value))
  2199. value = `_${value}`;
  2200. return value || '_';
  2201. }
  2202. const VALID_IDENTIFIER_REGEXP = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
  2203. const NUMBER_REGEXP = /^(?:0|[1-9]\d*)$/;
  2204. function stringifyObjectKeyIfNeeded(key) {
  2205. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  2206. return key === '__proto__' ? '["__proto__"]' : key;
  2207. }
  2208. if (NUMBER_REGEXP.test(key) && +key <= Number.MAX_SAFE_INTEGER) {
  2209. return key;
  2210. }
  2211. return JSON.stringify(key);
  2212. }
  2213. function stringifyIdentifierIfNeeded(key) {
  2214. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  2215. return key;
  2216. }
  2217. return JSON.stringify(key);
  2218. }
  2219. class ExternalModule {
  2220. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
  2221. this.options = options;
  2222. this.id = id;
  2223. this.renormalizeRenderPath = renormalizeRenderPath;
  2224. this.dynamicImporters = [];
  2225. this.execIndex = Infinity;
  2226. this.exportedVariables = new Map();
  2227. this.importers = [];
  2228. this.reexported = false;
  2229. this.used = false;
  2230. this.declarations = new Map();
  2231. this.mostCommonSuggestion = 0;
  2232. this.nameSuggestions = new Map();
  2233. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  2234. const { importers, dynamicImporters } = this;
  2235. this.info = {
  2236. ast: null,
  2237. attributes,
  2238. code: null,
  2239. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2240. dynamicallyImportedIds: EMPTY_ARRAY,
  2241. get dynamicImporters() {
  2242. return dynamicImporters.sort();
  2243. },
  2244. exportedBindings: null,
  2245. exports: null,
  2246. hasDefaultExport: null,
  2247. id,
  2248. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2249. implicitlyLoadedBefore: EMPTY_ARRAY,
  2250. importedIdResolutions: EMPTY_ARRAY,
  2251. importedIds: EMPTY_ARRAY,
  2252. get importers() {
  2253. return importers.sort();
  2254. },
  2255. isEntry: false,
  2256. isExternal: true,
  2257. isIncluded: null,
  2258. meta,
  2259. moduleSideEffects,
  2260. syntheticNamedExports: false
  2261. };
  2262. }
  2263. cacheInfoGetters() {
  2264. cacheObjectGetters(this.info, ['dynamicImporters', 'importers']);
  2265. }
  2266. getVariableForExportName(name) {
  2267. const declaration = this.declarations.get(name);
  2268. if (declaration)
  2269. return [declaration];
  2270. const externalVariable = new ExternalVariable(this, name);
  2271. this.declarations.set(name, externalVariable);
  2272. this.exportedVariables.set(externalVariable, name);
  2273. return [externalVariable];
  2274. }
  2275. suggestName(name) {
  2276. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  2277. this.nameSuggestions.set(name, value);
  2278. if (value > this.mostCommonSuggestion) {
  2279. this.mostCommonSuggestion = value;
  2280. this.suggestedVariableName = name;
  2281. }
  2282. }
  2283. warnUnusedImports() {
  2284. const unused = [...this.declarations]
  2285. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2286. .map(([name]) => name);
  2287. if (unused.length === 0)
  2288. return;
  2289. const importersSet = new Set();
  2290. for (const name of unused) {
  2291. for (const importer of this.declarations.get(name).module.importers) {
  2292. importersSet.add(importer);
  2293. }
  2294. }
  2295. const importersArray = [...importersSet];
  2296. this.options.onLog(LOGLEVEL_WARN, logUnusedExternalImports(this.id, unused, importersArray));
  2297. }
  2298. }
  2299. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  2300. baseModule.isExecuted = true;
  2301. const modules = [baseModule];
  2302. const visitedModules = new Set();
  2303. for (const module of modules) {
  2304. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  2305. if (!(dependency instanceof ExternalModule) &&
  2306. !dependency.isExecuted &&
  2307. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  2308. !visitedModules.has(dependency.id)) {
  2309. dependency.isExecuted = true;
  2310. visitedModules.add(dependency.id);
  2311. modules.push(dependency);
  2312. }
  2313. }
  2314. }
  2315. }
  2316. const doNothing = () => { };
  2317. // This file is generated by scripts/generate-child-node-keys.js.
  2318. // Do not edit this file directly.
  2319. const childNodeKeys = {
  2320. ArrayExpression: ['elements'],
  2321. ArrayPattern: ['elements'],
  2322. ArrowFunctionExpression: ['params', 'body'],
  2323. AssignmentExpression: ['left', 'right'],
  2324. AssignmentPattern: ['left', 'right'],
  2325. AwaitExpression: ['argument'],
  2326. BinaryExpression: ['left', 'right'],
  2327. BlockStatement: ['body'],
  2328. BreakStatement: ['label'],
  2329. CallExpression: ['callee', 'arguments'],
  2330. CatchClause: ['param', 'body'],
  2331. ChainExpression: ['expression'],
  2332. ClassBody: ['body'],
  2333. ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
  2334. ClassExpression: ['decorators', 'id', 'superClass', 'body'],
  2335. ConditionalExpression: ['test', 'consequent', 'alternate'],
  2336. ContinueStatement: ['label'],
  2337. DebuggerStatement: [],
  2338. Decorator: ['expression'],
  2339. DoWhileStatement: ['body', 'test'],
  2340. EmptyStatement: [],
  2341. ExportAllDeclaration: ['exported', 'source', 'attributes'],
  2342. ExportDefaultDeclaration: ['declaration'],
  2343. ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
  2344. ExportSpecifier: ['local', 'exported'],
  2345. ExpressionStatement: ['expression'],
  2346. ForInStatement: ['left', 'right', 'body'],
  2347. ForOfStatement: ['left', 'right', 'body'],
  2348. ForStatement: ['init', 'test', 'update', 'body'],
  2349. FunctionDeclaration: ['id', 'params', 'body'],
  2350. FunctionExpression: ['id', 'params', 'body'],
  2351. Identifier: [],
  2352. IfStatement: ['test', 'consequent', 'alternate'],
  2353. ImportAttribute: ['key', 'value'],
  2354. ImportDeclaration: ['specifiers', 'source', 'attributes'],
  2355. ImportDefaultSpecifier: ['local'],
  2356. ImportExpression: ['source', 'options'],
  2357. ImportNamespaceSpecifier: ['local'],
  2358. ImportSpecifier: ['imported', 'local'],
  2359. JSXAttribute: ['name', 'value'],
  2360. JSXClosingElement: ['name'],
  2361. JSXClosingFragment: [],
  2362. JSXElement: ['openingElement', 'children', 'closingElement'],
  2363. JSXEmptyExpression: [],
  2364. JSXExpressionContainer: ['expression'],
  2365. JSXFragment: ['openingFragment', 'children', 'closingFragment'],
  2366. JSXIdentifier: [],
  2367. JSXMemberExpression: ['object', 'property'],
  2368. JSXNamespacedName: ['namespace', 'name'],
  2369. JSXOpeningElement: ['name', 'attributes'],
  2370. JSXOpeningFragment: [],
  2371. JSXSpreadAttribute: ['argument'],
  2372. JSXSpreadChild: ['expression'],
  2373. JSXText: [],
  2374. LabeledStatement: ['label', 'body'],
  2375. Literal: [],
  2376. LogicalExpression: ['left', 'right'],
  2377. MemberExpression: ['object', 'property'],
  2378. MetaProperty: ['meta', 'property'],
  2379. MethodDefinition: ['decorators', 'key', 'value'],
  2380. NewExpression: ['callee', 'arguments'],
  2381. ObjectExpression: ['properties'],
  2382. ObjectPattern: ['properties'],
  2383. PanicError: [],
  2384. ParseError: [],
  2385. PrivateIdentifier: [],
  2386. Program: ['body'],
  2387. Property: ['key', 'value'],
  2388. PropertyDefinition: ['decorators', 'key', 'value'],
  2389. RestElement: ['argument'],
  2390. ReturnStatement: ['argument'],
  2391. SequenceExpression: ['expressions'],
  2392. SpreadElement: ['argument'],
  2393. StaticBlock: ['body'],
  2394. Super: [],
  2395. SwitchCase: ['test', 'consequent'],
  2396. SwitchStatement: ['discriminant', 'cases'],
  2397. TaggedTemplateExpression: ['tag', 'quasi'],
  2398. TemplateElement: [],
  2399. TemplateLiteral: ['quasis', 'expressions'],
  2400. ThisExpression: [],
  2401. ThrowStatement: ['argument'],
  2402. TryStatement: ['block', 'handler', 'finalizer'],
  2403. UnaryExpression: ['argument'],
  2404. UpdateExpression: ['argument'],
  2405. VariableDeclaration: ['declarations'],
  2406. VariableDeclarator: ['id', 'init'],
  2407. WhileStatement: ['test', 'body'],
  2408. YieldExpression: ['argument']
  2409. };
  2410. const INCLUDE_PARAMETERS = 'variables';
  2411. const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
  2412. class NodeBase extends ExpressionEntity {
  2413. /**
  2414. * Nodes can apply custom deoptimizations once they become part of the
  2415. * executed code. To do this, they must initialize this as false, implement
  2416. * applyDeoptimizations and call this from include and hasEffects if they have
  2417. * custom handlers
  2418. */
  2419. get deoptimized() {
  2420. return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
  2421. }
  2422. set deoptimized(value) {
  2423. this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
  2424. }
  2425. constructor(parent, parentScope) {
  2426. super();
  2427. this.parent = parent;
  2428. this.scope = parentScope;
  2429. this.createScope(parentScope);
  2430. }
  2431. addExportedVariables(_variables, _exportNamesByVariable) { }
  2432. /**
  2433. * Override this to bind assignments to variables and do any initialisations
  2434. * that require the scopes to be populated with variables.
  2435. */
  2436. bind() {
  2437. for (const key of childNodeKeys[this.type]) {
  2438. const value = this[key];
  2439. if (Array.isArray(value)) {
  2440. for (const child of value) {
  2441. child?.bind();
  2442. }
  2443. }
  2444. else if (value) {
  2445. value.bind();
  2446. }
  2447. }
  2448. }
  2449. /**
  2450. * Override if this node should receive a different scope than the parent
  2451. * scope.
  2452. */
  2453. createScope(parentScope) {
  2454. this.scope = parentScope;
  2455. }
  2456. hasEffects(context) {
  2457. if (!this.deoptimized)
  2458. this.applyDeoptimizations();
  2459. for (const key of childNodeKeys[this.type]) {
  2460. const value = this[key];
  2461. if (value === null)
  2462. continue;
  2463. if (Array.isArray(value)) {
  2464. for (const child of value) {
  2465. if (child?.hasEffects(context))
  2466. return true;
  2467. }
  2468. }
  2469. else if (value.hasEffects(context))
  2470. return true;
  2471. }
  2472. return false;
  2473. }
  2474. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  2475. return (this.hasEffects(context) ||
  2476. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  2477. }
  2478. include(context, includeChildrenRecursively, _options) {
  2479. if (!this.included)
  2480. this.includeNode(context);
  2481. for (const key of childNodeKeys[this.type]) {
  2482. const value = this[key];
  2483. if (value === null)
  2484. continue;
  2485. if (Array.isArray(value)) {
  2486. for (const child of value) {
  2487. child?.include(context, includeChildrenRecursively);
  2488. }
  2489. }
  2490. else {
  2491. value.include(context, includeChildrenRecursively);
  2492. }
  2493. }
  2494. }
  2495. includeNode(context) {
  2496. this.included = true;
  2497. if (!this.deoptimized)
  2498. this.applyDeoptimizations();
  2499. for (const key of childNodeKeys[this.type]) {
  2500. const value = this[key];
  2501. if (value === null)
  2502. continue;
  2503. if (Array.isArray(value)) {
  2504. for (const child of value) {
  2505. child?.includePath(UNKNOWN_PATH, context);
  2506. }
  2507. }
  2508. else {
  2509. value.includePath(UNKNOWN_PATH, context);
  2510. }
  2511. }
  2512. }
  2513. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  2514. this.include(context, includeChildrenRecursively);
  2515. }
  2516. /**
  2517. * Override to perform special initialisation steps after the scope is
  2518. * initialised
  2519. */
  2520. initialise() {
  2521. this.scope.context.magicString.addSourcemapLocation(this.start);
  2522. this.scope.context.magicString.addSourcemapLocation(this.end);
  2523. }
  2524. parseNode(esTreeNode) {
  2525. for (const [key, value] of Object.entries(esTreeNode)) {
  2526. // Skip properties defined on the class already.
  2527. // This way, we can override this function to add custom initialisation and then call super.parseNode
  2528. // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
  2529. // in bitfields. Those are still assigned from the value in the esTreeNode.
  2530. if (this.hasOwnProperty(key))
  2531. continue;
  2532. if (key.charCodeAt(0) === 95 /* _ */) {
  2533. if (key === ANNOTATION_KEY) {
  2534. this.annotations = value;
  2535. }
  2536. else if (key === INVALID_ANNOTATION_KEY) {
  2537. this.invalidAnnotations = value;
  2538. }
  2539. }
  2540. else if (typeof value !== 'object' || value === null) {
  2541. this[key] = value;
  2542. }
  2543. else if (Array.isArray(value)) {
  2544. this[key] = new Array(value.length);
  2545. let index = 0;
  2546. for (const child of value) {
  2547. this[key][index++] =
  2548. child === null
  2549. ? null
  2550. : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child);
  2551. }
  2552. }
  2553. else {
  2554. this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
  2555. }
  2556. }
  2557. // extend child keys for unknown node types
  2558. childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
  2559. this.initialise();
  2560. return this;
  2561. }
  2562. removeAnnotations(code) {
  2563. if (this.annotations) {
  2564. for (const annotation of this.annotations) {
  2565. code.remove(annotation.start, annotation.end);
  2566. }
  2567. }
  2568. }
  2569. render(code, options) {
  2570. for (const key of childNodeKeys[this.type]) {
  2571. const value = this[key];
  2572. if (value === null)
  2573. continue;
  2574. if (Array.isArray(value)) {
  2575. for (const child of value) {
  2576. child?.render(code, options);
  2577. }
  2578. }
  2579. else {
  2580. value.render(code, options);
  2581. }
  2582. }
  2583. }
  2584. setAssignedValue(value) {
  2585. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  2586. }
  2587. shouldBeIncluded(context) {
  2588. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  2589. }
  2590. /**
  2591. * Just deoptimize everything by default so that when e.g. we do not track
  2592. * something properly, it is deoptimized.
  2593. * @protected
  2594. */
  2595. applyDeoptimizations() {
  2596. this.deoptimized = true;
  2597. for (const key of childNodeKeys[this.type]) {
  2598. const value = this[key];
  2599. if (value === null)
  2600. continue;
  2601. if (Array.isArray(value)) {
  2602. for (const child of value) {
  2603. child?.deoptimizePath(UNKNOWN_PATH);
  2604. }
  2605. }
  2606. else {
  2607. value.deoptimizePath(UNKNOWN_PATH);
  2608. }
  2609. }
  2610. this.scope.context.requestTreeshakingPass();
  2611. }
  2612. }
  2613. function createChildNodeKeysForNode(esTreeNode) {
  2614. return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  2615. }
  2616. function onlyIncludeSelf() {
  2617. this.included = true;
  2618. if (!this.deoptimized)
  2619. this.applyDeoptimizations();
  2620. }
  2621. function onlyIncludeSelfNoDeoptimize() {
  2622. this.included = true;
  2623. }
  2624. function doNotDeoptimize() {
  2625. this.deoptimized = true;
  2626. }
  2627. function isObjectExpressionNode(node) {
  2628. return node instanceof NodeBase && node.type === ObjectExpression$1;
  2629. }
  2630. function isPropertyNode(node) {
  2631. return node instanceof NodeBase && node.type === Property$1;
  2632. }
  2633. function isArrowFunctionExpressionNode(node) {
  2634. return node instanceof NodeBase && node.type === ArrowFunctionExpression$1;
  2635. }
  2636. function isFunctionExpressionNode(node) {
  2637. return node instanceof NodeBase && node.type === FunctionExpression$1;
  2638. }
  2639. function isCallExpressionNode(node) {
  2640. return node instanceof NodeBase && node.type === CallExpression$1;
  2641. }
  2642. function isMemberExpressionNode(node) {
  2643. return node instanceof NodeBase && node.type === MemberExpression$1;
  2644. }
  2645. function isImportExpressionNode(node) {
  2646. return node instanceof NodeBase && node.type === ImportExpression$1;
  2647. }
  2648. function isAwaitExpressionNode(node) {
  2649. return node instanceof NodeBase && node.type === AwaitExpression$1;
  2650. }
  2651. function isIdentifierNode(node) {
  2652. return node instanceof NodeBase && node.type === Identifier$1;
  2653. }
  2654. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  2655. return Object.create(inheritedDescriptions, memberDescriptions);
  2656. }
  2657. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  2658. getLiteralValueAtPath(path) {
  2659. return path.length > 0 ? UnknownValue : undefined;
  2660. }
  2661. })();
  2662. const returnsUnknown = {
  2663. value: {
  2664. hasEffectsWhenCalled: null,
  2665. returns: UNKNOWN_EXPRESSION
  2666. }
  2667. };
  2668. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  2669. getReturnExpressionWhenCalledAtPath(path) {
  2670. if (path.length === 1) {
  2671. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  2672. }
  2673. return UNKNOWN_RETURN_EXPRESSION;
  2674. }
  2675. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2676. if (interaction.type === INTERACTION_ACCESSED) {
  2677. return path.length > 1;
  2678. }
  2679. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2680. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  2681. }
  2682. return true;
  2683. }
  2684. })();
  2685. const returnsBoolean = {
  2686. value: {
  2687. hasEffectsWhenCalled: null,
  2688. returns: UNKNOWN_LITERAL_BOOLEAN
  2689. }
  2690. };
  2691. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  2692. getReturnExpressionWhenCalledAtPath(path) {
  2693. if (path.length === 1) {
  2694. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  2695. }
  2696. return UNKNOWN_RETURN_EXPRESSION;
  2697. }
  2698. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2699. if (interaction.type === INTERACTION_ACCESSED) {
  2700. return path.length > 1;
  2701. }
  2702. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2703. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  2704. }
  2705. return true;
  2706. }
  2707. })();
  2708. const returnsNumber = {
  2709. value: {
  2710. hasEffectsWhenCalled: null,
  2711. returns: UNKNOWN_LITERAL_NUMBER
  2712. }
  2713. };
  2714. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  2715. getReturnExpressionWhenCalledAtPath(path) {
  2716. if (path.length === 1) {
  2717. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  2718. }
  2719. return UNKNOWN_RETURN_EXPRESSION;
  2720. }
  2721. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2722. if (interaction.type === INTERACTION_ACCESSED) {
  2723. return path.length > 1;
  2724. }
  2725. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2726. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  2727. }
  2728. return true;
  2729. }
  2730. })();
  2731. const returnsString = {
  2732. value: {
  2733. hasEffectsWhenCalled: null,
  2734. returns: UNKNOWN_LITERAL_STRING
  2735. }
  2736. };
  2737. const stringReplace = {
  2738. value: {
  2739. hasEffectsWhenCalled({ args }, context) {
  2740. const argument1 = args[2];
  2741. return (args.length < 3 ||
  2742. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  2743. deoptimizeCache() { }
  2744. }) === 'symbol' &&
  2745. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  2746. },
  2747. returns: UNKNOWN_LITERAL_STRING
  2748. }
  2749. };
  2750. const objectMembers = assembleMemberDescriptions({
  2751. hasOwnProperty: returnsBoolean,
  2752. isPrototypeOf: returnsBoolean,
  2753. propertyIsEnumerable: returnsBoolean,
  2754. toLocaleString: returnsString,
  2755. toString: returnsString,
  2756. valueOf: returnsUnknown
  2757. });
  2758. const literalBooleanMembers = assembleMemberDescriptions({
  2759. valueOf: returnsBoolean
  2760. }, objectMembers);
  2761. const literalNumberMembers = assembleMemberDescriptions({
  2762. toExponential: returnsString,
  2763. toFixed: returnsString,
  2764. toLocaleString: returnsString,
  2765. toPrecision: returnsString,
  2766. valueOf: returnsNumber
  2767. }, objectMembers);
  2768. /**
  2769. * RegExp are stateful when they have the global or sticky flags set.
  2770. * But if we actually don't use them, the side effect does not matter.
  2771. * the check logic in `hasEffectsOnInteractionAtPath`.
  2772. */
  2773. const literalRegExpMembers = assembleMemberDescriptions({
  2774. exec: returnsUnknown,
  2775. test: returnsBoolean
  2776. }, objectMembers);
  2777. const literalStringMembers = assembleMemberDescriptions({
  2778. anchor: returnsString,
  2779. at: returnsUnknown,
  2780. big: returnsString,
  2781. blink: returnsString,
  2782. bold: returnsString,
  2783. charAt: returnsString,
  2784. charCodeAt: returnsNumber,
  2785. codePointAt: returnsUnknown,
  2786. concat: returnsString,
  2787. endsWith: returnsBoolean,
  2788. fixed: returnsString,
  2789. fontcolor: returnsString,
  2790. fontsize: returnsString,
  2791. includes: returnsBoolean,
  2792. indexOf: returnsNumber,
  2793. italics: returnsString,
  2794. lastIndexOf: returnsNumber,
  2795. link: returnsString,
  2796. localeCompare: returnsNumber,
  2797. match: returnsUnknown,
  2798. matchAll: returnsUnknown,
  2799. normalize: returnsString,
  2800. padEnd: returnsString,
  2801. padStart: returnsString,
  2802. repeat: returnsString,
  2803. replace: stringReplace,
  2804. replaceAll: stringReplace,
  2805. search: returnsNumber,
  2806. slice: returnsString,
  2807. small: returnsString,
  2808. split: returnsUnknown,
  2809. startsWith: returnsBoolean,
  2810. strike: returnsString,
  2811. sub: returnsString,
  2812. substr: returnsString,
  2813. substring: returnsString,
  2814. sup: returnsString,
  2815. toLocaleLowerCase: returnsString,
  2816. toLocaleUpperCase: returnsString,
  2817. toLowerCase: returnsString,
  2818. toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
  2819. toUpperCase: returnsString,
  2820. trim: returnsString,
  2821. trimEnd: returnsString,
  2822. trimLeft: returnsString,
  2823. trimRight: returnsString,
  2824. trimStart: returnsString,
  2825. valueOf: returnsString
  2826. }, objectMembers);
  2827. function getLiteralMembersForValue(value) {
  2828. if (value instanceof RegExp) {
  2829. return literalRegExpMembers;
  2830. }
  2831. switch (typeof value) {
  2832. case 'boolean': {
  2833. return literalBooleanMembers;
  2834. }
  2835. case 'number': {
  2836. return literalNumberMembers;
  2837. }
  2838. case 'string': {
  2839. return literalStringMembers;
  2840. }
  2841. }
  2842. return Object.create(null);
  2843. }
  2844. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  2845. if (typeof memberName !== 'string' || !members[memberName]) {
  2846. return true;
  2847. }
  2848. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  2849. }
  2850. function getMemberReturnExpressionWhenCalled(members, memberName) {
  2851. if (typeof memberName !== 'string' || !members[memberName])
  2852. return UNKNOWN_RETURN_EXPRESSION;
  2853. return [members[memberName].returns, false];
  2854. }
  2855. class Method extends ExpressionEntity {
  2856. constructor(description) {
  2857. super();
  2858. this.description = description;
  2859. }
  2860. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  2861. if (type === INTERACTION_CALLED && path.length === 0) {
  2862. if (this.description.mutatesSelfAsArray) {
  2863. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  2864. }
  2865. if (this.description.mutatesArgs) {
  2866. for (let index = 1; index < args.length; index++) {
  2867. args[index].deoptimizePath(UNKNOWN_PATH);
  2868. }
  2869. }
  2870. }
  2871. }
  2872. getReturnExpressionWhenCalledAtPath(path, { args }) {
  2873. if (path.length > 0) {
  2874. return UNKNOWN_RETURN_EXPRESSION;
  2875. }
  2876. return [
  2877. this.description.returnsPrimitive ||
  2878. (this.description.returns === 'self'
  2879. ? args[0] || UNKNOWN_EXPRESSION
  2880. : this.description.returns()),
  2881. false
  2882. ];
  2883. }
  2884. hasEffectsOnInteractionAtPath(path, { args, type }, context) {
  2885. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  2886. return true;
  2887. }
  2888. if (type === INTERACTION_CALLED) {
  2889. if (this.description.mutatesSelfAsArray === true &&
  2890. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  2891. return true;
  2892. }
  2893. if (this.description.callsArgs) {
  2894. for (const argumentIndex of this.description.callsArgs) {
  2895. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  2896. return true;
  2897. }
  2898. }
  2899. }
  2900. }
  2901. return false;
  2902. }
  2903. }
  2904. const METHOD_RETURNS_BOOLEAN = [
  2905. new Method({
  2906. callsArgs: null,
  2907. mutatesArgs: false,
  2908. mutatesSelfAsArray: false,
  2909. returns: null,
  2910. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  2911. })
  2912. ];
  2913. const METHOD_RETURNS_STRING = [
  2914. new Method({
  2915. callsArgs: null,
  2916. mutatesArgs: false,
  2917. mutatesSelfAsArray: false,
  2918. returns: null,
  2919. returnsPrimitive: UNKNOWN_LITERAL_STRING
  2920. })
  2921. ];
  2922. const METHOD_RETURNS_NUMBER = [
  2923. new Method({
  2924. callsArgs: null,
  2925. mutatesArgs: false,
  2926. mutatesSelfAsArray: false,
  2927. returns: null,
  2928. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  2929. })
  2930. ];
  2931. const METHOD_RETURNS_UNKNOWN = [
  2932. new Method({
  2933. callsArgs: null,
  2934. mutatesArgs: false,
  2935. mutatesSelfAsArray: false,
  2936. returns: null,
  2937. returnsPrimitive: UNKNOWN_EXPRESSION
  2938. })
  2939. ];
  2940. const INTEGER_REG_EXP = /^\d+$/;
  2941. class ObjectEntity extends ExpressionEntity {
  2942. get hasLostTrack() {
  2943. return isFlagSet(this.flags, 2048 /* Flag.hasLostTrack */);
  2944. }
  2945. set hasLostTrack(value) {
  2946. this.flags = setFlag(this.flags, 2048 /* Flag.hasLostTrack */, value);
  2947. }
  2948. get hasUnknownDeoptimizedInteger() {
  2949. return isFlagSet(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */);
  2950. }
  2951. set hasUnknownDeoptimizedInteger(value) {
  2952. this.flags = setFlag(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */, value);
  2953. }
  2954. get hasUnknownDeoptimizedProperty() {
  2955. return isFlagSet(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */);
  2956. }
  2957. set hasUnknownDeoptimizedProperty(value) {
  2958. this.flags = setFlag(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */, value);
  2959. }
  2960. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  2961. // and we assume there are no setters or getters
  2962. constructor(properties, prototypeExpression, immutable = false) {
  2963. super();
  2964. this.prototypeExpression = prototypeExpression;
  2965. this.immutable = immutable;
  2966. this.additionalExpressionsToBeDeoptimized = new Set();
  2967. this.allProperties = [];
  2968. this.deoptimizedPaths = Object.create(null);
  2969. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  2970. this.gettersByKey = Object.create(null);
  2971. this.propertiesAndGettersByKey = Object.create(null);
  2972. this.propertiesAndSettersByKey = Object.create(null);
  2973. this.settersByKey = Object.create(null);
  2974. this.unknownIntegerProps = [];
  2975. this.unmatchableGetters = [];
  2976. this.unmatchablePropertiesAndGetters = [];
  2977. this.unmatchablePropertiesAndSetters = [];
  2978. this.unmatchableSetters = [];
  2979. if (Array.isArray(properties)) {
  2980. this.buildPropertyMaps(properties);
  2981. }
  2982. else {
  2983. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  2984. for (const propertiesForKey of Object.values(properties)) {
  2985. this.allProperties.push(...propertiesForKey);
  2986. }
  2987. }
  2988. }
  2989. deoptimizeAllProperties(noAccessors) {
  2990. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  2991. if (noAccessors) {
  2992. this.hasUnknownDeoptimizedProperty = true;
  2993. }
  2994. else {
  2995. this.hasLostTrack = true;
  2996. }
  2997. if (isDeoptimized) {
  2998. return;
  2999. }
  3000. for (const properties of [
  3001. ...Object.values(this.propertiesAndGettersByKey),
  3002. ...Object.values(this.settersByKey)
  3003. ]) {
  3004. for (const property of properties) {
  3005. property.deoptimizePath(UNKNOWN_PATH);
  3006. }
  3007. }
  3008. // While the prototype itself cannot be mutated, each property can
  3009. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  3010. this.deoptimizeCachedEntities();
  3011. }
  3012. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  3013. const [key, ...subPath] = path;
  3014. const { args, type } = interaction;
  3015. if (this.hasLostTrack ||
  3016. // single paths that are deoptimized will not become getters or setters
  3017. ((type === INTERACTION_CALLED || path.length > 1) &&
  3018. (this.hasUnknownDeoptimizedProperty ||
  3019. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  3020. deoptimizeInteraction(interaction);
  3021. return;
  3022. }
  3023. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  3024. ? [
  3025. this.propertiesAndGettersByKey,
  3026. this.propertiesAndGettersByKey,
  3027. this.unmatchablePropertiesAndGetters
  3028. ]
  3029. : type === INTERACTION_ACCESSED
  3030. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  3031. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  3032. if (typeof key === 'string') {
  3033. if (propertiesForExactMatchByKey[key]) {
  3034. const properties = relevantPropertiesByKey[key];
  3035. if (properties) {
  3036. for (const property of properties) {
  3037. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3038. }
  3039. }
  3040. if (!this.immutable) {
  3041. for (const argument of args) {
  3042. if (argument) {
  3043. this.additionalExpressionsToBeDeoptimized.add(argument);
  3044. }
  3045. }
  3046. }
  3047. return;
  3048. }
  3049. for (const property of relevantUnmatchableProperties) {
  3050. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3051. }
  3052. if (INTEGER_REG_EXP.test(key)) {
  3053. for (const property of this.unknownIntegerProps) {
  3054. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3055. }
  3056. }
  3057. }
  3058. else {
  3059. for (const properties of [
  3060. ...Object.values(relevantPropertiesByKey),
  3061. relevantUnmatchableProperties
  3062. ]) {
  3063. for (const property of properties) {
  3064. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3065. }
  3066. }
  3067. for (const property of this.unknownIntegerProps) {
  3068. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3069. }
  3070. }
  3071. if (!this.immutable) {
  3072. for (const argument of args) {
  3073. if (argument) {
  3074. this.additionalExpressionsToBeDeoptimized.add(argument);
  3075. }
  3076. }
  3077. }
  3078. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  3079. }
  3080. deoptimizeIntegerProperties() {
  3081. if (this.hasLostTrack ||
  3082. this.hasUnknownDeoptimizedProperty ||
  3083. this.hasUnknownDeoptimizedInteger) {
  3084. return;
  3085. }
  3086. this.hasUnknownDeoptimizedInteger = true;
  3087. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  3088. if (INTEGER_REG_EXP.test(key)) {
  3089. for (const property of propertiesAndGetters) {
  3090. property.deoptimizePath(UNKNOWN_PATH);
  3091. }
  3092. }
  3093. }
  3094. this.deoptimizeCachedIntegerEntities();
  3095. }
  3096. // Assumption: If only a specific path is deoptimized, no accessors are created
  3097. deoptimizePath(path) {
  3098. if (this.hasLostTrack || this.immutable) {
  3099. return;
  3100. }
  3101. const key = path[0];
  3102. if (path.length === 1) {
  3103. if (key === UnknownInteger) {
  3104. return this.deoptimizeIntegerProperties();
  3105. }
  3106. else if (typeof key !== 'string') {
  3107. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  3108. }
  3109. if (!this.deoptimizedPaths[key]) {
  3110. this.deoptimizedPaths[key] = true;
  3111. // we only deoptimizeCache exact matches as in all other cases,
  3112. // we do not return a literal value or return expression
  3113. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  3114. if (expressionsToBeDeoptimized) {
  3115. for (const expression of expressionsToBeDeoptimized) {
  3116. expression.deoptimizeCache();
  3117. }
  3118. }
  3119. }
  3120. }
  3121. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  3122. for (const property of typeof key === 'string'
  3123. ? [
  3124. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  3125. ...(this.settersByKey[key] || this.unmatchableSetters)
  3126. ]
  3127. : this.allProperties) {
  3128. property.deoptimizePath(subPath);
  3129. }
  3130. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [path[0], UnknownKey] : path);
  3131. }
  3132. getLiteralValueAtPath(path, recursionTracker, origin) {
  3133. if (path.length === 0) {
  3134. // This should actually be "UnknownTruthyValue". However, this currently
  3135. // causes an issue with TypeScript enums in files with moduleSideEffects:
  3136. // false because we cannot properly track whether a "var" has been
  3137. // initialized. This should be reverted once we can properly track this.
  3138. // return UnknownTruthyValue;
  3139. return UnknownValue;
  3140. }
  3141. const key = path[0];
  3142. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  3143. if (expressionAtPath) {
  3144. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  3145. }
  3146. if (this.prototypeExpression) {
  3147. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  3148. }
  3149. if (path.length === 1) {
  3150. return undefined;
  3151. }
  3152. return UnknownValue;
  3153. }
  3154. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  3155. if (path.length === 0) {
  3156. return UNKNOWN_RETURN_EXPRESSION;
  3157. }
  3158. const [key, ...subPath] = path;
  3159. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  3160. if (expressionAtPath) {
  3161. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  3162. }
  3163. if (this.prototypeExpression) {
  3164. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  3165. }
  3166. return UNKNOWN_RETURN_EXPRESSION;
  3167. }
  3168. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3169. const [key, ...subPath] = path;
  3170. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  3171. const expressionAtPath = this.getMemberExpression(key);
  3172. if (expressionAtPath) {
  3173. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  3174. }
  3175. if (this.prototypeExpression) {
  3176. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  3177. }
  3178. return true;
  3179. }
  3180. if (key === UnknownNonAccessorKey)
  3181. return false;
  3182. if (this.hasLostTrack)
  3183. return true;
  3184. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  3185. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  3186. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  3187. if (typeof key === 'string') {
  3188. if (propertiesAndAccessorsByKey[key]) {
  3189. const accessors = accessorsByKey[key];
  3190. if (accessors) {
  3191. for (const accessor of accessors) {
  3192. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  3193. return true;
  3194. }
  3195. }
  3196. return false;
  3197. }
  3198. for (const accessor of unmatchableAccessors) {
  3199. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  3200. return true;
  3201. }
  3202. }
  3203. }
  3204. else {
  3205. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  3206. for (const accessor of accessors) {
  3207. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  3208. return true;
  3209. }
  3210. }
  3211. }
  3212. if (this.prototypeExpression) {
  3213. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  3214. }
  3215. return false;
  3216. }
  3217. include(context, includeChildrenRecursively) {
  3218. this.included = true;
  3219. for (const property of this.allProperties) {
  3220. if (includeChildrenRecursively || property.shouldBeIncluded(context)) {
  3221. property.include(context, includeChildrenRecursively);
  3222. }
  3223. }
  3224. this.prototypeExpression?.include(context, includeChildrenRecursively);
  3225. }
  3226. includePath(path, context) {
  3227. this.included = true;
  3228. if (path.length === 0)
  3229. return;
  3230. const [key, ...subPath] = path;
  3231. const [includedMembers, includedPath] = typeof key === 'string'
  3232. ? [
  3233. new Set([
  3234. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  3235. ...(this.propertiesAndSettersByKey[key] || this.unmatchablePropertiesAndSetters)
  3236. ]),
  3237. subPath
  3238. ]
  3239. : [this.allProperties, UNKNOWN_PATH];
  3240. for (const property of includedMembers) {
  3241. property.includePath(includedPath, context);
  3242. }
  3243. this.prototypeExpression?.includePath(path, context);
  3244. }
  3245. buildPropertyMaps(properties) {
  3246. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchablePropertiesAndSetters, unmatchableGetters, unmatchableSetters } = this;
  3247. for (let index = properties.length - 1; index >= 0; index--) {
  3248. const { key, kind, property } = properties[index];
  3249. allProperties.push(property);
  3250. if (typeof key === 'string') {
  3251. if (kind === 'set') {
  3252. if (!propertiesAndSettersByKey[key]) {
  3253. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  3254. settersByKey[key] = [property, ...unmatchableSetters];
  3255. }
  3256. }
  3257. else if (kind === 'get') {
  3258. if (!propertiesAndGettersByKey[key]) {
  3259. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  3260. gettersByKey[key] = [property, ...unmatchableGetters];
  3261. }
  3262. }
  3263. else {
  3264. if (!propertiesAndSettersByKey[key]) {
  3265. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  3266. }
  3267. if (!propertiesAndGettersByKey[key]) {
  3268. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  3269. }
  3270. }
  3271. }
  3272. else {
  3273. if (key === UnknownInteger) {
  3274. unknownIntegerProps.push(property);
  3275. continue;
  3276. }
  3277. if (kind === 'set')
  3278. unmatchableSetters.push(property);
  3279. if (kind === 'get')
  3280. unmatchableGetters.push(property);
  3281. if (kind !== 'get')
  3282. unmatchablePropertiesAndSetters.push(property);
  3283. if (kind !== 'set')
  3284. unmatchablePropertiesAndGetters.push(property);
  3285. }
  3286. }
  3287. }
  3288. deoptimizeCachedEntities() {
  3289. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  3290. for (const expression of expressionsToBeDeoptimized) {
  3291. expression.deoptimizeCache();
  3292. }
  3293. }
  3294. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  3295. expression.deoptimizePath(UNKNOWN_PATH);
  3296. }
  3297. }
  3298. deoptimizeCachedIntegerEntities() {
  3299. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  3300. if (INTEGER_REG_EXP.test(key)) {
  3301. for (const expression of expressionsToBeDeoptimized) {
  3302. expression.deoptimizeCache();
  3303. }
  3304. }
  3305. }
  3306. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  3307. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  3308. }
  3309. }
  3310. getMemberExpression(key) {
  3311. if (this.hasLostTrack ||
  3312. this.hasUnknownDeoptimizedProperty ||
  3313. typeof key !== 'string' ||
  3314. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  3315. this.deoptimizedPaths[key]) {
  3316. return UNKNOWN_EXPRESSION;
  3317. }
  3318. const properties = this.propertiesAndGettersByKey[key];
  3319. if (properties?.length === 1) {
  3320. return properties[0];
  3321. }
  3322. if (properties ||
  3323. this.unmatchablePropertiesAndGetters.length > 0 ||
  3324. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  3325. return UNKNOWN_EXPRESSION;
  3326. }
  3327. return null;
  3328. }
  3329. getMemberExpressionAndTrackDeopt(key, origin) {
  3330. if (typeof key !== 'string') {
  3331. return UNKNOWN_EXPRESSION;
  3332. }
  3333. const expression = this.getMemberExpression(key);
  3334. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  3335. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  3336. this.expressionsToBeDeoptimizedByKey[key] || []);
  3337. expressionsToBeDeoptimized.push(origin);
  3338. }
  3339. return expression;
  3340. }
  3341. }
  3342. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  3343. // This makes sure unknown properties are not handled as "undefined" but as
  3344. // "unknown" but without access side effects. An exception is done for numeric
  3345. // properties as we do not expect new builtin properties to be numbers, this
  3346. // will improve tree-shaking for out-of-bounds array properties
  3347. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  3348. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  3349. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  3350. deoptimizeInteraction(interaction);
  3351. }
  3352. }
  3353. getLiteralValueAtPath(path) {
  3354. // We ignore number properties as we do not expect new properties to be
  3355. // numbers and also want to keep handling out-of-bound array elements as
  3356. // "undefined"
  3357. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  3358. }
  3359. hasEffectsOnInteractionAtPath(path, { type }) {
  3360. return path.length > 1 || type === INTERACTION_CALLED;
  3361. }
  3362. })();
  3363. const OBJECT_PROTOTYPE = new ObjectEntity({
  3364. __proto__: null,
  3365. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  3366. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  3367. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  3368. toLocaleString: METHOD_RETURNS_STRING,
  3369. toString: METHOD_RETURNS_STRING,
  3370. valueOf: METHOD_RETURNS_UNKNOWN
  3371. }, OBJECT_PROTOTYPE_FALLBACK, true);
  3372. const NEW_ARRAY_PROPERTIES = [
  3373. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  3374. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  3375. ];
  3376. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  3377. new Method({
  3378. callsArgs: [0],
  3379. mutatesArgs: false,
  3380. mutatesSelfAsArray: 'deopt-only',
  3381. returns: null,
  3382. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  3383. })
  3384. ];
  3385. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  3386. new Method({
  3387. callsArgs: [0],
  3388. mutatesArgs: false,
  3389. mutatesSelfAsArray: 'deopt-only',
  3390. returns: null,
  3391. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  3392. })
  3393. ];
  3394. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  3395. new Method({
  3396. callsArgs: null,
  3397. mutatesArgs: false,
  3398. mutatesSelfAsArray: true,
  3399. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3400. returnsPrimitive: null
  3401. })
  3402. ];
  3403. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  3404. new Method({
  3405. callsArgs: null,
  3406. mutatesArgs: false,
  3407. mutatesSelfAsArray: 'deopt-only',
  3408. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3409. returnsPrimitive: null
  3410. })
  3411. ];
  3412. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  3413. new Method({
  3414. callsArgs: [0],
  3415. mutatesArgs: false,
  3416. mutatesSelfAsArray: 'deopt-only',
  3417. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3418. returnsPrimitive: null
  3419. })
  3420. ];
  3421. const METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER = [
  3422. new Method({
  3423. callsArgs: null,
  3424. mutatesArgs: true,
  3425. mutatesSelfAsArray: true,
  3426. returns: null,
  3427. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  3428. })
  3429. ];
  3430. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  3431. new Method({
  3432. callsArgs: null,
  3433. mutatesArgs: false,
  3434. mutatesSelfAsArray: true,
  3435. returns: null,
  3436. returnsPrimitive: UNKNOWN_EXPRESSION
  3437. })
  3438. ];
  3439. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  3440. new Method({
  3441. callsArgs: null,
  3442. mutatesArgs: false,
  3443. mutatesSelfAsArray: 'deopt-only',
  3444. returns: null,
  3445. returnsPrimitive: UNKNOWN_EXPRESSION
  3446. })
  3447. ];
  3448. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  3449. new Method({
  3450. callsArgs: [0],
  3451. mutatesArgs: false,
  3452. mutatesSelfAsArray: 'deopt-only',
  3453. returns: null,
  3454. returnsPrimitive: UNKNOWN_EXPRESSION
  3455. })
  3456. ];
  3457. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  3458. new Method({
  3459. callsArgs: null,
  3460. mutatesArgs: false,
  3461. mutatesSelfAsArray: true,
  3462. returns: 'self',
  3463. returnsPrimitive: null
  3464. })
  3465. ];
  3466. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  3467. new Method({
  3468. callsArgs: [0],
  3469. mutatesArgs: false,
  3470. mutatesSelfAsArray: true,
  3471. returns: 'self',
  3472. returnsPrimitive: null
  3473. })
  3474. ];
  3475. const ARRAY_PROTOTYPE = new ObjectEntity({
  3476. __proto__: null,
  3477. // We assume that accessors have effects as we do not track the accessed value afterwards
  3478. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  3479. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3480. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  3481. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3482. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  3483. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  3484. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3485. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3486. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  3487. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3488. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  3489. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3490. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3491. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3492. includes: METHOD_RETURNS_BOOLEAN,
  3493. indexOf: METHOD_RETURNS_NUMBER,
  3494. join: METHOD_RETURNS_STRING,
  3495. keys: METHOD_RETURNS_UNKNOWN,
  3496. lastIndexOf: METHOD_RETURNS_NUMBER,
  3497. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3498. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  3499. push: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  3500. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3501. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3502. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  3503. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  3504. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3505. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  3506. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  3507. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  3508. toLocaleString: METHOD_RETURNS_STRING,
  3509. toString: METHOD_RETURNS_STRING,
  3510. unshift: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  3511. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  3512. }, OBJECT_PROTOTYPE, true);
  3513. class SpreadElement extends NodeBase {
  3514. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  3515. if (path.length > 0) {
  3516. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, UNKNOWN_PATH, recursionTracker);
  3517. }
  3518. }
  3519. hasEffects(context) {
  3520. if (!this.deoptimized)
  3521. this.applyDeoptimizations();
  3522. const { propertyReadSideEffects } = this.scope.context.options
  3523. .treeshake;
  3524. return (this.argument.hasEffects(context) ||
  3525. (propertyReadSideEffects &&
  3526. (propertyReadSideEffects === 'always' ||
  3527. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  3528. }
  3529. includeNode(context) {
  3530. this.included = true;
  3531. if (!this.deoptimized)
  3532. this.applyDeoptimizations();
  3533. this.argument.includePath(UNKNOWN_PATH, context);
  3534. }
  3535. applyDeoptimizations() {
  3536. this.deoptimized = true;
  3537. // Only properties of properties of the argument could become subject to reassignment
  3538. // This will also reassign the return values of iterators
  3539. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  3540. this.scope.context.requestTreeshakingPass();
  3541. }
  3542. }
  3543. class ArrayExpression extends NodeBase {
  3544. constructor() {
  3545. super(...arguments);
  3546. this.objectEntity = null;
  3547. }
  3548. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  3549. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  3550. }
  3551. deoptimizePath(path) {
  3552. this.getObjectEntity().deoptimizePath(path);
  3553. }
  3554. getLiteralValueAtPath(path, recursionTracker, origin) {
  3555. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  3556. }
  3557. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  3558. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  3559. }
  3560. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3561. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  3562. }
  3563. includeNode(context) {
  3564. this.included = true;
  3565. if (!this.deoptimized)
  3566. this.applyDeoptimizations();
  3567. for (const element of this.elements) {
  3568. if (element) {
  3569. element?.includePath(UNKNOWN_PATH, context);
  3570. }
  3571. }
  3572. }
  3573. applyDeoptimizations() {
  3574. this.deoptimized = true;
  3575. let hasSpread = false;
  3576. for (let index = 0; index < this.elements.length; index++) {
  3577. const element = this.elements[index];
  3578. if (element && (hasSpread || element instanceof SpreadElement)) {
  3579. hasSpread = true;
  3580. element.deoptimizePath(UNKNOWN_PATH);
  3581. }
  3582. }
  3583. this.scope.context.requestTreeshakingPass();
  3584. }
  3585. getObjectEntity() {
  3586. if (this.objectEntity !== null) {
  3587. return this.objectEntity;
  3588. }
  3589. const properties = [
  3590. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  3591. ];
  3592. let hasSpread = false;
  3593. for (let index = 0; index < this.elements.length; index++) {
  3594. const element = this.elements[index];
  3595. if (hasSpread || element instanceof SpreadElement) {
  3596. if (element) {
  3597. hasSpread = true;
  3598. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  3599. }
  3600. }
  3601. else if (element) {
  3602. properties.push({ key: String(index), kind: 'init', property: element });
  3603. }
  3604. else {
  3605. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  3606. }
  3607. }
  3608. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  3609. }
  3610. }
  3611. /* eslint sort-keys: "off" */
  3612. const ValueProperties = Symbol('Value Properties');
  3613. const getUnknownValue = () => UnknownValue;
  3614. const returnFalse = () => false;
  3615. const returnTrue = () => true;
  3616. const PURE = {
  3617. deoptimizeArgumentsOnCall: doNothing,
  3618. getLiteralValue: getUnknownValue,
  3619. hasEffectsWhenCalled: returnFalse
  3620. };
  3621. const IMPURE = {
  3622. deoptimizeArgumentsOnCall: doNothing,
  3623. getLiteralValue: getUnknownValue,
  3624. hasEffectsWhenCalled: returnTrue
  3625. };
  3626. const PURE_WITH_ARRAY = {
  3627. deoptimizeArgumentsOnCall: doNothing,
  3628. getLiteralValue: getUnknownValue,
  3629. hasEffectsWhenCalled({ args }) {
  3630. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  3631. }
  3632. };
  3633. const GETTER_ACCESS = {
  3634. deoptimizeArgumentsOnCall: doNothing,
  3635. getLiteralValue: getUnknownValue,
  3636. hasEffectsWhenCalled({ args }, context) {
  3637. const [_thisArgument, firstArgument] = args;
  3638. return (!(firstArgument instanceof ExpressionEntity) ||
  3639. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  3640. }
  3641. };
  3642. // We use shortened variables to reduce file size here
  3643. /* OBJECT */
  3644. const O = {
  3645. __proto__: null,
  3646. [ValueProperties]: IMPURE
  3647. };
  3648. /* PURE FUNCTION */
  3649. const PF = {
  3650. __proto__: null,
  3651. [ValueProperties]: PURE
  3652. };
  3653. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  3654. const PF_NO_GETTER = {
  3655. __proto__: null,
  3656. [ValueProperties]: GETTER_ACCESS
  3657. };
  3658. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  3659. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  3660. __proto__: null,
  3661. [ValueProperties]: {
  3662. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  3663. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  3664. },
  3665. getLiteralValue: getUnknownValue,
  3666. hasEffectsWhenCalled({ args }, context) {
  3667. return (args.length <= 1 ||
  3668. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  3669. }
  3670. }
  3671. };
  3672. /* CONSTRUCTOR */
  3673. const C = {
  3674. __proto__: null,
  3675. [ValueProperties]: IMPURE,
  3676. prototype: O
  3677. };
  3678. /* PURE CONSTRUCTOR */
  3679. const PC = {
  3680. __proto__: null,
  3681. [ValueProperties]: PURE,
  3682. prototype: O
  3683. };
  3684. const PC_WITH_ARRAY = {
  3685. __proto__: null,
  3686. [ValueProperties]: PURE_WITH_ARRAY,
  3687. prototype: O
  3688. };
  3689. const ARRAY_TYPE = {
  3690. __proto__: null,
  3691. [ValueProperties]: PURE,
  3692. from: O,
  3693. of: PF,
  3694. prototype: O
  3695. };
  3696. const INTL_MEMBER = {
  3697. __proto__: null,
  3698. [ValueProperties]: PURE,
  3699. supportedLocalesOf: PC
  3700. };
  3701. const knownGlobals = {
  3702. // Placeholders for global objects to avoid shape mutations
  3703. global: O,
  3704. globalThis: O,
  3705. self: O,
  3706. window: O,
  3707. // Common globals
  3708. __proto__: null,
  3709. [ValueProperties]: IMPURE,
  3710. Array: {
  3711. __proto__: null,
  3712. [ValueProperties]: IMPURE,
  3713. from: O,
  3714. isArray: PF,
  3715. of: PF,
  3716. prototype: O
  3717. },
  3718. ArrayBuffer: {
  3719. __proto__: null,
  3720. [ValueProperties]: PURE,
  3721. isView: PF,
  3722. prototype: O
  3723. },
  3724. AggregateError: PC_WITH_ARRAY,
  3725. Atomics: O,
  3726. BigInt: C,
  3727. BigInt64Array: C,
  3728. BigUint64Array: C,
  3729. Boolean: PC,
  3730. constructor: C,
  3731. DataView: PC,
  3732. Date: {
  3733. __proto__: null,
  3734. [ValueProperties]: PURE,
  3735. now: PF,
  3736. parse: PF,
  3737. prototype: O,
  3738. UTC: PF
  3739. },
  3740. decodeURI: PF,
  3741. decodeURIComponent: PF,
  3742. encodeURI: PF,
  3743. encodeURIComponent: PF,
  3744. Error: PC,
  3745. escape: PF,
  3746. eval: O,
  3747. EvalError: PC,
  3748. FinalizationRegistry: C,
  3749. Float32Array: ARRAY_TYPE,
  3750. Float64Array: ARRAY_TYPE,
  3751. Function: C,
  3752. hasOwnProperty: O,
  3753. Infinity: O,
  3754. Int16Array: ARRAY_TYPE,
  3755. Int32Array: ARRAY_TYPE,
  3756. Int8Array: ARRAY_TYPE,
  3757. isFinite: PF,
  3758. isNaN: PF,
  3759. isPrototypeOf: O,
  3760. JSON: O,
  3761. Map: PC_WITH_ARRAY,
  3762. Math: {
  3763. __proto__: null,
  3764. [ValueProperties]: IMPURE,
  3765. abs: PF,
  3766. acos: PF,
  3767. acosh: PF,
  3768. asin: PF,
  3769. asinh: PF,
  3770. atan: PF,
  3771. atan2: PF,
  3772. atanh: PF,
  3773. cbrt: PF,
  3774. ceil: PF,
  3775. clz32: PF,
  3776. cos: PF,
  3777. cosh: PF,
  3778. exp: PF,
  3779. expm1: PF,
  3780. floor: PF,
  3781. fround: PF,
  3782. hypot: PF,
  3783. imul: PF,
  3784. log: PF,
  3785. log10: PF,
  3786. log1p: PF,
  3787. log2: PF,
  3788. max: PF,
  3789. min: PF,
  3790. pow: PF,
  3791. random: PF,
  3792. round: PF,
  3793. sign: PF,
  3794. sin: PF,
  3795. sinh: PF,
  3796. sqrt: PF,
  3797. tan: PF,
  3798. tanh: PF,
  3799. trunc: PF
  3800. },
  3801. NaN: O,
  3802. Number: {
  3803. __proto__: null,
  3804. [ValueProperties]: PURE,
  3805. isFinite: PF,
  3806. isInteger: PF,
  3807. isNaN: PF,
  3808. isSafeInteger: PF,
  3809. parseFloat: PF,
  3810. parseInt: PF,
  3811. prototype: O
  3812. },
  3813. Object: {
  3814. __proto__: null,
  3815. [ValueProperties]: PURE,
  3816. create: PF,
  3817. // Technically those can throw in certain situations, but we ignore this as
  3818. // code that relies on this will hopefully wrap this in a try-catch, which
  3819. // deoptimizes everything anyway
  3820. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  3821. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  3822. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  3823. getOwnPropertyDescriptor: PF,
  3824. getOwnPropertyDescriptors: PF,
  3825. getOwnPropertyNames: PF,
  3826. getOwnPropertySymbols: PF,
  3827. getPrototypeOf: PF,
  3828. hasOwn: PF,
  3829. is: PF,
  3830. isExtensible: PF,
  3831. isFrozen: PF,
  3832. isSealed: PF,
  3833. keys: PF,
  3834. fromEntries: O,
  3835. entries: PF_NO_GETTER,
  3836. values: PF_NO_GETTER,
  3837. prototype: O
  3838. },
  3839. parseFloat: PF,
  3840. parseInt: PF,
  3841. Promise: {
  3842. __proto__: null,
  3843. [ValueProperties]: IMPURE,
  3844. all: O,
  3845. allSettled: O,
  3846. any: O,
  3847. prototype: O,
  3848. race: O,
  3849. reject: O,
  3850. resolve: O
  3851. },
  3852. propertyIsEnumerable: O,
  3853. Proxy: {
  3854. __proto__: null,
  3855. [ValueProperties]: {
  3856. deoptimizeArgumentsOnCall: ({ args: [, target, parameter] }) => {
  3857. if (isObjectExpressionNode(parameter)) {
  3858. const hasSpreadElement = parameter.properties.some(property => !isPropertyNode(property));
  3859. if (!hasSpreadElement) {
  3860. for (const property of parameter.properties) {
  3861. property.deoptimizeArgumentsOnInteractionAtPath({
  3862. args: [null, target],
  3863. type: INTERACTION_CALLED,
  3864. withNew: false
  3865. }, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  3866. }
  3867. return;
  3868. }
  3869. }
  3870. target.deoptimizePath(UNKNOWN_PATH);
  3871. },
  3872. getLiteralValue: getUnknownValue,
  3873. hasEffectsWhenCalled: returnTrue
  3874. }
  3875. },
  3876. RangeError: PC,
  3877. ReferenceError: PC,
  3878. Reflect: O,
  3879. RegExp: PC,
  3880. Set: PC_WITH_ARRAY,
  3881. SharedArrayBuffer: C,
  3882. String: {
  3883. __proto__: null,
  3884. [ValueProperties]: PURE,
  3885. fromCharCode: PF,
  3886. fromCodePoint: PF,
  3887. prototype: O,
  3888. raw: PF
  3889. },
  3890. Symbol: {
  3891. __proto__: null,
  3892. [ValueProperties]: PURE,
  3893. for: PF,
  3894. keyFor: PF,
  3895. prototype: O,
  3896. toStringTag: {
  3897. __proto__: null,
  3898. [ValueProperties]: {
  3899. deoptimizeArgumentsOnCall: doNothing,
  3900. getLiteralValue() {
  3901. return SymbolToStringTag;
  3902. },
  3903. hasEffectsWhenCalled: returnTrue
  3904. }
  3905. }
  3906. },
  3907. SyntaxError: PC,
  3908. toLocaleString: O,
  3909. toString: O,
  3910. TypeError: PC,
  3911. Uint16Array: ARRAY_TYPE,
  3912. Uint32Array: ARRAY_TYPE,
  3913. Uint8Array: ARRAY_TYPE,
  3914. Uint8ClampedArray: ARRAY_TYPE,
  3915. // Technically, this is a global, but it needs special handling
  3916. // undefined: ?,
  3917. unescape: PF,
  3918. URIError: PC,
  3919. valueOf: O,
  3920. WeakMap: PC_WITH_ARRAY,
  3921. WeakRef: C,
  3922. WeakSet: PC_WITH_ARRAY,
  3923. // Additional globals shared by Node and Browser that are not strictly part of the language
  3924. clearInterval: C,
  3925. clearTimeout: C,
  3926. console: {
  3927. __proto__: null,
  3928. [ValueProperties]: IMPURE,
  3929. assert: C,
  3930. clear: C,
  3931. count: C,
  3932. countReset: C,
  3933. debug: C,
  3934. dir: C,
  3935. dirxml: C,
  3936. error: C,
  3937. exception: C,
  3938. group: C,
  3939. groupCollapsed: C,
  3940. groupEnd: C,
  3941. info: C,
  3942. log: C,
  3943. table: C,
  3944. time: C,
  3945. timeEnd: C,
  3946. timeLog: C,
  3947. trace: C,
  3948. warn: C
  3949. },
  3950. Intl: {
  3951. __proto__: null,
  3952. [ValueProperties]: IMPURE,
  3953. Collator: INTL_MEMBER,
  3954. DateTimeFormat: INTL_MEMBER,
  3955. DisplayNames: INTL_MEMBER,
  3956. ListFormat: INTL_MEMBER,
  3957. Locale: INTL_MEMBER,
  3958. NumberFormat: INTL_MEMBER,
  3959. PluralRules: INTL_MEMBER,
  3960. RelativeTimeFormat: INTL_MEMBER,
  3961. Segmenter: INTL_MEMBER
  3962. },
  3963. setInterval: C,
  3964. setTimeout: C,
  3965. TextDecoder: C,
  3966. TextEncoder: C,
  3967. URL: {
  3968. __proto__: null,
  3969. [ValueProperties]: IMPURE,
  3970. prototype: O,
  3971. canParse: PF
  3972. },
  3973. URLSearchParams: C,
  3974. // Browser specific globals
  3975. AbortController: C,
  3976. AbortSignal: C,
  3977. addEventListener: O,
  3978. alert: O,
  3979. AnalyserNode: C,
  3980. Animation: C,
  3981. AnimationEvent: C,
  3982. applicationCache: O,
  3983. ApplicationCache: C,
  3984. ApplicationCacheErrorEvent: C,
  3985. atob: O,
  3986. Attr: C,
  3987. Audio: C,
  3988. AudioBuffer: C,
  3989. AudioBufferSourceNode: C,
  3990. AudioContext: C,
  3991. AudioDestinationNode: C,
  3992. AudioListener: C,
  3993. AudioNode: C,
  3994. AudioParam: C,
  3995. AudioProcessingEvent: C,
  3996. AudioScheduledSourceNode: C,
  3997. AudioWorkletNode: C,
  3998. BarProp: C,
  3999. BaseAudioContext: C,
  4000. BatteryManager: C,
  4001. BeforeUnloadEvent: C,
  4002. BiquadFilterNode: C,
  4003. Blob: C,
  4004. BlobEvent: C,
  4005. blur: O,
  4006. BroadcastChannel: C,
  4007. btoa: O,
  4008. ByteLengthQueuingStrategy: C,
  4009. Cache: C,
  4010. caches: O,
  4011. CacheStorage: C,
  4012. cancelAnimationFrame: O,
  4013. cancelIdleCallback: O,
  4014. CanvasCaptureMediaStreamTrack: C,
  4015. CanvasGradient: C,
  4016. CanvasPattern: C,
  4017. CanvasRenderingContext2D: C,
  4018. ChannelMergerNode: C,
  4019. ChannelSplitterNode: C,
  4020. CharacterData: C,
  4021. clientInformation: O,
  4022. ClipboardEvent: C,
  4023. close: O,
  4024. closed: O,
  4025. CloseEvent: C,
  4026. Comment: C,
  4027. CompositionEvent: C,
  4028. confirm: O,
  4029. ConstantSourceNode: C,
  4030. ConvolverNode: C,
  4031. CountQueuingStrategy: C,
  4032. createImageBitmap: O,
  4033. Credential: C,
  4034. CredentialsContainer: C,
  4035. crypto: O,
  4036. Crypto: C,
  4037. CryptoKey: C,
  4038. CSS: C,
  4039. CSSConditionRule: C,
  4040. CSSFontFaceRule: C,
  4041. CSSGroupingRule: C,
  4042. CSSImportRule: C,
  4043. CSSKeyframeRule: C,
  4044. CSSKeyframesRule: C,
  4045. CSSMediaRule: C,
  4046. CSSNamespaceRule: C,
  4047. CSSPageRule: C,
  4048. CSSRule: C,
  4049. CSSRuleList: C,
  4050. CSSStyleDeclaration: C,
  4051. CSSStyleRule: C,
  4052. CSSStyleSheet: C,
  4053. CSSSupportsRule: C,
  4054. CustomElementRegistry: C,
  4055. customElements: O,
  4056. CustomEvent: {
  4057. __proto__: null,
  4058. [ValueProperties]: {
  4059. deoptimizeArgumentsOnCall({ args }) {
  4060. args[2]?.deoptimizePath(['detail']);
  4061. },
  4062. getLiteralValue: getUnknownValue,
  4063. hasEffectsWhenCalled: returnFalse
  4064. },
  4065. prototype: O
  4066. },
  4067. DataTransfer: C,
  4068. DataTransferItem: C,
  4069. DataTransferItemList: C,
  4070. defaultstatus: O,
  4071. defaultStatus: O,
  4072. DelayNode: C,
  4073. DeviceMotionEvent: C,
  4074. DeviceOrientationEvent: C,
  4075. devicePixelRatio: O,
  4076. dispatchEvent: O,
  4077. document: O,
  4078. Document: C,
  4079. DocumentFragment: C,
  4080. DocumentType: C,
  4081. DOMError: C,
  4082. DOMException: C,
  4083. DOMImplementation: C,
  4084. DOMMatrix: C,
  4085. DOMMatrixReadOnly: C,
  4086. DOMParser: C,
  4087. DOMPoint: C,
  4088. DOMPointReadOnly: C,
  4089. DOMQuad: C,
  4090. DOMRect: C,
  4091. DOMRectReadOnly: C,
  4092. DOMStringList: C,
  4093. DOMStringMap: C,
  4094. DOMTokenList: C,
  4095. DragEvent: C,
  4096. DynamicsCompressorNode: C,
  4097. Element: C,
  4098. ErrorEvent: C,
  4099. Event: C,
  4100. EventSource: C,
  4101. EventTarget: C,
  4102. external: O,
  4103. fetch: O,
  4104. File: C,
  4105. FileList: C,
  4106. FileReader: C,
  4107. find: O,
  4108. focus: O,
  4109. FocusEvent: C,
  4110. FontFace: C,
  4111. FontFaceSetLoadEvent: C,
  4112. FormData: C,
  4113. frames: O,
  4114. GainNode: C,
  4115. Gamepad: C,
  4116. GamepadButton: C,
  4117. GamepadEvent: C,
  4118. getComputedStyle: O,
  4119. getSelection: O,
  4120. HashChangeEvent: C,
  4121. Headers: C,
  4122. history: O,
  4123. History: C,
  4124. HTMLAllCollection: C,
  4125. HTMLAnchorElement: C,
  4126. HTMLAreaElement: C,
  4127. HTMLAudioElement: C,
  4128. HTMLBaseElement: C,
  4129. HTMLBodyElement: C,
  4130. HTMLBRElement: C,
  4131. HTMLButtonElement: C,
  4132. HTMLCanvasElement: C,
  4133. HTMLCollection: C,
  4134. HTMLContentElement: C,
  4135. HTMLDataElement: C,
  4136. HTMLDataListElement: C,
  4137. HTMLDetailsElement: C,
  4138. HTMLDialogElement: C,
  4139. HTMLDirectoryElement: C,
  4140. HTMLDivElement: C,
  4141. HTMLDListElement: C,
  4142. HTMLDocument: C,
  4143. HTMLElement: C,
  4144. HTMLEmbedElement: C,
  4145. HTMLFieldSetElement: C,
  4146. HTMLFontElement: C,
  4147. HTMLFormControlsCollection: C,
  4148. HTMLFormElement: C,
  4149. HTMLFrameElement: C,
  4150. HTMLFrameSetElement: C,
  4151. HTMLHeadElement: C,
  4152. HTMLHeadingElement: C,
  4153. HTMLHRElement: C,
  4154. HTMLHtmlElement: C,
  4155. HTMLIFrameElement: C,
  4156. HTMLImageElement: C,
  4157. HTMLInputElement: C,
  4158. HTMLLabelElement: C,
  4159. HTMLLegendElement: C,
  4160. HTMLLIElement: C,
  4161. HTMLLinkElement: C,
  4162. HTMLMapElement: C,
  4163. HTMLMarqueeElement: C,
  4164. HTMLMediaElement: C,
  4165. HTMLMenuElement: C,
  4166. HTMLMetaElement: C,
  4167. HTMLMeterElement: C,
  4168. HTMLModElement: C,
  4169. HTMLObjectElement: C,
  4170. HTMLOListElement: C,
  4171. HTMLOptGroupElement: C,
  4172. HTMLOptionElement: C,
  4173. HTMLOptionsCollection: C,
  4174. HTMLOutputElement: C,
  4175. HTMLParagraphElement: C,
  4176. HTMLParamElement: C,
  4177. HTMLPictureElement: C,
  4178. HTMLPreElement: C,
  4179. HTMLProgressElement: C,
  4180. HTMLQuoteElement: C,
  4181. HTMLScriptElement: C,
  4182. HTMLSelectElement: C,
  4183. HTMLShadowElement: C,
  4184. HTMLSlotElement: C,
  4185. HTMLSourceElement: C,
  4186. HTMLSpanElement: C,
  4187. HTMLStyleElement: C,
  4188. HTMLTableCaptionElement: C,
  4189. HTMLTableCellElement: C,
  4190. HTMLTableColElement: C,
  4191. HTMLTableElement: C,
  4192. HTMLTableRowElement: C,
  4193. HTMLTableSectionElement: C,
  4194. HTMLTemplateElement: C,
  4195. HTMLTextAreaElement: C,
  4196. HTMLTimeElement: C,
  4197. HTMLTitleElement: C,
  4198. HTMLTrackElement: C,
  4199. HTMLUListElement: C,
  4200. HTMLUnknownElement: C,
  4201. HTMLVideoElement: C,
  4202. IDBCursor: C,
  4203. IDBCursorWithValue: C,
  4204. IDBDatabase: C,
  4205. IDBFactory: C,
  4206. IDBIndex: C,
  4207. IDBKeyRange: C,
  4208. IDBObjectStore: C,
  4209. IDBOpenDBRequest: C,
  4210. IDBRequest: C,
  4211. IDBTransaction: C,
  4212. IDBVersionChangeEvent: C,
  4213. IdleDeadline: C,
  4214. IIRFilterNode: C,
  4215. Image: C,
  4216. ImageBitmap: C,
  4217. ImageBitmapRenderingContext: C,
  4218. ImageCapture: C,
  4219. ImageData: C,
  4220. indexedDB: O,
  4221. innerHeight: O,
  4222. innerWidth: O,
  4223. InputEvent: C,
  4224. IntersectionObserver: C,
  4225. IntersectionObserverEntry: C,
  4226. isSecureContext: O,
  4227. KeyboardEvent: C,
  4228. KeyframeEffect: C,
  4229. length: O,
  4230. localStorage: O,
  4231. location: O,
  4232. Location: C,
  4233. locationbar: O,
  4234. matchMedia: O,
  4235. MediaDeviceInfo: C,
  4236. MediaDevices: C,
  4237. MediaElementAudioSourceNode: C,
  4238. MediaEncryptedEvent: C,
  4239. MediaError: C,
  4240. MediaKeyMessageEvent: C,
  4241. MediaKeySession: C,
  4242. MediaKeyStatusMap: C,
  4243. MediaKeySystemAccess: C,
  4244. MediaList: C,
  4245. MediaQueryList: C,
  4246. MediaQueryListEvent: C,
  4247. MediaRecorder: C,
  4248. MediaSettingsRange: C,
  4249. MediaSource: C,
  4250. MediaStream: C,
  4251. MediaStreamAudioDestinationNode: C,
  4252. MediaStreamAudioSourceNode: C,
  4253. MediaStreamEvent: C,
  4254. MediaStreamTrack: C,
  4255. MediaStreamTrackEvent: C,
  4256. menubar: O,
  4257. MessageChannel: C,
  4258. MessageEvent: C,
  4259. MessagePort: C,
  4260. MIDIAccess: C,
  4261. MIDIConnectionEvent: C,
  4262. MIDIInput: C,
  4263. MIDIInputMap: C,
  4264. MIDIMessageEvent: C,
  4265. MIDIOutput: C,
  4266. MIDIOutputMap: C,
  4267. MIDIPort: C,
  4268. MimeType: C,
  4269. MimeTypeArray: C,
  4270. MouseEvent: C,
  4271. moveBy: O,
  4272. moveTo: O,
  4273. MutationEvent: C,
  4274. MutationObserver: C,
  4275. MutationRecord: C,
  4276. name: O,
  4277. NamedNodeMap: C,
  4278. NavigationPreloadManager: C,
  4279. navigator: O,
  4280. Navigator: C,
  4281. NetworkInformation: C,
  4282. Node: C,
  4283. NodeFilter: O,
  4284. NodeIterator: C,
  4285. NodeList: C,
  4286. Notification: C,
  4287. OfflineAudioCompletionEvent: C,
  4288. OfflineAudioContext: C,
  4289. offscreenBuffering: O,
  4290. OffscreenCanvas: C,
  4291. open: O,
  4292. openDatabase: O,
  4293. Option: C,
  4294. origin: O,
  4295. OscillatorNode: C,
  4296. outerHeight: O,
  4297. outerWidth: O,
  4298. PageTransitionEvent: C,
  4299. pageXOffset: O,
  4300. pageYOffset: O,
  4301. PannerNode: C,
  4302. parent: O,
  4303. Path2D: C,
  4304. PaymentAddress: C,
  4305. PaymentRequest: C,
  4306. PaymentRequestUpdateEvent: C,
  4307. PaymentResponse: C,
  4308. performance: O,
  4309. Performance: C,
  4310. PerformanceEntry: C,
  4311. PerformanceLongTaskTiming: C,
  4312. PerformanceMark: C,
  4313. PerformanceMeasure: C,
  4314. PerformanceNavigation: C,
  4315. PerformanceNavigationTiming: C,
  4316. PerformanceObserver: C,
  4317. PerformanceObserverEntryList: C,
  4318. PerformancePaintTiming: C,
  4319. PerformanceResourceTiming: C,
  4320. PerformanceTiming: C,
  4321. PeriodicWave: C,
  4322. Permissions: C,
  4323. PermissionStatus: C,
  4324. personalbar: O,
  4325. PhotoCapabilities: C,
  4326. Plugin: C,
  4327. PluginArray: C,
  4328. PointerEvent: C,
  4329. PopStateEvent: C,
  4330. postMessage: O,
  4331. Presentation: C,
  4332. PresentationAvailability: C,
  4333. PresentationConnection: C,
  4334. PresentationConnectionAvailableEvent: C,
  4335. PresentationConnectionCloseEvent: C,
  4336. PresentationConnectionList: C,
  4337. PresentationReceiver: C,
  4338. PresentationRequest: C,
  4339. print: O,
  4340. ProcessingInstruction: C,
  4341. ProgressEvent: C,
  4342. PromiseRejectionEvent: C,
  4343. prompt: O,
  4344. PushManager: C,
  4345. PushSubscription: C,
  4346. PushSubscriptionOptions: C,
  4347. queueMicrotask: O,
  4348. RadioNodeList: C,
  4349. Range: C,
  4350. ReadableStream: C,
  4351. RemotePlayback: C,
  4352. removeEventListener: O,
  4353. Request: C,
  4354. requestAnimationFrame: O,
  4355. requestIdleCallback: O,
  4356. resizeBy: O,
  4357. ResizeObserver: C,
  4358. ResizeObserverEntry: C,
  4359. resizeTo: O,
  4360. Response: C,
  4361. RTCCertificate: C,
  4362. RTCDataChannel: C,
  4363. RTCDataChannelEvent: C,
  4364. RTCDtlsTransport: C,
  4365. RTCIceCandidate: C,
  4366. RTCIceTransport: C,
  4367. RTCPeerConnection: C,
  4368. RTCPeerConnectionIceEvent: C,
  4369. RTCRtpReceiver: C,
  4370. RTCRtpSender: C,
  4371. RTCSctpTransport: C,
  4372. RTCSessionDescription: C,
  4373. RTCStatsReport: C,
  4374. RTCTrackEvent: C,
  4375. screen: O,
  4376. Screen: C,
  4377. screenLeft: O,
  4378. ScreenOrientation: C,
  4379. screenTop: O,
  4380. screenX: O,
  4381. screenY: O,
  4382. ScriptProcessorNode: C,
  4383. scroll: O,
  4384. scrollbars: O,
  4385. scrollBy: O,
  4386. scrollTo: O,
  4387. scrollX: O,
  4388. scrollY: O,
  4389. SecurityPolicyViolationEvent: C,
  4390. Selection: C,
  4391. ServiceWorker: C,
  4392. ServiceWorkerContainer: C,
  4393. ServiceWorkerRegistration: C,
  4394. sessionStorage: O,
  4395. ShadowRoot: C,
  4396. SharedWorker: C,
  4397. SourceBuffer: C,
  4398. SourceBufferList: C,
  4399. speechSynthesis: O,
  4400. SpeechSynthesisEvent: C,
  4401. SpeechSynthesisUtterance: C,
  4402. StaticRange: C,
  4403. status: O,
  4404. statusbar: O,
  4405. StereoPannerNode: C,
  4406. stop: O,
  4407. Storage: C,
  4408. StorageEvent: C,
  4409. StorageManager: C,
  4410. styleMedia: O,
  4411. StyleSheet: C,
  4412. StyleSheetList: C,
  4413. SubtleCrypto: C,
  4414. SVGAElement: C,
  4415. SVGAngle: C,
  4416. SVGAnimatedAngle: C,
  4417. SVGAnimatedBoolean: C,
  4418. SVGAnimatedEnumeration: C,
  4419. SVGAnimatedInteger: C,
  4420. SVGAnimatedLength: C,
  4421. SVGAnimatedLengthList: C,
  4422. SVGAnimatedNumber: C,
  4423. SVGAnimatedNumberList: C,
  4424. SVGAnimatedPreserveAspectRatio: C,
  4425. SVGAnimatedRect: C,
  4426. SVGAnimatedString: C,
  4427. SVGAnimatedTransformList: C,
  4428. SVGAnimateElement: C,
  4429. SVGAnimateMotionElement: C,
  4430. SVGAnimateTransformElement: C,
  4431. SVGAnimationElement: C,
  4432. SVGCircleElement: C,
  4433. SVGClipPathElement: C,
  4434. SVGComponentTransferFunctionElement: C,
  4435. SVGDefsElement: C,
  4436. SVGDescElement: C,
  4437. SVGDiscardElement: C,
  4438. SVGElement: C,
  4439. SVGEllipseElement: C,
  4440. SVGFEBlendElement: C,
  4441. SVGFEColorMatrixElement: C,
  4442. SVGFEComponentTransferElement: C,
  4443. SVGFECompositeElement: C,
  4444. SVGFEConvolveMatrixElement: C,
  4445. SVGFEDiffuseLightingElement: C,
  4446. SVGFEDisplacementMapElement: C,
  4447. SVGFEDistantLightElement: C,
  4448. SVGFEDropShadowElement: C,
  4449. SVGFEFloodElement: C,
  4450. SVGFEFuncAElement: C,
  4451. SVGFEFuncBElement: C,
  4452. SVGFEFuncGElement: C,
  4453. SVGFEFuncRElement: C,
  4454. SVGFEGaussianBlurElement: C,
  4455. SVGFEImageElement: C,
  4456. SVGFEMergeElement: C,
  4457. SVGFEMergeNodeElement: C,
  4458. SVGFEMorphologyElement: C,
  4459. SVGFEOffsetElement: C,
  4460. SVGFEPointLightElement: C,
  4461. SVGFESpecularLightingElement: C,
  4462. SVGFESpotLightElement: C,
  4463. SVGFETileElement: C,
  4464. SVGFETurbulenceElement: C,
  4465. SVGFilterElement: C,
  4466. SVGForeignObjectElement: C,
  4467. SVGGElement: C,
  4468. SVGGeometryElement: C,
  4469. SVGGradientElement: C,
  4470. SVGGraphicsElement: C,
  4471. SVGImageElement: C,
  4472. SVGLength: C,
  4473. SVGLengthList: C,
  4474. SVGLinearGradientElement: C,
  4475. SVGLineElement: C,
  4476. SVGMarkerElement: C,
  4477. SVGMaskElement: C,
  4478. SVGMatrix: C,
  4479. SVGMetadataElement: C,
  4480. SVGMPathElement: C,
  4481. SVGNumber: C,
  4482. SVGNumberList: C,
  4483. SVGPathElement: C,
  4484. SVGPatternElement: C,
  4485. SVGPoint: C,
  4486. SVGPointList: C,
  4487. SVGPolygonElement: C,
  4488. SVGPolylineElement: C,
  4489. SVGPreserveAspectRatio: C,
  4490. SVGRadialGradientElement: C,
  4491. SVGRect: C,
  4492. SVGRectElement: C,
  4493. SVGScriptElement: C,
  4494. SVGSetElement: C,
  4495. SVGStopElement: C,
  4496. SVGStringList: C,
  4497. SVGStyleElement: C,
  4498. SVGSVGElement: C,
  4499. SVGSwitchElement: C,
  4500. SVGSymbolElement: C,
  4501. SVGTextContentElement: C,
  4502. SVGTextElement: C,
  4503. SVGTextPathElement: C,
  4504. SVGTextPositioningElement: C,
  4505. SVGTitleElement: C,
  4506. SVGTransform: C,
  4507. SVGTransformList: C,
  4508. SVGTSpanElement: C,
  4509. SVGUnitTypes: C,
  4510. SVGUseElement: C,
  4511. SVGViewElement: C,
  4512. TaskAttributionTiming: C,
  4513. Text: C,
  4514. TextEvent: C,
  4515. TextMetrics: C,
  4516. TextTrack: C,
  4517. TextTrackCue: C,
  4518. TextTrackCueList: C,
  4519. TextTrackList: C,
  4520. TimeRanges: C,
  4521. toolbar: O,
  4522. top: O,
  4523. Touch: C,
  4524. TouchEvent: C,
  4525. TouchList: C,
  4526. TrackEvent: C,
  4527. TransitionEvent: C,
  4528. TreeWalker: C,
  4529. UIEvent: C,
  4530. ValidityState: C,
  4531. visualViewport: O,
  4532. VisualViewport: C,
  4533. VTTCue: C,
  4534. WaveShaperNode: C,
  4535. WebAssembly: O,
  4536. WebGL2RenderingContext: C,
  4537. WebGLActiveInfo: C,
  4538. WebGLBuffer: C,
  4539. WebGLContextEvent: C,
  4540. WebGLFramebuffer: C,
  4541. WebGLProgram: C,
  4542. WebGLQuery: C,
  4543. WebGLRenderbuffer: C,
  4544. WebGLRenderingContext: C,
  4545. WebGLSampler: C,
  4546. WebGLShader: C,
  4547. WebGLShaderPrecisionFormat: C,
  4548. WebGLSync: C,
  4549. WebGLTexture: C,
  4550. WebGLTransformFeedback: C,
  4551. WebGLUniformLocation: C,
  4552. WebGLVertexArrayObject: C,
  4553. WebSocket: C,
  4554. WheelEvent: C,
  4555. Window: C,
  4556. Worker: C,
  4557. WritableStream: C,
  4558. XMLDocument: C,
  4559. XMLHttpRequest: C,
  4560. XMLHttpRequestEventTarget: C,
  4561. XMLHttpRequestUpload: C,
  4562. XMLSerializer: C,
  4563. XPathEvaluator: C,
  4564. XPathExpression: C,
  4565. XPathResult: C,
  4566. XSLTProcessor: C
  4567. };
  4568. for (const global of ['window', 'global', 'self', 'globalThis']) {
  4569. knownGlobals[global] = knownGlobals;
  4570. }
  4571. function getGlobalAtPath(path) {
  4572. let currentGlobal = knownGlobals;
  4573. for (const pathSegment of path) {
  4574. if (typeof pathSegment !== 'string') {
  4575. return null;
  4576. }
  4577. currentGlobal = currentGlobal[pathSegment];
  4578. if (!currentGlobal) {
  4579. return null;
  4580. }
  4581. }
  4582. return currentGlobal[ValueProperties];
  4583. }
  4584. class GlobalVariable extends Variable {
  4585. constructor(name) {
  4586. super(name);
  4587. // Ensure we use live-bindings for globals as we do not know if they have
  4588. // been reassigned
  4589. this.markReassigned();
  4590. }
  4591. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4592. switch (interaction.type) {
  4593. // While there is no point in testing these cases as at the moment, they
  4594. // are also covered via other means, we keep them for completeness
  4595. case INTERACTION_ACCESSED:
  4596. case INTERACTION_ASSIGNED: {
  4597. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  4598. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4599. }
  4600. return;
  4601. }
  4602. case INTERACTION_CALLED: {
  4603. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4604. if (globalAtPath) {
  4605. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  4606. }
  4607. else {
  4608. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4609. }
  4610. return;
  4611. }
  4612. }
  4613. }
  4614. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  4615. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4616. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  4617. }
  4618. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4619. switch (interaction.type) {
  4620. case INTERACTION_ACCESSED: {
  4621. if (path.length === 0) {
  4622. // Technically, "undefined" is a global variable of sorts
  4623. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  4624. }
  4625. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  4626. }
  4627. case INTERACTION_ASSIGNED: {
  4628. return true;
  4629. }
  4630. case INTERACTION_CALLED: {
  4631. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4632. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  4633. }
  4634. }
  4635. }
  4636. }
  4637. // To avoid infinite recursions
  4638. const MAX_PATH_DEPTH = 6;
  4639. // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
  4640. // most MAX_PATH_DEPTH long. The last element is always UnknownKey
  4641. const limitConcatenatedPathDepth = (path1, path2) => {
  4642. const { length: length1 } = path1;
  4643. const { length: length2 } = path2;
  4644. return length1 === 0
  4645. ? path2
  4646. : length2 === 0
  4647. ? path1
  4648. : length1 + length2 > MAX_PATH_DEPTH
  4649. ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
  4650. : [...path1, ...path2];
  4651. };
  4652. class LocalVariable extends Variable {
  4653. constructor(name, declarator, init,
  4654. /** if this is non-empty, the actual init is this path of this.init */
  4655. initPath, context, kind) {
  4656. super(name);
  4657. this.init = init;
  4658. this.initPath = initPath;
  4659. this.kind = kind;
  4660. this.calledFromTryStatement = false;
  4661. this.additionalInitializers = null;
  4662. this.includedPathTracker = new IncludedFullPathTracker();
  4663. this.expressionsToBeDeoptimized = [];
  4664. this.declarations = declarator ? [declarator] : [];
  4665. this.deoptimizationTracker = context.deoptimizationTracker;
  4666. this.module = context.module;
  4667. }
  4668. addDeclaration(identifier, init) {
  4669. this.declarations.push(identifier);
  4670. this.markInitializersForDeoptimization().push(init);
  4671. }
  4672. consolidateInitializers() {
  4673. if (this.additionalInitializers) {
  4674. for (const initializer of this.additionalInitializers) {
  4675. initializer.deoptimizePath(UNKNOWN_PATH);
  4676. }
  4677. }
  4678. }
  4679. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4680. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4681. deoptimizeInteraction(interaction);
  4682. return;
  4683. }
  4684. recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4685. this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], recursionTracker);
  4686. }, undefined);
  4687. }
  4688. deoptimizePath(path) {
  4689. if (this.isReassigned ||
  4690. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  4691. return;
  4692. }
  4693. if (path.length === 0) {
  4694. this.markReassigned();
  4695. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  4696. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  4697. for (const expression of expressionsToBeDeoptimized) {
  4698. expression.deoptimizeCache();
  4699. }
  4700. this.init.deoptimizePath([...this.initPath, UnknownKey]);
  4701. }
  4702. else {
  4703. this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
  4704. }
  4705. }
  4706. getLiteralValueAtPath(path, recursionTracker, origin) {
  4707. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4708. return UnknownValue;
  4709. }
  4710. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4711. this.expressionsToBeDeoptimized.push(origin);
  4712. return this.init.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin);
  4713. }, UnknownValue);
  4714. }
  4715. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4716. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4717. return UNKNOWN_RETURN_EXPRESSION;
  4718. }
  4719. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4720. this.expressionsToBeDeoptimized.push(origin);
  4721. return this.init.getReturnExpressionWhenCalledAtPath([...this.initPath, ...path], interaction, recursionTracker, origin);
  4722. }, UNKNOWN_RETURN_EXPRESSION);
  4723. }
  4724. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4725. if (path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4726. return true;
  4727. }
  4728. switch (interaction.type) {
  4729. case INTERACTION_ACCESSED: {
  4730. if (this.isReassigned)
  4731. return true;
  4732. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  4733. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4734. }
  4735. case INTERACTION_ASSIGNED: {
  4736. if (this.included)
  4737. return true;
  4738. if (path.length === 0)
  4739. return false;
  4740. if (this.isReassigned)
  4741. return true;
  4742. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  4743. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4744. }
  4745. case INTERACTION_CALLED: {
  4746. if (this.isReassigned)
  4747. return true;
  4748. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  4749. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4750. }
  4751. }
  4752. }
  4753. includePath(path, context) {
  4754. if (!this.includedPathTracker.includePathAndGetIfIncluded(path)) {
  4755. this.module.scope.context.requestTreeshakingPass();
  4756. if (!this.included) {
  4757. // This will reduce the number of tree-shaking passes by eagerly
  4758. // including inits. By pushing this here instead of directly including
  4759. // we avoid deep call stacks.
  4760. this.module.scope.context.newlyIncludedVariableInits.add(this.init);
  4761. }
  4762. super.includePath(path, context);
  4763. for (const declaration of this.declarations) {
  4764. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  4765. if (!declaration.included)
  4766. declaration.include(context, false);
  4767. let node = declaration.parent;
  4768. while (!node.included) {
  4769. // We do not want to properly include parents in case they are part of a dead branch
  4770. // in which case .include() might pull in more dead code
  4771. node.includeNode(context);
  4772. if (node.type === Program$1)
  4773. break;
  4774. node = node.parent;
  4775. }
  4776. /**
  4777. * import('foo').then(m => {
  4778. * console.log(m.foo)
  4779. * })
  4780. */
  4781. if (this.kind === 'parameter' &&
  4782. (isArrowFunctionExpressionNode(declaration.parent) ||
  4783. isFunctionExpressionNode(declaration.parent)) &&
  4784. isCallExpressionNode(declaration.parent.parent) &&
  4785. isMemberExpressionNode(declaration.parent.parent.callee) &&
  4786. isIdentifierNode(declaration.parent.parent.callee.property) &&
  4787. declaration.parent.parent.callee.property.name === 'then' &&
  4788. isImportExpressionNode(declaration.parent.parent.callee.object)) {
  4789. declaration.parent.parent.callee.object.includePath(path, context);
  4790. }
  4791. }
  4792. // We need to make sure we include the correct path of the init
  4793. if (path.length > 0) {
  4794. this.init.includePath(limitConcatenatedPathDepth(this.initPath, path), context);
  4795. this.additionalInitializers?.forEach(initializer => initializer.includePath(UNKNOWN_PATH, context));
  4796. }
  4797. }
  4798. }
  4799. includeCallArguments(interaction, context) {
  4800. if (this.isReassigned ||
  4801. context.includedCallArguments.has(this.init) ||
  4802. // This can be removed again once we can include arguments when called at
  4803. // a specific path
  4804. this.initPath.length > 0) {
  4805. includeInteraction(interaction, context);
  4806. }
  4807. else {
  4808. context.includedCallArguments.add(this.init);
  4809. this.init.includeCallArguments(interaction, context);
  4810. context.includedCallArguments.delete(this.init);
  4811. }
  4812. }
  4813. markCalledFromTryStatement() {
  4814. this.calledFromTryStatement = true;
  4815. }
  4816. markInitializersForDeoptimization() {
  4817. if (this.additionalInitializers === null) {
  4818. this.additionalInitializers = [this.init];
  4819. this.init = UNKNOWN_EXPRESSION;
  4820. this.markReassigned();
  4821. }
  4822. return this.additionalInitializers;
  4823. }
  4824. }
  4825. const tdzVariableKinds = new Set(['class', 'const', 'let', 'var', 'using', 'await using']);
  4826. class IdentifierBase extends NodeBase {
  4827. constructor() {
  4828. super(...arguments);
  4829. this.variable = null;
  4830. this.isVariableReference = false;
  4831. }
  4832. get isTDZAccess() {
  4833. if (!isFlagSet(this.flags, 4 /* Flag.tdzAccessDefined */)) {
  4834. return null;
  4835. }
  4836. return isFlagSet(this.flags, 8 /* Flag.tdzAccess */);
  4837. }
  4838. set isTDZAccess(value) {
  4839. this.flags = setFlag(this.flags, 4 /* Flag.tdzAccessDefined */, true);
  4840. this.flags = setFlag(this.flags, 8 /* Flag.tdzAccess */, value);
  4841. }
  4842. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4843. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4844. }
  4845. deoptimizePath(path) {
  4846. if (path.length === 0 && !this.scope.contains(this.name)) {
  4847. this.disallowImportReassignment();
  4848. }
  4849. // We keep conditional chaining because an unknown Node could have an
  4850. // Identifier as property that might be deoptimized by default
  4851. this.variable?.deoptimizePath(path);
  4852. }
  4853. getLiteralValueAtPath(path, recursionTracker, origin) {
  4854. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  4855. }
  4856. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4857. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4858. return [expression, isPure || this.isPureFunction(path)];
  4859. }
  4860. hasEffects(context) {
  4861. if (!this.deoptimized)
  4862. this.applyDeoptimizations();
  4863. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  4864. return true;
  4865. }
  4866. return (this.scope.context.options.treeshake
  4867. .unknownGlobalSideEffects &&
  4868. this.variable instanceof GlobalVariable &&
  4869. !this.isPureFunction(EMPTY_PATH) &&
  4870. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  4871. }
  4872. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4873. switch (interaction.type) {
  4874. case INTERACTION_ACCESSED: {
  4875. return (this.variable !== null &&
  4876. !this.isPureFunction(path) &&
  4877. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  4878. }
  4879. case INTERACTION_ASSIGNED: {
  4880. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  4881. }
  4882. case INTERACTION_CALLED: {
  4883. return (!this.isPureFunction(path) &&
  4884. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  4885. }
  4886. }
  4887. }
  4888. include(context, includeChildrenRecursively) {
  4889. if (!this.included)
  4890. this.includeNode(context);
  4891. if (includeChildrenRecursively) {
  4892. this.variable?.includePath(UNKNOWN_PATH, context);
  4893. }
  4894. }
  4895. includeNode(context) {
  4896. this.included = true;
  4897. if (!this.deoptimized)
  4898. this.applyDeoptimizations();
  4899. if (this.variable !== null) {
  4900. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  4901. }
  4902. }
  4903. includePath(path, context) {
  4904. if (!this.included) {
  4905. this.included = true;
  4906. if (!this.deoptimized)
  4907. this.applyDeoptimizations();
  4908. if (this.variable !== null) {
  4909. this.scope.context.includeVariableInModule(this.variable, path, context);
  4910. }
  4911. }
  4912. else if (path.length > 0) {
  4913. this.variable?.includePath(path, context);
  4914. }
  4915. }
  4916. includeCallArguments(interaction, context) {
  4917. this.variable.includeCallArguments(interaction, context);
  4918. }
  4919. isPossibleTDZ() {
  4920. // return cached value to avoid issues with the next tree-shaking pass
  4921. const cachedTdzAccess = this.isTDZAccess;
  4922. if (cachedTdzAccess !== null)
  4923. return cachedTdzAccess;
  4924. if (!(this.variable instanceof LocalVariable &&
  4925. this.variable.kind &&
  4926. tdzVariableKinds.has(this.variable.kind) &&
  4927. // We ignore modules that did not receive a treeshaking pass yet as that
  4928. // causes many false positives due to circular dependencies or disabled
  4929. // moduleSideEffects.
  4930. this.variable.module.hasTreeShakingPassStarted)) {
  4931. return (this.isTDZAccess = false);
  4932. }
  4933. let decl_id;
  4934. if (this.variable.declarations &&
  4935. this.variable.declarations.length === 1 &&
  4936. (decl_id = this.variable.declarations[0]) &&
  4937. this.start < decl_id.start &&
  4938. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  4939. // a variable accessed before its declaration
  4940. // in the same function or at top level of module
  4941. return (this.isTDZAccess = true);
  4942. }
  4943. if (!this.variable.initReached) {
  4944. // Either a const/let TDZ violation or
  4945. // var use before declaration was encountered.
  4946. return (this.isTDZAccess = true);
  4947. }
  4948. return (this.isTDZAccess = false);
  4949. }
  4950. applyDeoptimizations() {
  4951. this.deoptimized = true;
  4952. if (this.variable instanceof LocalVariable) {
  4953. // When accessing a variable from a module without side effects, this
  4954. // means we use an export of that module and therefore need to potentially
  4955. // include it in the bundle.
  4956. if (!this.variable.module.isExecuted) {
  4957. markModuleAndImpureDependenciesAsExecuted(this.variable.module);
  4958. }
  4959. this.variable.consolidateInitializers();
  4960. this.scope.context.requestTreeshakingPass();
  4961. }
  4962. if (this.isVariableReference) {
  4963. this.variable.addUsedPlace(this);
  4964. this.scope.context.requestTreeshakingPass();
  4965. }
  4966. }
  4967. disallowImportReassignment() {
  4968. return this.scope.context.error(logIllegalImportReassignment(this.name, this.scope.context.module.id), this.start);
  4969. }
  4970. getVariableRespectingTDZ() {
  4971. if (this.isPossibleTDZ()) {
  4972. return UNKNOWN_EXPRESSION;
  4973. }
  4974. return this.variable;
  4975. }
  4976. isPureFunction(path) {
  4977. let currentPureFunction = this.scope.context.manualPureFunctions[this.name];
  4978. for (const segment of path) {
  4979. if (currentPureFunction) {
  4980. if (currentPureFunction[PureFunctionKey]) {
  4981. return true;
  4982. }
  4983. currentPureFunction = currentPureFunction[segment];
  4984. }
  4985. else {
  4986. return false;
  4987. }
  4988. }
  4989. return currentPureFunction?.[PureFunctionKey];
  4990. }
  4991. }
  4992. function closestParentFunctionOrProgram(node) {
  4993. while (node && !/^Program|Function/.test(node.type)) {
  4994. node = node.parent;
  4995. }
  4996. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  4997. return node;
  4998. }
  4999. class ObjectMember extends ExpressionEntity {
  5000. constructor(object, path) {
  5001. super();
  5002. this.object = object;
  5003. this.path = path;
  5004. }
  5005. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5006. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.path, ...path], recursionTracker);
  5007. }
  5008. deoptimizePath(path) {
  5009. this.object.deoptimizePath([...this.path, ...path]);
  5010. }
  5011. getLiteralValueAtPath(path, recursionTracker, origin) {
  5012. return this.object.getLiteralValueAtPath([...this.path, ...path], recursionTracker, origin);
  5013. }
  5014. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5015. return this.object.getReturnExpressionWhenCalledAtPath([...this.path, ...path], interaction, recursionTracker, origin);
  5016. }
  5017. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5018. return this.object.hasEffectsOnInteractionAtPath([...this.path, ...path], interaction, context);
  5019. }
  5020. }
  5021. class Identifier extends IdentifierBase {
  5022. constructor() {
  5023. super(...arguments);
  5024. this.variable = null;
  5025. }
  5026. get isDestructuringDeoptimized() {
  5027. return isFlagSet(this.flags, 16777216 /* Flag.destructuringDeoptimized */);
  5028. }
  5029. set isDestructuringDeoptimized(value) {
  5030. this.flags = setFlag(this.flags, 16777216 /* Flag.destructuringDeoptimized */, value);
  5031. }
  5032. addExportedVariables(variables, exportNamesByVariable) {
  5033. if (exportNamesByVariable.has(this.variable)) {
  5034. variables.push(this.variable);
  5035. }
  5036. }
  5037. bind() {
  5038. if (!this.variable && is_reference(this, this.parent)) {
  5039. this.variable = this.scope.findVariable(this.name);
  5040. this.variable.addReference(this);
  5041. this.isVariableReference = true;
  5042. }
  5043. }
  5044. declare(kind, destructuredInitPath, init) {
  5045. let variable;
  5046. const { treeshake } = this.scope.context.options;
  5047. if (kind === 'parameter') {
  5048. variable = this.scope.addParameterDeclaration(this, destructuredInitPath);
  5049. }
  5050. else {
  5051. variable = this.scope.addDeclaration(this, this.scope.context, init, destructuredInitPath, kind);
  5052. if (kind === 'var' && treeshake && treeshake.correctVarValueBeforeDeclaration) {
  5053. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  5054. variable.markInitializersForDeoptimization();
  5055. }
  5056. }
  5057. return [(this.variable = variable)];
  5058. }
  5059. deoptimizeAssignment(destructuredInitPath, init) {
  5060. this.deoptimizePath(EMPTY_PATH);
  5061. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  5062. }
  5063. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  5064. return (destructuredInitPath.length > 0 &&
  5065. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  5066. }
  5067. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  5068. if (destructuredInitPath.length > 0 && !this.isDestructuringDeoptimized) {
  5069. this.isDestructuringDeoptimized = true;
  5070. init.deoptimizeArgumentsOnInteractionAtPath({
  5071. args: [new ObjectMember(init, destructuredInitPath.slice(0, -1))],
  5072. type: INTERACTION_ACCESSED
  5073. }, destructuredInitPath, SHARED_RECURSION_TRACKER);
  5074. }
  5075. const { propertyReadSideEffects } = this.scope.context.options
  5076. .treeshake;
  5077. let included = this.included;
  5078. if ((included ||=
  5079. destructuredInitPath.length > 0 &&
  5080. !context.brokenFlow &&
  5081. propertyReadSideEffects &&
  5082. (propertyReadSideEffects === 'always' ||
  5083. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext())))) {
  5084. if (this.variable && !this.variable.included) {
  5085. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  5086. }
  5087. init.includePath(destructuredInitPath, context);
  5088. }
  5089. if (!this.included && included) {
  5090. this.includeNode(context);
  5091. }
  5092. return this.included;
  5093. }
  5094. markDeclarationReached() {
  5095. this.variable.initReached = true;
  5096. }
  5097. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  5098. if (this.variable) {
  5099. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  5100. if (name !== this.name) {
  5101. code.overwrite(this.start, this.end, name, {
  5102. contentOnly: true,
  5103. storeName: true
  5104. });
  5105. if (isShorthandProperty) {
  5106. code.prependRight(this.start, `${this.name}: `);
  5107. }
  5108. }
  5109. // In strict mode, any variable named "eval" must be the actual "eval" function
  5110. if (name === 'eval' &&
  5111. renderedParentType === CallExpression$1 &&
  5112. isCalleeOfRenderedParent) {
  5113. code.appendRight(this.start, '0, ');
  5114. }
  5115. }
  5116. }
  5117. }
  5118. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  5119. const base = 64;
  5120. function toBase64(value) {
  5121. let outString = '';
  5122. do {
  5123. const currentDigit = value % base;
  5124. value = (value / base) | 0;
  5125. outString = chars[currentDigit] + outString;
  5126. } while (value !== 0);
  5127. return outString;
  5128. }
  5129. function getSafeName(baseName, usedNames, forbiddenNames) {
  5130. let safeName = baseName;
  5131. let count = 1;
  5132. while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
  5133. safeName = `${baseName}$${toBase64(count++)}`;
  5134. }
  5135. usedNames.add(safeName);
  5136. return safeName;
  5137. }
  5138. class Scope {
  5139. constructor() {
  5140. this.children = [];
  5141. this.variables = new Map();
  5142. }
  5143. /*
  5144. Redeclaration rules:
  5145. - var can redeclare var
  5146. - in function scopes, function and var can redeclare function and var
  5147. - var is hoisted across scopes, function remains in the scope it is declared
  5148. - var and function can redeclare function parameters, but parameters cannot redeclare parameters
  5149. - function cannot redeclare catch scope parameters
  5150. - var can redeclare catch scope parameters in a way
  5151. - if the parameter is an identifier and not a pattern
  5152. - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
  5153. - const, let, class, and function except in the cases above cannot redeclare anything
  5154. */
  5155. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5156. const name = identifier.name;
  5157. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5158. if (existingVariable) {
  5159. if (kind === 'var' && existingVariable.kind === 'var') {
  5160. existingVariable.addDeclaration(identifier, init);
  5161. return existingVariable;
  5162. }
  5163. context.error(logRedeclarationError(name), identifier.start);
  5164. }
  5165. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  5166. this.variables.set(name, newVariable);
  5167. return newVariable;
  5168. }
  5169. addHoistedVariable(name, variable) {
  5170. (this.hoistedVariables ||= new Map()).set(name, variable);
  5171. }
  5172. contains(name) {
  5173. return this.variables.has(name);
  5174. }
  5175. findVariable(_name) {
  5176. /* istanbul ignore next */
  5177. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  5178. }
  5179. }
  5180. class ChildScope extends Scope {
  5181. constructor(parent, context) {
  5182. super();
  5183. this.parent = parent;
  5184. this.context = context;
  5185. this.accessedOutsideVariables = new Map();
  5186. parent.children.push(this);
  5187. }
  5188. addAccessedDynamicImport(importExpression) {
  5189. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  5190. if (this.parent instanceof ChildScope) {
  5191. this.parent.addAccessedDynamicImport(importExpression);
  5192. }
  5193. }
  5194. addAccessedGlobals(globals, accessedGlobalsByScope) {
  5195. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  5196. for (const name of globals) {
  5197. accessedGlobals.add(name);
  5198. }
  5199. accessedGlobalsByScope.set(this, accessedGlobals);
  5200. if (this.parent instanceof ChildScope) {
  5201. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  5202. }
  5203. }
  5204. addNamespaceMemberAccess(name, variable) {
  5205. this.accessedOutsideVariables.set(name, variable);
  5206. this.parent.addNamespaceMemberAccess(name, variable);
  5207. }
  5208. addReturnExpression(expression) {
  5209. if (this.parent instanceof ChildScope) {
  5210. this.parent.addReturnExpression(expression);
  5211. }
  5212. }
  5213. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  5214. for (const variable of this.accessedOutsideVariables.values()) {
  5215. if (variable.included) {
  5216. usedNames.add(variable.getBaseVariableName());
  5217. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5218. usedNames.add('exports');
  5219. }
  5220. }
  5221. }
  5222. const accessedGlobals = accessedGlobalsByScope.get(this);
  5223. if (accessedGlobals) {
  5224. for (const name of accessedGlobals) {
  5225. usedNames.add(name);
  5226. }
  5227. }
  5228. }
  5229. contains(name) {
  5230. return this.variables.has(name) || this.parent.contains(name);
  5231. }
  5232. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  5233. const usedNames = new Set();
  5234. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  5235. if (this.accessedDynamicImports) {
  5236. for (const importExpression of this.accessedDynamicImports) {
  5237. if (importExpression.inlineNamespace) {
  5238. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  5239. }
  5240. }
  5241. }
  5242. for (const [name, variable] of this.variables) {
  5243. if (variable.included || variable.alwaysRendered) {
  5244. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  5245. }
  5246. }
  5247. for (const scope of this.children) {
  5248. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  5249. }
  5250. }
  5251. findLexicalBoundary() {
  5252. return this.parent.findLexicalBoundary();
  5253. }
  5254. findGlobal(name) {
  5255. const variable = this.parent.findVariable(name);
  5256. this.accessedOutsideVariables.set(name, variable);
  5257. return variable;
  5258. }
  5259. findVariable(name) {
  5260. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  5261. if (knownVariable) {
  5262. return knownVariable;
  5263. }
  5264. const variable = this.parent.findVariable(name);
  5265. this.accessedOutsideVariables.set(name, variable);
  5266. return variable;
  5267. }
  5268. }
  5269. function checkEffectForNodes(nodes, context) {
  5270. for (const node of nodes) {
  5271. if (node.hasEffects(context)) {
  5272. return true;
  5273. }
  5274. }
  5275. return false;
  5276. }
  5277. class MethodBase extends NodeBase {
  5278. constructor() {
  5279. super(...arguments);
  5280. this.accessedValue = null;
  5281. }
  5282. get computed() {
  5283. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  5284. }
  5285. set computed(value) {
  5286. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  5287. }
  5288. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5289. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  5290. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  5291. args: interaction.args,
  5292. type: INTERACTION_CALLED,
  5293. withNew: false
  5294. }, EMPTY_PATH, recursionTracker);
  5295. }
  5296. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  5297. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  5298. args: interaction.args,
  5299. type: INTERACTION_CALLED,
  5300. withNew: false
  5301. }, EMPTY_PATH, recursionTracker);
  5302. }
  5303. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5304. }
  5305. // As getter properties directly receive their values from fixed function
  5306. // expressions, there is no known situation where a getter is deoptimized.
  5307. deoptimizeCache() { }
  5308. deoptimizePath(path) {
  5309. this.getAccessedValue()[0].deoptimizePath(path);
  5310. }
  5311. getLiteralValueAtPath(path, recursionTracker, origin) {
  5312. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  5313. }
  5314. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5315. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5316. }
  5317. hasEffects(context) {
  5318. return this.key.hasEffects(context);
  5319. }
  5320. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5321. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  5322. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  5323. args: interaction.args,
  5324. type: INTERACTION_CALLED,
  5325. withNew: false
  5326. }, context);
  5327. }
  5328. // setters are only called for empty paths
  5329. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  5330. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  5331. args: interaction.args,
  5332. type: INTERACTION_CALLED,
  5333. withNew: false
  5334. }, context);
  5335. }
  5336. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  5337. }
  5338. getAccessedValue() {
  5339. if (this.accessedValue === null) {
  5340. if (this.kind === 'get') {
  5341. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  5342. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  5343. }
  5344. else {
  5345. return (this.accessedValue = [this.value, false]);
  5346. }
  5347. }
  5348. return this.accessedValue;
  5349. }
  5350. }
  5351. MethodBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  5352. MethodBase.prototype.applyDeoptimizations = doNotDeoptimize;
  5353. class MethodDefinition extends MethodBase {
  5354. hasEffects(context) {
  5355. return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  5356. }
  5357. }
  5358. class BlockScope extends ChildScope {
  5359. constructor(parent) {
  5360. super(parent, parent.context);
  5361. }
  5362. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5363. if (kind === 'var') {
  5364. const name = identifier.name;
  5365. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5366. if (existingVariable) {
  5367. if (existingVariable.kind === 'var' ||
  5368. (kind === 'var' && existingVariable.kind === 'parameter')) {
  5369. existingVariable.addDeclaration(identifier, init);
  5370. return existingVariable;
  5371. }
  5372. return context.error(logRedeclarationError(name), identifier.start);
  5373. }
  5374. const declaredVariable = this.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5375. // Necessary to make sure the init is deoptimized for conditional declarations.
  5376. // We cannot call deoptimizePath here.
  5377. declaredVariable.markInitializersForDeoptimization();
  5378. // We add the variable to this and all parent scopes to reliably detect conflicts
  5379. this.addHoistedVariable(name, declaredVariable);
  5380. return declaredVariable;
  5381. }
  5382. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5383. }
  5384. }
  5385. class StaticBlock extends NodeBase {
  5386. createScope(parentScope) {
  5387. this.scope = new BlockScope(parentScope);
  5388. }
  5389. hasEffects(context) {
  5390. for (const node of this.body) {
  5391. if (node.hasEffects(context))
  5392. return true;
  5393. }
  5394. return false;
  5395. }
  5396. include(context, includeChildrenRecursively) {
  5397. this.included = true;
  5398. for (const node of this.body) {
  5399. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  5400. node.include(context, includeChildrenRecursively);
  5401. }
  5402. }
  5403. render(code, options) {
  5404. if (this.body.length > 0) {
  5405. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  5406. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  5407. }
  5408. else {
  5409. super.render(code, options);
  5410. }
  5411. }
  5412. }
  5413. StaticBlock.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  5414. StaticBlock.prototype.applyDeoptimizations = doNotDeoptimize;
  5415. function isStaticBlock(statement) {
  5416. return statement.type === StaticBlock$1;
  5417. }
  5418. class ClassNode extends NodeBase {
  5419. constructor() {
  5420. super(...arguments);
  5421. this.objectEntity = null;
  5422. }
  5423. createScope(parentScope) {
  5424. this.scope = new ChildScope(parentScope, parentScope.context);
  5425. }
  5426. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5427. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5428. }
  5429. deoptimizeCache() {
  5430. this.getObjectEntity().deoptimizeAllProperties();
  5431. }
  5432. deoptimizePath(path) {
  5433. this.getObjectEntity().deoptimizePath(path);
  5434. }
  5435. getLiteralValueAtPath(path, recursionTracker, origin) {
  5436. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5437. }
  5438. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5439. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5440. }
  5441. hasEffects(context) {
  5442. if (!this.deoptimized)
  5443. this.applyDeoptimizations();
  5444. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  5445. this.id?.markDeclarationReached();
  5446. return initEffect || super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  5447. }
  5448. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5449. return interaction.type === INTERACTION_CALLED && path.length === 0
  5450. ? !interaction.withNew ||
  5451. (this.classConstructor === null
  5452. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  5453. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  5454. false
  5455. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5456. }
  5457. include(context, includeChildrenRecursively) {
  5458. if (!this.included)
  5459. this.includeNode(context);
  5460. this.superClass?.include(context, includeChildrenRecursively);
  5461. this.body.include(context, includeChildrenRecursively);
  5462. for (const decorator of this.decorators)
  5463. decorator.include(context, includeChildrenRecursively);
  5464. if (this.id) {
  5465. this.id.markDeclarationReached();
  5466. this.id.include(context, includeChildrenRecursively);
  5467. }
  5468. }
  5469. initialise() {
  5470. super.initialise();
  5471. this.id?.declare('class', EMPTY_PATH, this);
  5472. for (const method of this.body.body) {
  5473. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  5474. this.classConstructor = method;
  5475. return;
  5476. }
  5477. }
  5478. this.classConstructor = null;
  5479. }
  5480. applyDeoptimizations() {
  5481. this.deoptimized = true;
  5482. for (const definition of this.body.body) {
  5483. if (!isStaticBlock(definition) &&
  5484. !(definition.static ||
  5485. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  5486. // Calls to methods are not tracked, ensure that the return value is deoptimized
  5487. definition.deoptimizePath(UNKNOWN_PATH);
  5488. }
  5489. }
  5490. this.scope.context.requestTreeshakingPass();
  5491. }
  5492. getObjectEntity() {
  5493. if (this.objectEntity !== null) {
  5494. return this.objectEntity;
  5495. }
  5496. const staticProperties = [];
  5497. const dynamicMethods = [];
  5498. for (const definition of this.body.body) {
  5499. if (isStaticBlock(definition))
  5500. continue;
  5501. const properties = definition.static ? staticProperties : dynamicMethods;
  5502. const definitionKind = definition.kind;
  5503. // Note that class fields do not end up on the prototype
  5504. if (properties === dynamicMethods && !definitionKind)
  5505. continue;
  5506. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  5507. let key;
  5508. if (definition.computed) {
  5509. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  5510. if (typeof keyValue === 'symbol') {
  5511. properties.push({ key: UnknownKey, kind, property: definition });
  5512. continue;
  5513. }
  5514. else {
  5515. key = String(keyValue);
  5516. }
  5517. }
  5518. else {
  5519. key =
  5520. definition.key instanceof Identifier
  5521. ? definition.key.name
  5522. : String(definition.key.value);
  5523. }
  5524. properties.push({ key, kind, property: definition });
  5525. }
  5526. staticProperties.unshift({
  5527. key: 'prototype',
  5528. kind: 'init',
  5529. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, ['prototype']) : OBJECT_PROTOTYPE)
  5530. });
  5531. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  5532. }
  5533. }
  5534. ClassNode.prototype.includeNode = onlyIncludeSelf;
  5535. class ClassDeclaration extends ClassNode {
  5536. initialise() {
  5537. super.initialise();
  5538. if (this.id !== null) {
  5539. this.id.variable.isId = true;
  5540. }
  5541. }
  5542. parseNode(esTreeNode) {
  5543. if (esTreeNode.id !== null) {
  5544. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  5545. }
  5546. return super.parseNode(esTreeNode);
  5547. }
  5548. render(code, options) {
  5549. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  5550. if (this.id) {
  5551. const { variable, name } = this.id;
  5552. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5553. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  5554. }
  5555. const renderedVariable = variable.getName(getPropertyAccess);
  5556. if (renderedVariable !== name) {
  5557. this.decorators.map(decorator => decorator.render(code, options));
  5558. this.superClass?.render(code, options);
  5559. this.body.render(code, {
  5560. ...options,
  5561. useOriginalName: (_variable) => _variable === variable
  5562. });
  5563. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  5564. code.prependLeft(this.end, ';');
  5565. return;
  5566. }
  5567. }
  5568. super.render(code, options);
  5569. }
  5570. applyDeoptimizations() {
  5571. super.applyDeoptimizations();
  5572. const { id, scope } = this;
  5573. if (id) {
  5574. const { name, variable } = id;
  5575. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  5576. if (accessedVariable !== variable) {
  5577. accessedVariable.forbidName(name);
  5578. }
  5579. }
  5580. }
  5581. }
  5582. }
  5583. class ArgumentsVariable extends LocalVariable {
  5584. constructor(context) {
  5585. super('arguments', null, UNKNOWN_EXPRESSION, EMPTY_PATH, context, 'other');
  5586. }
  5587. addArgumentToBeDeoptimized(_argument) { }
  5588. // Only If there is at least one reference, then we need to track all
  5589. // arguments in order to be able to deoptimize them.
  5590. addReference() {
  5591. this.deoptimizedArguments = [];
  5592. this.addArgumentToBeDeoptimized = addArgumentToBeDeoptimized;
  5593. }
  5594. hasEffectsOnInteractionAtPath(path, { type }) {
  5595. return type !== INTERACTION_ACCESSED || path.length > 1;
  5596. }
  5597. includePath(path, context) {
  5598. super.includePath(path, context);
  5599. for (const argument of this.deoptimizedArguments) {
  5600. argument.deoptimizePath(UNKNOWN_PATH);
  5601. }
  5602. this.deoptimizedArguments.length = 0;
  5603. }
  5604. }
  5605. function addArgumentToBeDeoptimized(argument) {
  5606. if (this.included) {
  5607. argument.deoptimizePath(UNKNOWN_PATH);
  5608. }
  5609. else {
  5610. this.deoptimizedArguments?.push(argument);
  5611. }
  5612. }
  5613. const MAX_TRACKED_INTERACTIONS = 20;
  5614. const NO_INTERACTIONS = EMPTY_ARRAY;
  5615. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  5616. const EMPTY_PATH_TRACKER = new EntityPathTracker();
  5617. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  5618. class ParameterVariable extends LocalVariable {
  5619. constructor(name, declarator, argumentPath, context) {
  5620. super(name, declarator, UNKNOWN_EXPRESSION, argumentPath, context, 'parameter');
  5621. this.includedPathTracker = new IncludedTopLevelPathTracker();
  5622. this.argumentsToBeDeoptimized = new Set();
  5623. this.deoptimizationInteractions = [];
  5624. this.deoptimizations = new EntityPathTracker();
  5625. this.deoptimizedFields = new Set();
  5626. this.expressionsDependingOnKnownValue = [];
  5627. this.knownValue = null;
  5628. this.knownValueLiteral = UnknownValue;
  5629. }
  5630. addArgumentForDeoptimization(entity) {
  5631. this.updateKnownValue(entity);
  5632. if (entity === UNKNOWN_EXPRESSION) {
  5633. // As unknown expressions fully deoptimize all interactions, we can clear
  5634. // the interaction cache at this point provided we keep this optimization
  5635. // in mind when adding new interactions
  5636. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5637. this.argumentsToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  5638. for (const { interaction } of this.deoptimizationInteractions) {
  5639. deoptimizeInteraction(interaction);
  5640. }
  5641. this.deoptimizationInteractions = NO_INTERACTIONS;
  5642. }
  5643. }
  5644. else if (this.deoptimizedFields.has(UnknownKey)) {
  5645. // This means that we already deoptimized all interactions and no longer
  5646. // track them
  5647. entity.deoptimizePath([...this.initPath, UnknownKey]);
  5648. }
  5649. else if (!this.argumentsToBeDeoptimized.has(entity)) {
  5650. this.argumentsToBeDeoptimized.add(entity);
  5651. for (const field of this.deoptimizedFields) {
  5652. entity.deoptimizePath([...this.initPath, field]);
  5653. }
  5654. for (const { interaction, path } of this.deoptimizationInteractions) {
  5655. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  5656. }
  5657. }
  5658. }
  5659. /** This says we should not make assumptions about the value of the parameter.
  5660. * This is different from deoptimization that will also cause argument values
  5661. * to be deoptimized. */
  5662. markReassigned() {
  5663. if (this.isReassigned) {
  5664. return;
  5665. }
  5666. super.markReassigned();
  5667. for (const expression of this.expressionsDependingOnKnownValue) {
  5668. expression.deoptimizeCache();
  5669. }
  5670. this.expressionsDependingOnKnownValue = EMPTY_ARRAY;
  5671. }
  5672. deoptimizeCache() {
  5673. this.markReassigned();
  5674. }
  5675. /**
  5676. * Update the known value of the parameter variable.
  5677. * Must be called for every function call, so it can track all the arguments,
  5678. * and deoptimizeCache itself to mark reassigned if the argument is changed.
  5679. * @param argument The argument of the function call
  5680. */
  5681. updateKnownValue(argument) {
  5682. if (this.isReassigned) {
  5683. return;
  5684. }
  5685. if (this.knownValue === null) {
  5686. this.knownValue = argument;
  5687. this.knownValueLiteral = argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this);
  5688. return;
  5689. }
  5690. // the same literal or identifier, do nothing
  5691. if (this.knownValue === argument ||
  5692. (this.knownValue instanceof Identifier &&
  5693. argument instanceof Identifier &&
  5694. this.knownValue.variable === argument.variable)) {
  5695. return;
  5696. }
  5697. const { knownValueLiteral } = this;
  5698. if (typeof knownValueLiteral === 'symbol' ||
  5699. argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this) !==
  5700. knownValueLiteral) {
  5701. this.markReassigned();
  5702. }
  5703. }
  5704. /**
  5705. * This function freezes the known value of the parameter variable,
  5706. * so the optimization starts with a certain ExpressionEntity.
  5707. * The optimization can be undone by calling `markReassigned`.
  5708. * @returns the frozen value
  5709. */
  5710. getKnownValue() {
  5711. return this.knownValue || UNKNOWN_EXPRESSION;
  5712. }
  5713. getLiteralValueAtPath(path, recursionTracker, origin) {
  5714. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  5715. return UnknownValue;
  5716. }
  5717. const knownValue = this.getKnownValue();
  5718. this.expressionsDependingOnKnownValue.push(origin);
  5719. return recursionTracker.withTrackedEntityAtPath(path, knownValue, () => knownValue.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin), UnknownValue);
  5720. }
  5721. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5722. const { type } = interaction;
  5723. if (this.isReassigned ||
  5724. type === INTERACTION_ASSIGNED ||
  5725. path.length + this.initPath.length > MAX_PATH_DEPTH) {
  5726. return super.hasEffectsOnInteractionAtPath(path, interaction, context);
  5727. }
  5728. return (!(type === INTERACTION_CALLED
  5729. ? (interaction.withNew
  5730. ? context.instantiated
  5731. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)
  5732. : context.accessed.trackEntityAtPathAndGetIfTracked(path, this)) &&
  5733. this.getKnownValue().hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  5734. }
  5735. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  5736. // For performance reasons, we fully deoptimize all deeper interactions
  5737. if (path.length >= 2 ||
  5738. this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  5739. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  5740. (path.length === 1 &&
  5741. (this.deoptimizedFields.has(UnknownKey) ||
  5742. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0])))) ||
  5743. this.initPath.length + path.length > MAX_PATH_DEPTH) {
  5744. deoptimizeInteraction(interaction);
  5745. return;
  5746. }
  5747. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  5748. for (const entity of this.argumentsToBeDeoptimized) {
  5749. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  5750. }
  5751. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5752. this.deoptimizationInteractions.push({
  5753. interaction,
  5754. path
  5755. });
  5756. }
  5757. }
  5758. }
  5759. deoptimizePath(path) {
  5760. if (path.length === 0) {
  5761. this.markReassigned();
  5762. return;
  5763. }
  5764. if (this.deoptimizedFields.has(UnknownKey)) {
  5765. return;
  5766. }
  5767. const key = path[0];
  5768. if (this.deoptimizedFields.has(key)) {
  5769. return;
  5770. }
  5771. this.deoptimizedFields.add(key);
  5772. for (const entity of this.argumentsToBeDeoptimized) {
  5773. // We do not need a recursion tracker here as we already track whether
  5774. // this field is deoptimized
  5775. entity.deoptimizePath([...this.initPath, key]);
  5776. }
  5777. if (key === UnknownKey) {
  5778. // save some memory
  5779. this.deoptimizationInteractions = NO_INTERACTIONS;
  5780. this.deoptimizations = EMPTY_PATH_TRACKER;
  5781. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  5782. this.argumentsToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  5783. }
  5784. }
  5785. getReturnExpressionWhenCalledAtPath(path) {
  5786. // We deoptimize everything that is called as that will trivially deoptimize
  5787. // the corresponding return expressions as well and avoid badly performing
  5788. // and complicated alternatives
  5789. if (path.length === 0) {
  5790. this.deoptimizePath(UNKNOWN_PATH);
  5791. }
  5792. else if (!this.deoptimizedFields.has(path[0])) {
  5793. this.deoptimizePath([path[0]]);
  5794. }
  5795. return UNKNOWN_RETURN_EXPRESSION;
  5796. }
  5797. includeArgumentPaths(entity, context) {
  5798. this.includedPathTracker.includeAllPaths(entity, context, this.initPath);
  5799. }
  5800. }
  5801. class ThisVariable extends ParameterVariable {
  5802. constructor(context) {
  5803. super('this', null, EMPTY_PATH, context);
  5804. }
  5805. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5806. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  5807. }
  5808. }
  5809. class CatchBodyScope extends ChildScope {
  5810. constructor(parent) {
  5811. super(parent, parent.context);
  5812. this.parent = parent;
  5813. }
  5814. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5815. if (kind === 'var') {
  5816. const name = identifier.name;
  5817. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5818. if (existingVariable) {
  5819. const existingKind = existingVariable.kind;
  5820. if (existingKind === 'parameter' &&
  5821. // If this is a destructured parameter, it is forbidden to redeclare
  5822. existingVariable.declarations[0].parent.type === CatchClause$1) {
  5823. // If this is a var with the same name as the catch scope parameter,
  5824. // the assignment actually goes to the parameter and the var is
  5825. // hoisted without assignment. Locally, it is shadowed by the
  5826. // parameter
  5827. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, destructuredInitPath, kind);
  5828. // To avoid the need to rewrite the declaration, we link the variable
  5829. // names. If we ever implement a logic that splits initialization and
  5830. // assignment for hoisted vars, the "renderLikeHoisted" logic can be
  5831. // removed again.
  5832. // We do not need to check whether there already is a linked
  5833. // variable because then declaredVariable would be that linked
  5834. // variable.
  5835. existingVariable.renderLikeHoisted(declaredVariable);
  5836. this.addHoistedVariable(name, declaredVariable);
  5837. return declaredVariable;
  5838. }
  5839. if (existingKind === 'var') {
  5840. existingVariable.addDeclaration(identifier, init);
  5841. return existingVariable;
  5842. }
  5843. return context.error(logRedeclarationError(name), identifier.start);
  5844. }
  5845. // We only add parameters to parameter scopes
  5846. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5847. // Necessary to make sure the init is deoptimized for conditional declarations.
  5848. // We cannot call deoptimizePath here.
  5849. declaredVariable.markInitializersForDeoptimization();
  5850. // We add the variable to this and all parent scopes to reliably detect conflicts
  5851. this.addHoistedVariable(name, declaredVariable);
  5852. return declaredVariable;
  5853. }
  5854. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5855. }
  5856. }
  5857. class FunctionBodyScope extends ChildScope {
  5858. constructor(parent) {
  5859. super(parent, parent.context);
  5860. }
  5861. // There is stuff that is only allowed in function scopes, i.e. functions can
  5862. // be redeclared, functions and var can redeclare each other
  5863. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5864. const name = identifier.name;
  5865. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5866. if (existingVariable) {
  5867. const existingKind = existingVariable.kind;
  5868. if ((kind === 'var' || kind === 'function') &&
  5869. (existingKind === 'var' || existingKind === 'function' || existingKind === 'parameter')) {
  5870. existingVariable.addDeclaration(identifier, init);
  5871. return existingVariable;
  5872. }
  5873. context.error(logRedeclarationError(name), identifier.start);
  5874. }
  5875. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  5876. this.variables.set(name, newVariable);
  5877. return newVariable;
  5878. }
  5879. }
  5880. class ParameterScope extends ChildScope {
  5881. constructor(parent, isCatchScope) {
  5882. super(parent, parent.context);
  5883. this.hasRest = false;
  5884. this.parameters = [];
  5885. this.bodyScope = isCatchScope ? new CatchBodyScope(this) : new FunctionBodyScope(this);
  5886. }
  5887. /**
  5888. * Adds a parameter to this scope. Parameters must be added in the correct
  5889. * order, i.e. from left to right.
  5890. */
  5891. addParameterDeclaration(identifier, argumentPath) {
  5892. const { name, start } = identifier;
  5893. const existingParameter = this.variables.get(name);
  5894. if (existingParameter) {
  5895. return this.context.error(logDuplicateArgumentNameError(name), start);
  5896. }
  5897. const variable = new ParameterVariable(name, identifier, argumentPath, this.context);
  5898. this.variables.set(name, variable);
  5899. // We also add it to the body scope to detect name conflicts with local
  5900. // variables. We still need the intermediate scope, though, as parameter
  5901. // defaults are NOT taken from the body scope but from the parameters or
  5902. // outside scope.
  5903. this.bodyScope.addHoistedVariable(name, variable);
  5904. return variable;
  5905. }
  5906. addParameterVariables(parameters, hasRest) {
  5907. this.parameters = parameters;
  5908. for (const parameterList of parameters) {
  5909. for (const parameter of parameterList) {
  5910. parameter.alwaysRendered = true;
  5911. }
  5912. }
  5913. this.hasRest = hasRest;
  5914. }
  5915. includeCallArguments({ args }, context) {
  5916. let calledFromTryStatement = false;
  5917. let argumentIncluded = false;
  5918. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  5919. let lastExplicitlyIncludedIndex = args.length - 1;
  5920. // If there is a SpreadElement, we need to include all arguments after it
  5921. // because we no longer know which argument corresponds to which parameter.
  5922. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  5923. const argument = args[argumentIndex];
  5924. if (argument instanceof SpreadElement && !argumentIncluded) {
  5925. argumentIncluded = true;
  5926. lastExplicitlyIncludedIndex = argumentIndex - 1;
  5927. }
  5928. if (argumentIncluded) {
  5929. argument.includePath(UNKNOWN_PATH, context);
  5930. argument.include(context, false);
  5931. }
  5932. }
  5933. // Now we go backwards either starting from the last argument or before the
  5934. // first SpreadElement to ensure all arguments before are included as needed
  5935. for (let index = lastExplicitlyIncludedIndex; index >= 1; index--) {
  5936. const parameterVariables = this.parameters[index - 1] || restParameter;
  5937. const argument = args[index];
  5938. if (parameterVariables) {
  5939. calledFromTryStatement = false;
  5940. if (parameterVariables.length === 0) {
  5941. // handle empty destructuring to avoid destructuring undefined
  5942. argumentIncluded = true;
  5943. }
  5944. else {
  5945. for (const parameterVariable of parameterVariables) {
  5946. if (parameterVariable.calledFromTryStatement) {
  5947. calledFromTryStatement = true;
  5948. }
  5949. if (parameterVariable.included) {
  5950. argumentIncluded = true;
  5951. if (calledFromTryStatement) {
  5952. argument.include(context, true);
  5953. }
  5954. else {
  5955. parameterVariable.includeArgumentPaths(argument, context);
  5956. argument.include(context, false);
  5957. }
  5958. }
  5959. }
  5960. }
  5961. }
  5962. if (argumentIncluded || argument.shouldBeIncluded(context)) {
  5963. argumentIncluded = true;
  5964. argument.include(context, calledFromTryStatement);
  5965. }
  5966. }
  5967. }
  5968. }
  5969. class ReturnValueScope extends ParameterScope {
  5970. constructor() {
  5971. super(...arguments);
  5972. this.returnExpression = null;
  5973. this.returnExpressions = [];
  5974. }
  5975. addReturnExpression(expression) {
  5976. this.returnExpressions.push(expression);
  5977. }
  5978. deoptimizeArgumentsOnCall({ args }) {
  5979. const { parameters } = this;
  5980. let position = 0;
  5981. for (; position < args.length - 1; position++) {
  5982. // Only the "this" argument arg[0] can be null
  5983. const argument = args[position + 1];
  5984. if (argument instanceof SpreadElement) {
  5985. // This deoptimizes the current and remaining parameters and arguments
  5986. for (; position < parameters.length; position++) {
  5987. args[position + 1]?.deoptimizePath(UNKNOWN_PATH);
  5988. for (const variable of parameters[position]) {
  5989. variable.markReassigned();
  5990. }
  5991. }
  5992. break;
  5993. }
  5994. if (this.hasRest && position >= parameters.length - 1) {
  5995. argument.deoptimizePath(UNKNOWN_PATH);
  5996. }
  5997. else {
  5998. const variables = parameters[position];
  5999. if (variables) {
  6000. for (const variable of variables) {
  6001. variable.addArgumentForDeoptimization(argument);
  6002. }
  6003. }
  6004. this.addArgumentToBeDeoptimized(argument);
  6005. }
  6006. }
  6007. const nonRestParameterLength = this.hasRest ? parameters.length - 1 : parameters.length;
  6008. for (; position < nonRestParameterLength; position++) {
  6009. for (const variable of parameters[position]) {
  6010. variable.addArgumentForDeoptimization(UNDEFINED_EXPRESSION);
  6011. }
  6012. }
  6013. }
  6014. getReturnExpression() {
  6015. if (this.returnExpression === null)
  6016. this.updateReturnExpression();
  6017. return this.returnExpression;
  6018. }
  6019. deoptimizeAllParameters() {
  6020. for (const parameter of this.parameters) {
  6021. for (const variable of parameter) {
  6022. variable.deoptimizePath(UNKNOWN_PATH);
  6023. variable.markReassigned();
  6024. }
  6025. }
  6026. }
  6027. reassignAllParameters() {
  6028. for (const parameter of this.parameters) {
  6029. for (const variable of parameter) {
  6030. variable.markReassigned();
  6031. }
  6032. }
  6033. }
  6034. addArgumentToBeDeoptimized(_argument) { }
  6035. updateReturnExpression() {
  6036. if (this.returnExpressions.length === 1) {
  6037. this.returnExpression = this.returnExpressions[0];
  6038. }
  6039. else {
  6040. this.returnExpression = UNKNOWN_EXPRESSION;
  6041. for (const expression of this.returnExpressions) {
  6042. expression.deoptimizePath(UNKNOWN_PATH);
  6043. }
  6044. }
  6045. }
  6046. }
  6047. class FunctionScope extends ReturnValueScope {
  6048. constructor(parent, functionNode) {
  6049. super(parent, false);
  6050. this.functionNode = functionNode;
  6051. const { context } = parent;
  6052. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  6053. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  6054. }
  6055. findLexicalBoundary() {
  6056. return this;
  6057. }
  6058. includeCallArguments(interaction, context) {
  6059. super.includeCallArguments(interaction, context);
  6060. if (this.argumentsVariable.included) {
  6061. const { args } = interaction;
  6062. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  6063. const argument = args[argumentIndex];
  6064. if (argument) {
  6065. argument.includePath(UNKNOWN_PATH, context);
  6066. argument.include(context, false);
  6067. }
  6068. }
  6069. }
  6070. }
  6071. addArgumentToBeDeoptimized(argument) {
  6072. this.argumentsVariable.addArgumentToBeDeoptimized(argument);
  6073. }
  6074. }
  6075. class ExpressionStatement extends NodeBase {
  6076. initialise() {
  6077. super.initialise();
  6078. if (this.directive &&
  6079. this.directive !== 'use strict' &&
  6080. this.parent.type === Program$1) {
  6081. this.scope.context.log(LOGLEVEL_WARN,
  6082. // This is necessary, because either way (deleting or not) can lead to errors.
  6083. logModuleLevelDirective(this.directive, this.scope.context.module.id), this.start);
  6084. }
  6085. }
  6086. removeAnnotations(code) {
  6087. this.expression.removeAnnotations(code);
  6088. }
  6089. render(code, options) {
  6090. super.render(code, options);
  6091. if (code.original[this.end - 1] !== ';') {
  6092. code.appendLeft(this.end, ';');
  6093. }
  6094. }
  6095. shouldBeIncluded(context) {
  6096. if (this.directive && this.directive !== 'use strict')
  6097. return this.parent.type !== Program$1;
  6098. return super.shouldBeIncluded(context);
  6099. }
  6100. }
  6101. ExpressionStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6102. ExpressionStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  6103. class BlockStatement extends NodeBase {
  6104. get deoptimizeBody() {
  6105. return isFlagSet(this.flags, 32768 /* Flag.deoptimizeBody */);
  6106. }
  6107. set deoptimizeBody(value) {
  6108. this.flags = setFlag(this.flags, 32768 /* Flag.deoptimizeBody */, value);
  6109. }
  6110. get directlyIncluded() {
  6111. return isFlagSet(this.flags, 16384 /* Flag.directlyIncluded */);
  6112. }
  6113. set directlyIncluded(value) {
  6114. this.flags = setFlag(this.flags, 16384 /* Flag.directlyIncluded */, value);
  6115. }
  6116. addImplicitReturnExpressionToScope() {
  6117. const lastStatement = this.body[this.body.length - 1];
  6118. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  6119. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  6120. }
  6121. }
  6122. createScope(parentScope) {
  6123. this.scope = this.parent.preventChildBlockScope
  6124. ? parentScope
  6125. : new BlockScope(parentScope);
  6126. }
  6127. hasEffects(context) {
  6128. if (this.deoptimizeBody)
  6129. return true;
  6130. for (const node of this.body) {
  6131. if (context.brokenFlow)
  6132. break;
  6133. if (node.hasEffects(context))
  6134. return true;
  6135. }
  6136. return false;
  6137. }
  6138. include(context, includeChildrenRecursively) {
  6139. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  6140. this.included = true;
  6141. this.directlyIncluded = true;
  6142. if (this.deoptimizeBody)
  6143. includeChildrenRecursively = true;
  6144. for (const node of this.body) {
  6145. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  6146. node.include(context, includeChildrenRecursively);
  6147. }
  6148. }
  6149. }
  6150. initialise() {
  6151. super.initialise();
  6152. this.scope.context.magicString.addSourcemapLocation(this.end - 1);
  6153. const firstBodyStatement = this.body[0];
  6154. this.deoptimizeBody =
  6155. firstBodyStatement instanceof ExpressionStatement &&
  6156. firstBodyStatement.directive === 'use asm';
  6157. }
  6158. render(code, options) {
  6159. if (this.body.length > 0) {
  6160. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  6161. }
  6162. else {
  6163. super.render(code, options);
  6164. }
  6165. }
  6166. }
  6167. BlockStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6168. BlockStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  6169. class RestElement extends NodeBase {
  6170. constructor() {
  6171. super(...arguments);
  6172. this.declarationInit = null;
  6173. }
  6174. addExportedVariables(variables, exportNamesByVariable) {
  6175. this.argument.addExportedVariables(variables, exportNamesByVariable);
  6176. }
  6177. declare(kind, destructuredInitPath, init) {
  6178. this.declarationInit = init;
  6179. return this.argument.declare(kind, getIncludedPatternPath$1(destructuredInitPath), init);
  6180. }
  6181. deoptimizeAssignment(destructuredInitPath, init) {
  6182. this.argument.deoptimizeAssignment(getIncludedPatternPath$1(destructuredInitPath), init);
  6183. }
  6184. deoptimizePath(path) {
  6185. if (path.length === 0) {
  6186. this.argument.deoptimizePath(EMPTY_PATH);
  6187. }
  6188. }
  6189. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6190. return (path.length > 0 ||
  6191. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  6192. }
  6193. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  6194. return this.argument.hasEffectsWhenDestructuring(context, getIncludedPatternPath$1(destructuredInitPath), init);
  6195. }
  6196. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  6197. const included = this.argument.includeDestructuredIfNecessary(context, getIncludedPatternPath$1(destructuredInitPath), init);
  6198. if (!this.included && included) {
  6199. this.includeNode(context);
  6200. }
  6201. return this.included;
  6202. }
  6203. include(context, includeChildrenRecursively) {
  6204. if (!this.included)
  6205. this.includeNode(context);
  6206. // This should just include the identifier, its properties should be
  6207. // included where the variable is used.
  6208. this.argument.include(context, includeChildrenRecursively);
  6209. }
  6210. markDeclarationReached() {
  6211. this.argument.markDeclarationReached();
  6212. }
  6213. applyDeoptimizations() {
  6214. this.deoptimized = true;
  6215. if (this.declarationInit !== null) {
  6216. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  6217. this.scope.context.requestTreeshakingPass();
  6218. }
  6219. }
  6220. }
  6221. RestElement.prototype.includeNode = onlyIncludeSelf;
  6222. const getIncludedPatternPath$1 = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  6223. ? destructuredInitPath
  6224. : [...destructuredInitPath, UnknownKey];
  6225. class FunctionBase extends NodeBase {
  6226. constructor() {
  6227. super(...arguments);
  6228. this.parameterVariableValuesDeoptimized = false;
  6229. this.includeCallArguments = this.scope.includeCallArguments.bind(this.scope);
  6230. }
  6231. get async() {
  6232. return isFlagSet(this.flags, 256 /* Flag.async */);
  6233. }
  6234. set async(value) {
  6235. this.flags = setFlag(this.flags, 256 /* Flag.async */, value);
  6236. }
  6237. get deoptimizedReturn() {
  6238. return isFlagSet(this.flags, 512 /* Flag.deoptimizedReturn */);
  6239. }
  6240. set deoptimizedReturn(value) {
  6241. this.flags = setFlag(this.flags, 512 /* Flag.deoptimizedReturn */, value);
  6242. }
  6243. get generator() {
  6244. return isFlagSet(this.flags, 4194304 /* Flag.generator */);
  6245. }
  6246. set generator(value) {
  6247. this.flags = setFlag(this.flags, 4194304 /* Flag.generator */, value);
  6248. }
  6249. get hasCachedEffects() {
  6250. return isFlagSet(this.flags, 67108864 /* Flag.hasEffects */);
  6251. }
  6252. set hasCachedEffects(value) {
  6253. this.flags = setFlag(this.flags, 67108864 /* Flag.hasEffects */, value);
  6254. }
  6255. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6256. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  6257. this.scope.deoptimizeArgumentsOnCall(interaction);
  6258. }
  6259. else {
  6260. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6261. }
  6262. }
  6263. deoptimizePath(path) {
  6264. this.getObjectEntity().deoptimizePath(path);
  6265. if (path.length === 1 && path[0] === UnknownKey) {
  6266. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  6267. // which means the return expression and parameters need to be reassigned
  6268. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  6269. this.scope.deoptimizeAllParameters();
  6270. }
  6271. }
  6272. getLiteralValueAtPath(path, recursionTracker, origin) {
  6273. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  6274. }
  6275. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6276. if (path.length > 0) {
  6277. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6278. }
  6279. if (this.async) {
  6280. if (!this.deoptimizedReturn) {
  6281. this.deoptimizedReturn = true;
  6282. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  6283. this.scope.context.requestTreeshakingPass();
  6284. }
  6285. return UNKNOWN_RETURN_EXPRESSION;
  6286. }
  6287. return [this.scope.getReturnExpression(), false];
  6288. }
  6289. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6290. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  6291. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  6292. }
  6293. if (this.hasCachedEffects) {
  6294. return true;
  6295. }
  6296. if (this.async) {
  6297. const { propertyReadSideEffects } = this.scope.context.options
  6298. .treeshake;
  6299. const returnExpression = this.scope.getReturnExpression();
  6300. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  6301. (propertyReadSideEffects &&
  6302. (propertyReadSideEffects === 'always' ||
  6303. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  6304. this.hasCachedEffects = true;
  6305. return true;
  6306. }
  6307. }
  6308. const { propertyReadSideEffects } = this.scope.context.options
  6309. .treeshake;
  6310. for (let index = 0; index < this.params.length; index++) {
  6311. const parameter = this.params[index];
  6312. if (parameter.hasEffects(context) ||
  6313. (propertyReadSideEffects &&
  6314. parameter.hasEffectsWhenDestructuring(context, EMPTY_PATH, interaction.args[index + 1] || UNDEFINED_EXPRESSION))) {
  6315. this.hasCachedEffects = true;
  6316. return true;
  6317. }
  6318. }
  6319. return false;
  6320. }
  6321. /**
  6322. * If the function (expression or declaration) is only used as function calls
  6323. */
  6324. onlyFunctionCallUsed() {
  6325. let variable = null;
  6326. if (this.parent.type === VariableDeclarator$1) {
  6327. variable = this.parent.id.variable ?? null;
  6328. }
  6329. if (this.parent.type === ExportDefaultDeclaration$1) {
  6330. variable = this.parent.variable;
  6331. }
  6332. return variable?.getOnlyFunctionCallUsed() ?? false;
  6333. }
  6334. include(context, includeChildrenRecursively) {
  6335. if (!this.included)
  6336. this.includeNode(context);
  6337. if (!(this.parameterVariableValuesDeoptimized || this.onlyFunctionCallUsed())) {
  6338. this.parameterVariableValuesDeoptimized = true;
  6339. this.scope.reassignAllParameters();
  6340. }
  6341. const { brokenFlow } = context;
  6342. context.brokenFlow = false;
  6343. this.body.include(context, includeChildrenRecursively);
  6344. context.brokenFlow = brokenFlow;
  6345. }
  6346. initialise() {
  6347. super.initialise();
  6348. if (this.body instanceof BlockStatement) {
  6349. this.body.addImplicitReturnExpressionToScope();
  6350. }
  6351. else {
  6352. this.scope.addReturnExpression(this.body);
  6353. }
  6354. if (this.annotations &&
  6355. this.scope.context.options.treeshake.annotations) {
  6356. this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
  6357. }
  6358. }
  6359. parseNode(esTreeNode) {
  6360. const { body, params } = esTreeNode;
  6361. const { scope } = this;
  6362. const { bodyScope, context } = scope;
  6363. // We need to ensure that parameters are declared before the body is parsed
  6364. // so that the scope already knows all parameters and can detect conflicts
  6365. // when parsing the body.
  6366. const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
  6367. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  6368. this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
  6369. return super.parseNode(esTreeNode);
  6370. }
  6371. }
  6372. FunctionBase.prototype.preventChildBlockScope = true;
  6373. FunctionBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6374. FunctionBase.prototype.applyDeoptimizations = doNotDeoptimize;
  6375. class FunctionNode extends FunctionBase {
  6376. constructor() {
  6377. super(...arguments);
  6378. this.objectEntity = null;
  6379. }
  6380. createScope(parentScope) {
  6381. this.scope = new FunctionScope(parentScope, this);
  6382. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  6383. // This makes sure that all deoptimizations of "this" are applied to the
  6384. // constructed entity.
  6385. this.scope.thisVariable.addArgumentForDeoptimization(this.constructedEntity);
  6386. }
  6387. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6388. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6389. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  6390. // args[0] is the "this" argument
  6391. this.scope.thisVariable.addArgumentForDeoptimization(interaction.args[0]);
  6392. }
  6393. }
  6394. hasEffects(context) {
  6395. if (this.annotationNoSideEffects) {
  6396. return false;
  6397. }
  6398. return !!this.id?.hasEffects(context);
  6399. }
  6400. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6401. if (this.annotationNoSideEffects &&
  6402. path.length === 0 &&
  6403. interaction.type === INTERACTION_CALLED) {
  6404. return false;
  6405. }
  6406. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  6407. return true;
  6408. }
  6409. if (path.length === 0 && interaction.type === INTERACTION_CALLED) {
  6410. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  6411. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  6412. const { brokenFlow, ignore, replacedVariableInits } = context;
  6413. context.ignore = {
  6414. breaks: false,
  6415. continues: false,
  6416. labels: new Set(),
  6417. returnYield: true,
  6418. this: interaction.withNew
  6419. };
  6420. if (this.body.hasEffects(context)) {
  6421. this.hasCachedEffects = true;
  6422. return true;
  6423. }
  6424. context.brokenFlow = brokenFlow;
  6425. if (thisInit) {
  6426. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  6427. }
  6428. else {
  6429. replacedVariableInits.delete(this.scope.thisVariable);
  6430. }
  6431. context.ignore = ignore;
  6432. }
  6433. return false;
  6434. }
  6435. include(context, includeChildrenRecursively) {
  6436. super.include(context, includeChildrenRecursively);
  6437. this.id?.include(context, includeChildrenRecursively);
  6438. const hasArguments = this.scope.argumentsVariable.included;
  6439. for (const parameter of this.params) {
  6440. if (!(parameter instanceof Identifier) || hasArguments) {
  6441. parameter.include(context, includeChildrenRecursively);
  6442. }
  6443. }
  6444. }
  6445. includeNode(context) {
  6446. this.included = true;
  6447. const hasArguments = this.scope.argumentsVariable.included;
  6448. for (const parameter of this.params) {
  6449. if (!(parameter instanceof Identifier) || hasArguments) {
  6450. parameter.includePath(UNKNOWN_PATH, context);
  6451. }
  6452. }
  6453. }
  6454. initialise() {
  6455. super.initialise();
  6456. this.id?.declare('function', EMPTY_PATH, this);
  6457. }
  6458. getObjectEntity() {
  6459. if (this.objectEntity !== null) {
  6460. return this.objectEntity;
  6461. }
  6462. return (this.objectEntity = new ObjectEntity([
  6463. {
  6464. key: 'prototype',
  6465. kind: 'init',
  6466. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  6467. }
  6468. ], OBJECT_PROTOTYPE));
  6469. }
  6470. }
  6471. class FunctionDeclaration extends FunctionNode {
  6472. initialise() {
  6473. super.initialise();
  6474. if (this.id !== null) {
  6475. this.id.variable.isId = true;
  6476. }
  6477. }
  6478. onlyFunctionCallUsed() {
  6479. // call super.onlyFunctionCallUsed for export default anonymous function
  6480. return this.id?.variable.getOnlyFunctionCallUsed() ?? super.onlyFunctionCallUsed();
  6481. }
  6482. parseNode(esTreeNode) {
  6483. if (esTreeNode.id !== null) {
  6484. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  6485. }
  6486. return super.parseNode(esTreeNode);
  6487. }
  6488. }
  6489. // The header ends at the first non-white-space after "default"
  6490. function getDeclarationStart(code, start) {
  6491. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  6492. }
  6493. function getFunctionIdInsertPosition(code, start) {
  6494. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  6495. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  6496. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  6497. if (generatorStarPos === -1) {
  6498. return declarationEnd;
  6499. }
  6500. return declarationEnd + generatorStarPos + 1;
  6501. }
  6502. class ExportDefaultDeclaration extends NodeBase {
  6503. include(context, includeChildrenRecursively) {
  6504. this.included = true;
  6505. this.declaration.include(context, includeChildrenRecursively);
  6506. if (includeChildrenRecursively) {
  6507. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, context);
  6508. }
  6509. }
  6510. includePath(path, context) {
  6511. this.included = true;
  6512. this.declaration.includePath(path, context);
  6513. }
  6514. initialise() {
  6515. super.initialise();
  6516. const declaration = this.declaration;
  6517. this.declarationName =
  6518. (declaration.id && declaration.id.name) || this.declaration.name;
  6519. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.scope.context.getModuleName(), this, this.scope.context);
  6520. this.scope.context.addExport(this);
  6521. }
  6522. removeAnnotations(code) {
  6523. this.declaration.removeAnnotations(code);
  6524. }
  6525. render(code, options, nodeRenderOptions) {
  6526. const { start, end } = nodeRenderOptions;
  6527. const declarationStart = getDeclarationStart(code.original, this.start);
  6528. if (this.declaration instanceof FunctionDeclaration) {
  6529. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  6530. ? getFunctionIdInsertPosition(code.original, declarationStart)
  6531. : null, options);
  6532. }
  6533. else if (this.declaration instanceof ClassDeclaration) {
  6534. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  6535. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  6536. : null, options);
  6537. }
  6538. else if (this.variable.getOriginalVariable() !== this.variable) {
  6539. // Remove altogether to prevent re-declaring the same variable
  6540. treeshakeNode(this, code, start, end);
  6541. return;
  6542. }
  6543. else if (this.variable.included) {
  6544. this.renderVariableDeclaration(code, declarationStart, options);
  6545. }
  6546. else {
  6547. code.remove(this.start, declarationStart);
  6548. this.declaration.render(code, options, {
  6549. renderedSurroundingElement: ExpressionStatement$1
  6550. });
  6551. if (code.original[this.end - 1] !== ';') {
  6552. code.appendLeft(this.end, ';');
  6553. }
  6554. return;
  6555. }
  6556. this.declaration.render(code, options);
  6557. }
  6558. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  6559. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  6560. const name = this.variable.getName(getPropertyAccess);
  6561. // Remove `export default`
  6562. code.remove(this.start, declarationStart);
  6563. if (idInsertPosition !== null) {
  6564. code.appendLeft(idInsertPosition, ` ${name}`);
  6565. }
  6566. if (format === 'system' &&
  6567. this.declaration instanceof ClassDeclaration &&
  6568. exportNamesByVariable.has(this.variable)) {
  6569. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  6570. }
  6571. }
  6572. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  6573. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  6574. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  6575. if (systemExportNames) {
  6576. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports(${JSON.stringify(systemExportNames[0])}, `);
  6577. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  6578. }
  6579. else {
  6580. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  6581. if (!hasTrailingSemicolon) {
  6582. code.appendLeft(this.end, ';');
  6583. }
  6584. }
  6585. }
  6586. }
  6587. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  6588. ExportDefaultDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6589. ExportDefaultDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  6590. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  6591. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  6592. const backSlashRegEx = /\\/g;
  6593. function escapeId(id) {
  6594. if (!needsEscapeRegEx.test(id))
  6595. return id;
  6596. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  6597. }
  6598. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  6599. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  6600. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  6601. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  6602. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  6603. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  6604. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  6605. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  6606. const defaultInteropHelpersByInteropType = {
  6607. auto: INTEROP_DEFAULT_VARIABLE,
  6608. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  6609. default: null,
  6610. defaultOnly: null,
  6611. esModule: null
  6612. };
  6613. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  6614. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  6615. const namespaceInteropHelpersByInteropType = {
  6616. auto: INTEROP_NAMESPACE_VARIABLE,
  6617. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  6618. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  6619. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  6620. esModule: null
  6621. };
  6622. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  6623. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, symbols) => {
  6624. const usedHelpers = new Set(additionalHelpers);
  6625. for (const variable of HELPER_NAMES) {
  6626. if (accessedGlobals.has(variable)) {
  6627. usedHelpers.add(variable);
  6628. }
  6629. }
  6630. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  6631. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, symbols, usedHelpers)
  6632. : '').join('');
  6633. };
  6634. const HELPER_GENERATORS = {
  6635. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  6636. return `var ${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  6637. },
  6638. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  6639. const { _, getDirectReturnFunction, n } = snippets;
  6640. const [left, right] = getDirectReturnFunction(['e'], {
  6641. functionReturn: true,
  6642. lineBreakIndent: null,
  6643. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  6644. });
  6645. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  6646. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  6647. },
  6648. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  6649. const { _, getDirectReturnFunction, n } = snippets;
  6650. const [left, right] = getDirectReturnFunction(['e'], {
  6651. functionReturn: true,
  6652. lineBreakIndent: null,
  6653. name: INTEROP_DEFAULT_VARIABLE
  6654. });
  6655. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  6656. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  6657. },
  6658. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  6659. const { _, getDirectReturnFunction, n } = snippets;
  6660. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  6661. const [left, right] = getDirectReturnFunction(['e'], {
  6662. functionReturn: true,
  6663. lineBreakIndent: null,
  6664. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  6665. });
  6666. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  6667. }
  6668. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  6669. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  6670. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6671. `}${n}${n}`);
  6672. },
  6673. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, symbols) {
  6674. const { getDirectReturnFunction, getObject, n, _ } = snippets;
  6675. const [left, right] = getDirectReturnFunction(['e'], {
  6676. functionReturn: true,
  6677. lineBreakIndent: null,
  6678. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  6679. });
  6680. return `${left}${getFrozen(freeze, getWithToStringTag(symbols, getObject([
  6681. [null, `__proto__:${_}null`],
  6682. ['default', 'e']
  6683. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  6684. },
  6685. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  6686. const { _, n } = snippets;
  6687. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  6688. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6689. `}${n}${n}`);
  6690. },
  6691. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  6692. const { _, getDirectReturnFunction, n } = snippets;
  6693. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  6694. const [left, right] = getDirectReturnFunction(['e'], {
  6695. functionReturn: true,
  6696. lineBreakIndent: null,
  6697. name: INTEROP_NAMESPACE_VARIABLE
  6698. });
  6699. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  6700. }
  6701. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  6702. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  6703. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6704. `}${n}${n}`);
  6705. },
  6706. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  6707. const { _, cnst, n } = snippets;
  6708. const useForEach = cnst === 'var' && liveBindings;
  6709. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  6710. `${t}${loopOverNamespaces(`{${n}` +
  6711. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  6712. (liveBindings
  6713. ? useForEach
  6714. ? copyOwnPropertyLiveBinding
  6715. : copyPropertyLiveBinding
  6716. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  6717. `${t}${t}${t}}${n}` +
  6718. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  6719. `${t}return ${getFrozen(freeze, getWithToStringTag(symbols, 'n', snippets))};${n}` +
  6720. `}${n}${n}`);
  6721. }
  6722. };
  6723. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  6724. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  6725. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  6726. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, symbols) => {
  6727. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  6728. const copyProperty = `{${n}` +
  6729. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  6730. `${index}${t}}`;
  6731. return (`${index}${cnst} n${_}=${_}Object.create(null${symbols ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` +
  6732. `${index}if${_}(e)${_}{${n}` +
  6733. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  6734. `${index}}${n}` +
  6735. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  6736. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  6737. };
  6738. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  6739. ? `for${_}(${cnst} k in e)${_}${body}`
  6740. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  6741. isAsync: false,
  6742. name: null
  6743. })}${body})${s}`;
  6744. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  6745. if (useForEach) {
  6746. const [left, right] = getDirectReturnFunction(['e'], {
  6747. functionReturn: false,
  6748. lineBreakIndent: { base: t, t },
  6749. name: null
  6750. });
  6751. return (`m.forEach(${left}` +
  6752. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  6753. isAsync: false,
  6754. name: null
  6755. })}${body})${right});`);
  6756. }
  6757. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  6758. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  6759. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  6760. };
  6761. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  6762. const { _, n } = snippets;
  6763. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  6764. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  6765. `${index}}${n}`);
  6766. };
  6767. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  6768. const [left, right] = getDirectReturnFunction([], {
  6769. functionReturn: true,
  6770. lineBreakIndent: null,
  6771. name: null
  6772. });
  6773. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  6774. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  6775. `${index}${t}enumerable:${_}true,${n}` +
  6776. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  6777. `${index}});${n}`);
  6778. };
  6779. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  6780. const [left, right] = getDirectReturnFunction([], {
  6781. functionReturn: true,
  6782. lineBreakIndent: null,
  6783. name: null
  6784. });
  6785. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  6786. `${index}if${_}(d)${_}{${n}` +
  6787. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  6788. `${index}${t}${t}enumerable:${_}true,${n}` +
  6789. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  6790. `${index}${t}});${n}` +
  6791. `${index}}${n}`);
  6792. };
  6793. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  6794. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  6795. const getWithToStringTag = (symbols, fragment, { _, getObject }) => symbols
  6796. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  6797. : fragment;
  6798. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  6799. function getToStringTagValue(getObject) {
  6800. return getObject([['value', "'Module'"]], {
  6801. lineBreakIndent: null
  6802. });
  6803. }
  6804. class Literal extends NodeBase {
  6805. deoptimizeArgumentsOnInteractionAtPath() { }
  6806. getLiteralValueAtPath(path) {
  6807. if (path.length > 0 ||
  6808. // unknown literals can also be null but do not start with an "n"
  6809. (this.value === null && this.scope.context.code.charCodeAt(this.start) !== 110) ||
  6810. typeof this.value === 'bigint' ||
  6811. // to support shims for regular expressions
  6812. this.scope.context.code.charCodeAt(this.start) === 47) {
  6813. return UnknownValue;
  6814. }
  6815. return this.value;
  6816. }
  6817. getReturnExpressionWhenCalledAtPath(path) {
  6818. if (path.length !== 1)
  6819. return UNKNOWN_RETURN_EXPRESSION;
  6820. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  6821. }
  6822. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6823. switch (interaction.type) {
  6824. case INTERACTION_ACCESSED: {
  6825. return path.length > (this.value === null ? 0 : 1);
  6826. }
  6827. case INTERACTION_ASSIGNED: {
  6828. return true;
  6829. }
  6830. case INTERACTION_CALLED: {
  6831. if (this.included &&
  6832. this.value instanceof RegExp &&
  6833. (this.value.global || this.value.sticky)) {
  6834. return true;
  6835. }
  6836. return (path.length !== 1 ||
  6837. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  6838. }
  6839. }
  6840. }
  6841. initialise() {
  6842. super.initialise();
  6843. this.members = getLiteralMembersForValue(this.value);
  6844. }
  6845. parseNode(esTreeNode) {
  6846. this.value = esTreeNode.value;
  6847. this.regex = esTreeNode.regex;
  6848. return super.parseNode(esTreeNode);
  6849. }
  6850. render(code) {
  6851. if (typeof this.value === 'string') {
  6852. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  6853. }
  6854. }
  6855. }
  6856. Literal.prototype.includeNode = onlyIncludeSelf;
  6857. function getChainElementLiteralValueAtPath(element, object, path, recursionTracker, origin) {
  6858. if ('getLiteralValueAtPathAsChainElement' in object) {
  6859. const calleeValue = object.getLiteralValueAtPathAsChainElement(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin);
  6860. if (calleeValue === IS_SKIPPED_CHAIN || (element.optional && calleeValue == null)) {
  6861. return IS_SKIPPED_CHAIN;
  6862. }
  6863. }
  6864. else if (element.optional &&
  6865. object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null) {
  6866. return IS_SKIPPED_CHAIN;
  6867. }
  6868. return element.getLiteralValueAtPath(path, recursionTracker, origin);
  6869. }
  6870. function getResolvablePropertyKey(memberExpression) {
  6871. return memberExpression.computed
  6872. ? getResolvableComputedPropertyKey(memberExpression.property)
  6873. : memberExpression.property.name;
  6874. }
  6875. function getResolvableComputedPropertyKey(propertyKey) {
  6876. if (propertyKey instanceof Literal) {
  6877. return String(propertyKey.value);
  6878. }
  6879. return null;
  6880. }
  6881. function getPathIfNotComputed(memberExpression) {
  6882. const nextPathKey = memberExpression.propertyKey;
  6883. const object = memberExpression.object;
  6884. if (typeof nextPathKey === 'string') {
  6885. if (object instanceof Identifier) {
  6886. return [
  6887. { key: object.name, pos: object.start },
  6888. { key: nextPathKey, pos: memberExpression.property.start }
  6889. ];
  6890. }
  6891. if (object instanceof MemberExpression) {
  6892. const parentPath = getPathIfNotComputed(object);
  6893. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  6894. }
  6895. }
  6896. return null;
  6897. }
  6898. function getStringFromPath(path) {
  6899. let pathString = path[0].key;
  6900. for (let index = 1; index < path.length; index++) {
  6901. pathString += '.' + path[index].key;
  6902. }
  6903. return pathString;
  6904. }
  6905. class MemberExpression extends NodeBase {
  6906. constructor() {
  6907. super(...arguments);
  6908. this.variable = null;
  6909. this.expressionsToBeDeoptimized = [];
  6910. }
  6911. get computed() {
  6912. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  6913. }
  6914. set computed(value) {
  6915. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  6916. }
  6917. get optional() {
  6918. return isFlagSet(this.flags, 128 /* Flag.optional */);
  6919. }
  6920. set optional(value) {
  6921. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  6922. }
  6923. get assignmentDeoptimized() {
  6924. return isFlagSet(this.flags, 16 /* Flag.assignmentDeoptimized */);
  6925. }
  6926. set assignmentDeoptimized(value) {
  6927. this.flags = setFlag(this.flags, 16 /* Flag.assignmentDeoptimized */, value);
  6928. }
  6929. get bound() {
  6930. return isFlagSet(this.flags, 32 /* Flag.bound */);
  6931. }
  6932. set bound(value) {
  6933. this.flags = setFlag(this.flags, 32 /* Flag.bound */, value);
  6934. }
  6935. get isUndefined() {
  6936. return isFlagSet(this.flags, 64 /* Flag.isUndefined */);
  6937. }
  6938. set isUndefined(value) {
  6939. this.flags = setFlag(this.flags, 64 /* Flag.isUndefined */, value);
  6940. }
  6941. bind() {
  6942. this.bound = true;
  6943. const path = getPathIfNotComputed(this);
  6944. const baseVariable = path && this.scope.findVariable(path[0].key);
  6945. if (baseVariable?.isNamespace) {
  6946. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.scope.context);
  6947. if (!resolvedVariable) {
  6948. super.bind();
  6949. }
  6950. else if (resolvedVariable === 'undefined') {
  6951. this.isUndefined = true;
  6952. }
  6953. else {
  6954. this.variable = resolvedVariable;
  6955. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  6956. }
  6957. }
  6958. else {
  6959. super.bind();
  6960. }
  6961. }
  6962. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6963. if (this.variable) {
  6964. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6965. }
  6966. else if (!this.isUndefined) {
  6967. if (path.length < MAX_PATH_DEPTH) {
  6968. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, this.propertyKey === UnknownKey ? UNKNOWN_PATH : [this.propertyKey, ...path], recursionTracker);
  6969. }
  6970. else {
  6971. deoptimizeInteraction(interaction);
  6972. }
  6973. }
  6974. }
  6975. deoptimizeAssignment(destructuredInitPath, init) {
  6976. this.deoptimizePath(EMPTY_PATH);
  6977. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  6978. }
  6979. deoptimizeCache() {
  6980. if (this.propertyKey === this.dynamicPropertyKey)
  6981. return;
  6982. const { expressionsToBeDeoptimized, object } = this;
  6983. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  6984. this.dynamicPropertyKey = this.propertyKey;
  6985. object.deoptimizePath(UNKNOWN_PATH);
  6986. if (this.included) {
  6987. object.includePath(UNKNOWN_PATH, createInclusionContext());
  6988. }
  6989. for (const expression of expressionsToBeDeoptimized) {
  6990. expression.deoptimizeCache();
  6991. }
  6992. }
  6993. deoptimizePath(path) {
  6994. if (path.length === 0)
  6995. this.disallowNamespaceReassignment();
  6996. if (this.variable) {
  6997. this.variable.deoptimizePath(path);
  6998. }
  6999. else if (!this.isUndefined) {
  7000. const { propertyKey } = this;
  7001. this.object.deoptimizePath([
  7002. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  7003. ...(path.length < MAX_PATH_DEPTH
  7004. ? path
  7005. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  7006. ]);
  7007. }
  7008. }
  7009. getLiteralValueAtPath(path, recursionTracker, origin) {
  7010. if (this.variable) {
  7011. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  7012. }
  7013. if (this.isUndefined) {
  7014. return undefined;
  7015. }
  7016. const propertyKey = this.getDynamicPropertyKey();
  7017. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  7018. if (propertyKey !== this.propertyKey)
  7019. this.expressionsToBeDeoptimized.push(origin);
  7020. return this.object.getLiteralValueAtPath([propertyKey, ...path], recursionTracker, origin);
  7021. }
  7022. return UnknownValue;
  7023. }
  7024. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  7025. if (this.variable) {
  7026. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  7027. }
  7028. if (this.isUndefined) {
  7029. return undefined;
  7030. }
  7031. return getChainElementLiteralValueAtPath(this, this.object, path, recursionTracker, origin);
  7032. }
  7033. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7034. if (this.variable) {
  7035. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7036. }
  7037. if (this.isUndefined) {
  7038. return [UNDEFINED_EXPRESSION, false];
  7039. }
  7040. const propertyKey = this.getDynamicPropertyKey();
  7041. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  7042. if (propertyKey !== this.propertyKey)
  7043. this.expressionsToBeDeoptimized.push(origin);
  7044. return this.object.getReturnExpressionWhenCalledAtPath([propertyKey, ...path], interaction, recursionTracker, origin);
  7045. }
  7046. return UNKNOWN_RETURN_EXPRESSION;
  7047. }
  7048. hasEffects(context) {
  7049. if (!this.deoptimized)
  7050. this.applyDeoptimizations();
  7051. return (this.property.hasEffects(context) ||
  7052. this.object.hasEffects(context) ||
  7053. this.hasAccessEffect(context));
  7054. }
  7055. hasEffectsAsChainElement(context) {
  7056. if (this.variable || this.isUndefined)
  7057. return this.hasEffects(context);
  7058. const objectHasEffects = 'hasEffectsAsChainElement' in this.object
  7059. ? this.object.hasEffectsAsChainElement(context)
  7060. : this.object.hasEffects(context);
  7061. if (objectHasEffects === IS_SKIPPED_CHAIN)
  7062. return IS_SKIPPED_CHAIN;
  7063. if (this.optional &&
  7064. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  7065. return objectHasEffects || IS_SKIPPED_CHAIN;
  7066. }
  7067. // We only apply deoptimizations lazily once we know we are not skipping
  7068. if (!this.deoptimized)
  7069. this.applyDeoptimizations();
  7070. return objectHasEffects || this.property.hasEffects(context) || this.hasAccessEffect(context);
  7071. }
  7072. hasEffectsAsAssignmentTarget(context, checkAccess) {
  7073. if (checkAccess && !this.deoptimized)
  7074. this.applyDeoptimizations();
  7075. if (!this.assignmentDeoptimized)
  7076. this.applyAssignmentDeoptimization();
  7077. return (this.property.hasEffects(context) ||
  7078. this.object.hasEffects(context) ||
  7079. (checkAccess && this.hasAccessEffect(context)) ||
  7080. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  7081. }
  7082. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7083. if (this.variable) {
  7084. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  7085. }
  7086. if (this.isUndefined) {
  7087. return true;
  7088. }
  7089. if (path.length < MAX_PATH_DEPTH) {
  7090. return this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey(), ...path], interaction, context);
  7091. }
  7092. return true;
  7093. }
  7094. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  7095. return (destructuredInitPath.length > 0 &&
  7096. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  7097. }
  7098. include(context, includeChildrenRecursively) {
  7099. if (!this.included)
  7100. this.includeNode(context);
  7101. this.object.include(context, includeChildrenRecursively);
  7102. this.property.include(context, includeChildrenRecursively);
  7103. }
  7104. includeNode(context) {
  7105. this.included = true;
  7106. if (!this.deoptimized)
  7107. this.applyDeoptimizations();
  7108. if (this.variable) {
  7109. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  7110. }
  7111. else if (!this.isUndefined) {
  7112. this.object.includePath([this.propertyKey], context);
  7113. }
  7114. }
  7115. includeNodeAsAssignmentTarget(context) {
  7116. this.included = true;
  7117. if (!this.assignmentDeoptimized)
  7118. this.applyAssignmentDeoptimization();
  7119. if (this.variable) {
  7120. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  7121. }
  7122. else if (!this.isUndefined) {
  7123. this.object.includePath([this.propertyKey], context);
  7124. }
  7125. }
  7126. includePath(path, context) {
  7127. if (!this.included)
  7128. this.includeNode(context);
  7129. if (this.variable) {
  7130. this.variable?.includePath(path, context);
  7131. }
  7132. else if (!this.isUndefined) {
  7133. this.object.includePath([
  7134. this.propertyKey,
  7135. ...(path.length < MAX_PATH_DEPTH
  7136. ? path
  7137. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  7138. ], context);
  7139. }
  7140. }
  7141. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  7142. if (!this.included)
  7143. this.includeNodeAsAssignmentTarget(context);
  7144. if (deoptimizeAccess && !this.deoptimized)
  7145. this.applyDeoptimizations();
  7146. this.object.include(context, includeChildrenRecursively);
  7147. this.property.include(context, includeChildrenRecursively);
  7148. }
  7149. includeCallArguments(interaction, context) {
  7150. if (this.variable) {
  7151. this.variable.includeCallArguments(interaction, context);
  7152. }
  7153. else {
  7154. if (isImportExpressionNode(this.object) ||
  7155. /**
  7156. * const c = await import('foo')
  7157. * c.foo();
  7158. */
  7159. (this.object.variable &&
  7160. !this.object.variable.isReassigned &&
  7161. this.object.variable instanceof LocalVariable &&
  7162. isAwaitExpressionNode(this.object.variable.init) &&
  7163. isImportExpressionNode(this.object.variable.init.argument))) {
  7164. includeInteractionWithoutThis(interaction, context);
  7165. }
  7166. else {
  7167. includeInteraction(interaction, context);
  7168. }
  7169. }
  7170. }
  7171. includeDestructuredIfNecessary() {
  7172. /* istanbul ignore next */
  7173. this.scope.context.error({
  7174. message: 'includeDestructuredIfNecessary is currently not supported for MemberExpressions'
  7175. }, this.start);
  7176. }
  7177. initialise() {
  7178. super.initialise();
  7179. this.dynamicPropertyKey = getResolvablePropertyKey(this);
  7180. this.propertyKey = this.dynamicPropertyKey === null ? UnknownKey : this.dynamicPropertyKey;
  7181. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  7182. }
  7183. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  7184. if (this.variable || this.isUndefined) {
  7185. const { snippets: { getPropertyAccess } } = options;
  7186. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  7187. if (renderedParentType && isCalleeOfRenderedParent)
  7188. replacement = '0, ' + replacement;
  7189. code.overwrite(this.start, this.end, replacement, {
  7190. contentOnly: true,
  7191. storeName: true
  7192. });
  7193. }
  7194. else {
  7195. if (renderedParentType && isCalleeOfRenderedParent) {
  7196. code.appendRight(this.start, '0, ');
  7197. }
  7198. this.object.render(code, options, { renderedSurroundingElement });
  7199. this.property.render(code, options);
  7200. }
  7201. }
  7202. setAssignedValue(value) {
  7203. this.assignmentInteraction = {
  7204. args: [this.object, value],
  7205. type: INTERACTION_ASSIGNED
  7206. };
  7207. }
  7208. applyDeoptimizations() {
  7209. this.deoptimized = true;
  7210. const { propertyReadSideEffects } = this.scope.context.options
  7211. .treeshake;
  7212. if (
  7213. // Namespaces are not bound and should not be deoptimized
  7214. this.bound &&
  7215. propertyReadSideEffects &&
  7216. !(this.variable || this.isUndefined)) {
  7217. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  7218. this.scope.context.requestTreeshakingPass();
  7219. }
  7220. if (this.variable) {
  7221. this.variable.addUsedPlace(this);
  7222. this.scope.context.requestTreeshakingPass();
  7223. }
  7224. }
  7225. applyAssignmentDeoptimization() {
  7226. this.assignmentDeoptimized = true;
  7227. const { propertyReadSideEffects } = this.scope.context.options
  7228. .treeshake;
  7229. if (
  7230. // Namespaces are not bound and should not be deoptimized
  7231. this.bound &&
  7232. propertyReadSideEffects &&
  7233. !(this.variable || this.isUndefined)) {
  7234. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  7235. this.scope.context.requestTreeshakingPass();
  7236. }
  7237. }
  7238. disallowNamespaceReassignment() {
  7239. if (this.object instanceof Identifier) {
  7240. const variable = this.scope.findVariable(this.object.name);
  7241. if (variable.isNamespace) {
  7242. if (this.variable) {
  7243. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, createInclusionContext());
  7244. }
  7245. this.scope.context.log(LOGLEVEL_WARN, logIllegalImportReassignment(this.object.name, this.scope.context.module.id), this.start);
  7246. }
  7247. }
  7248. }
  7249. getDynamicPropertyKey() {
  7250. if (this.dynamicPropertyKey === null) {
  7251. this.dynamicPropertyKey = this.propertyKey;
  7252. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7253. return (this.dynamicPropertyKey =
  7254. value === SymbolToStringTag
  7255. ? value
  7256. : typeof value === 'symbol'
  7257. ? UnknownKey
  7258. : String(value));
  7259. }
  7260. return this.dynamicPropertyKey;
  7261. }
  7262. hasAccessEffect(context) {
  7263. const { propertyReadSideEffects } = this.scope.context.options
  7264. .treeshake;
  7265. return (!(this.variable || this.isUndefined) &&
  7266. propertyReadSideEffects &&
  7267. (propertyReadSideEffects === 'always' ||
  7268. this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey()], this.accessInteraction, context)));
  7269. }
  7270. }
  7271. function resolveNamespaceVariables(baseVariable, path, astContext) {
  7272. if (path.length === 0)
  7273. return baseVariable;
  7274. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  7275. return null;
  7276. const exportName = path[0].key;
  7277. const [variable, options] = baseVariable.context.traceExport(exportName);
  7278. if (!variable) {
  7279. if (path.length === 1) {
  7280. const fileName = baseVariable.context.fileName;
  7281. astContext.log(LOGLEVEL_WARN, logMissingExport(exportName, astContext.module.id, fileName, !!options?.missingButExportExists), path[0].pos);
  7282. return 'undefined';
  7283. }
  7284. return null;
  7285. }
  7286. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  7287. }
  7288. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  7289. const FILE_OBJ_PREFIX = 'ROLLUP_FILE_URL_OBJ_';
  7290. const IMPORT = 'import';
  7291. class MetaProperty extends NodeBase {
  7292. constructor() {
  7293. super(...arguments);
  7294. this.metaProperty = null;
  7295. this.preliminaryChunkId = null;
  7296. this.referenceId = null;
  7297. }
  7298. getReferencedFileName(outputPluginDriver) {
  7299. const { meta: { name }, metaProperty } = this;
  7300. if (name === IMPORT) {
  7301. if (metaProperty?.startsWith(FILE_OBJ_PREFIX)) {
  7302. return outputPluginDriver.getFileName(metaProperty.slice(FILE_OBJ_PREFIX.length));
  7303. }
  7304. else if (metaProperty?.startsWith(FILE_PREFIX)) {
  7305. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  7306. }
  7307. }
  7308. return null;
  7309. }
  7310. hasEffects() {
  7311. return false;
  7312. }
  7313. hasEffectsOnInteractionAtPath(path, { type }) {
  7314. return path.length > 1 || type !== INTERACTION_ACCESSED;
  7315. }
  7316. include() {
  7317. if (!this.included)
  7318. this.includeNode();
  7319. }
  7320. includeNode() {
  7321. this.included = true;
  7322. if (this.meta.name === IMPORT) {
  7323. this.scope.context.addImportMeta(this);
  7324. const parent = this.parent;
  7325. const metaProperty = (this.metaProperty =
  7326. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  7327. ? parent.propertyKey
  7328. : null);
  7329. if (metaProperty?.startsWith(FILE_OBJ_PREFIX)) {
  7330. this.referenceId = metaProperty.slice(FILE_OBJ_PREFIX.length);
  7331. }
  7332. else if (metaProperty?.startsWith(FILE_PREFIX)) {
  7333. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  7334. }
  7335. }
  7336. }
  7337. render(code, renderOptions) {
  7338. const { format, pluginDriver, snippets } = renderOptions;
  7339. const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  7340. const { id: moduleId } = module;
  7341. if (name !== IMPORT)
  7342. return;
  7343. const chunkId = preliminaryChunkId;
  7344. if (referenceId) {
  7345. const fileName = pluginDriver.getFileName(referenceId);
  7346. const relativePath = normalize(relative(dirname(chunkId), fileName));
  7347. const isUrlObject = !!metaProperty?.startsWith(FILE_OBJ_PREFIX);
  7348. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  7349. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  7350. ]) || relativeUrlMechanisms[format](relativePath, isUrlObject);
  7351. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7352. return;
  7353. }
  7354. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  7355. metaProperty,
  7356. { chunkId, format, moduleId }
  7357. ]);
  7358. if (!replacement) {
  7359. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  7360. renderOptions.accessedDocumentCurrentScript ||=
  7361. formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
  7362. }
  7363. if (typeof replacement === 'string') {
  7364. if (parent instanceof MemberExpression) {
  7365. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7366. }
  7367. else {
  7368. code.overwrite(start, end, replacement, { contentOnly: true });
  7369. }
  7370. }
  7371. }
  7372. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  7373. this.preliminaryChunkId = preliminaryChunkId;
  7374. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) || this.metaProperty?.startsWith(FILE_OBJ_PREFIX)
  7375. ? accessedFileUrlGlobals
  7376. : accessedMetaUrlGlobals)[format];
  7377. if (accessedGlobals.length > 0) {
  7378. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7379. }
  7380. }
  7381. }
  7382. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  7383. const accessedMetaUrlGlobals = {
  7384. amd: ['document', 'module', 'URL'],
  7385. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  7386. es: [],
  7387. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  7388. system: ['module'],
  7389. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  7390. };
  7391. const accessedFileUrlGlobals = {
  7392. amd: ['document', 'require', 'URL'],
  7393. cjs: ['document', 'require', 'URL'],
  7394. es: [],
  7395. iife: ['document', 'URL'],
  7396. system: ['module', 'URL'],
  7397. umd: ['document', 'require', 'URL']
  7398. };
  7399. const getResolveUrl = (path, asObject, URL = 'URL') => `new ${URL}(${path})${asObject ? '' : '.href'}`;
  7400. 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);
  7401. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  7402. const urlMechanism = getUrl(chunkId);
  7403. return property === null
  7404. ? `({ url: ${urlMechanism} })`
  7405. : property === 'url'
  7406. ? urlMechanism
  7407. : 'undefined';
  7408. };
  7409. const getFileUrlFromFullPath = (path, asObject) => `require('u' + 'rl').pathToFileURL(${path})${asObject ? '' : '.href'}`;
  7410. const getFileUrlFromRelativePath = (path, asObject) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`, asObject);
  7411. 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)`;
  7412. const relativeUrlMechanisms = {
  7413. amd: (relativePath, asObject) => {
  7414. if (relativePath[0] !== '.')
  7415. relativePath = './' + relativePath;
  7416. return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`, asObject);
  7417. },
  7418. cjs: (relativePath, asObject) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath, asObject)} : ${getRelativeUrlFromDocument(relativePath, asObject)})`,
  7419. es: (relativePath, asObject) => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`, asObject),
  7420. iife: (relativePath, asObject) => getRelativeUrlFromDocument(relativePath, asObject),
  7421. system: (relativePath, asObject) => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`, asObject),
  7422. umd: (relativePath, asObject) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath, asObject)} : ${getRelativeUrlFromDocument(relativePath, asObject, true)})`
  7423. };
  7424. const importMetaMechanisms = {
  7425. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`, false)),
  7426. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename', false)} : ${getUrlFromDocument(chunkId)})`),
  7427. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  7428. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  7429. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename', false)} : ${getUrlFromDocument(chunkId, true)})`)
  7430. };
  7431. class UndefinedVariable extends Variable {
  7432. constructor() {
  7433. super('undefined');
  7434. }
  7435. getLiteralValueAtPath() {
  7436. return undefined;
  7437. }
  7438. }
  7439. class ExportDefaultVariable extends LocalVariable {
  7440. constructor(name, exportDefaultDeclaration, context) {
  7441. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, EMPTY_PATH, context, 'other');
  7442. this.hasId = false;
  7443. this.originalId = null;
  7444. this.originalVariable = null;
  7445. const declaration = exportDefaultDeclaration.declaration;
  7446. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  7447. declaration.id) {
  7448. this.hasId = true;
  7449. this.originalId = declaration.id;
  7450. }
  7451. else if (declaration instanceof Identifier) {
  7452. this.originalId = declaration;
  7453. }
  7454. }
  7455. addReference(identifier) {
  7456. if (!this.hasId) {
  7457. this.name = identifier.name;
  7458. }
  7459. }
  7460. addUsedPlace(usedPlace) {
  7461. const original = this.getOriginalVariable();
  7462. if (original === this) {
  7463. super.addUsedPlace(usedPlace);
  7464. }
  7465. else {
  7466. original.addUsedPlace(usedPlace);
  7467. }
  7468. }
  7469. forbidName(name) {
  7470. const original = this.getOriginalVariable();
  7471. if (original === this) {
  7472. super.forbidName(name);
  7473. }
  7474. else {
  7475. original.forbidName(name);
  7476. }
  7477. }
  7478. getAssignedVariableName() {
  7479. return (this.originalId && this.originalId.name) || null;
  7480. }
  7481. getBaseVariableName() {
  7482. const original = this.getOriginalVariable();
  7483. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  7484. }
  7485. getDirectOriginalVariable() {
  7486. return this.originalId &&
  7487. (this.hasId ||
  7488. !(this.originalId.isPossibleTDZ() ||
  7489. this.originalId.variable.isReassigned ||
  7490. this.originalId.variable instanceof UndefinedVariable ||
  7491. // this avoids a circular dependency
  7492. 'syntheticNamespace' in this.originalId.variable))
  7493. ? this.originalId.variable
  7494. : null;
  7495. }
  7496. getName(getPropertyAccess) {
  7497. const original = this.getOriginalVariable();
  7498. return original === this
  7499. ? super.getName(getPropertyAccess)
  7500. : original.getName(getPropertyAccess);
  7501. }
  7502. getOriginalVariable() {
  7503. if (this.originalVariable)
  7504. return this.originalVariable;
  7505. // eslint-disable-next-line @typescript-eslint/no-this-alias
  7506. let original = this;
  7507. let currentVariable;
  7508. const checkedVariables = new Set();
  7509. do {
  7510. checkedVariables.add(original);
  7511. currentVariable = original;
  7512. original = currentVariable.getDirectOriginalVariable();
  7513. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  7514. return (this.originalVariable = original || currentVariable);
  7515. }
  7516. }
  7517. class NamespaceVariable extends Variable {
  7518. constructor(context) {
  7519. super(context.getModuleName());
  7520. this.memberVariables = null;
  7521. this.mergedNamespaces = [];
  7522. this.referencedEarly = false;
  7523. this.references = [];
  7524. this.context = context;
  7525. this.module = context.module;
  7526. }
  7527. addReference(identifier) {
  7528. this.references.push(identifier);
  7529. this.name = identifier.name;
  7530. }
  7531. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7532. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  7533. const key = path[0];
  7534. if (typeof key === 'string') {
  7535. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  7536. }
  7537. else {
  7538. deoptimizeInteraction(interaction);
  7539. }
  7540. }
  7541. }
  7542. deoptimizePath(path) {
  7543. if (path.length > 1) {
  7544. const key = path[0];
  7545. if (typeof key === 'string') {
  7546. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  7547. }
  7548. }
  7549. }
  7550. getLiteralValueAtPath(path) {
  7551. if (path[0] === SymbolToStringTag) {
  7552. return 'Module';
  7553. }
  7554. return UnknownValue;
  7555. }
  7556. getMemberVariables() {
  7557. if (this.memberVariables) {
  7558. return this.memberVariables;
  7559. }
  7560. const memberVariables = Object.create(null);
  7561. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  7562. for (const name of sortedExports) {
  7563. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  7564. const [exportedVariable] = this.context.traceExport(name);
  7565. if (exportedVariable) {
  7566. memberVariables[name] = exportedVariable;
  7567. }
  7568. }
  7569. }
  7570. return (this.memberVariables = memberVariables);
  7571. }
  7572. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7573. const { type } = interaction;
  7574. if (path.length === 0) {
  7575. // This can only be a call anyway
  7576. return true;
  7577. }
  7578. if (path.length === 1 && type !== INTERACTION_CALLED) {
  7579. return type === INTERACTION_ASSIGNED;
  7580. }
  7581. const key = path[0];
  7582. if (typeof key !== 'string') {
  7583. return true;
  7584. }
  7585. const memberVariable = this.getMemberVariables()[key];
  7586. return (!memberVariable ||
  7587. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  7588. }
  7589. includePath(path, context) {
  7590. super.includePath(path, context);
  7591. this.context.includeAllExports();
  7592. }
  7593. prepare(accessedGlobalsByScope) {
  7594. if (this.mergedNamespaces.length > 0) {
  7595. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  7596. }
  7597. }
  7598. renderBlock(options) {
  7599. const { exportNamesByVariable, format, freeze, indent: t, symbols, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  7600. const memberVariables = this.getMemberVariables();
  7601. const members = Object.entries(memberVariables)
  7602. .filter(([_, variable]) => variable.included)
  7603. .map(([name, variable]) => {
  7604. if (this.referencedEarly || variable.isReassigned || variable === this) {
  7605. return [
  7606. null,
  7607. `get ${stringifyObjectKeyIfNeeded(name)}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  7608. ];
  7609. }
  7610. return [name, variable.getName(getPropertyAccess)];
  7611. });
  7612. members.unshift([null, `__proto__:${_}null`]);
  7613. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  7614. if (this.mergedNamespaces.length > 0) {
  7615. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  7616. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  7617. }
  7618. else {
  7619. // The helper to merge namespaces will also take care of freezing and toStringTag
  7620. if (symbols) {
  7621. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  7622. }
  7623. if (freeze) {
  7624. output = `/*#__PURE__*/Object.freeze(${output})`;
  7625. }
  7626. }
  7627. const name = this.getName(getPropertyAccess);
  7628. output = `${cnst} ${name}${_}=${_}${output};`;
  7629. if (format === 'system' && exportNamesByVariable.has(this)) {
  7630. output += `${n}${getSystemExportStatement([this], options)};`;
  7631. }
  7632. return output;
  7633. }
  7634. renderFirst() {
  7635. return this.referencedEarly;
  7636. }
  7637. setMergedNamespaces(mergedNamespaces) {
  7638. this.mergedNamespaces = mergedNamespaces;
  7639. const moduleExecIndex = this.context.getModuleExecIndex();
  7640. for (const identifier of this.references) {
  7641. const { context } = identifier.scope;
  7642. if (context.getModuleExecIndex() <= moduleExecIndex) {
  7643. this.referencedEarly = true;
  7644. break;
  7645. }
  7646. }
  7647. }
  7648. }
  7649. NamespaceVariable.prototype.isNamespace = true;
  7650. class SyntheticNamedExportVariable extends Variable {
  7651. constructor(context, name, syntheticNamespace) {
  7652. super(name);
  7653. this.baseVariable = null;
  7654. this.context = context;
  7655. this.module = context.module;
  7656. this.syntheticNamespace = syntheticNamespace;
  7657. }
  7658. getBaseVariable() {
  7659. if (this.baseVariable)
  7660. return this.baseVariable;
  7661. let baseVariable = this.syntheticNamespace;
  7662. while (baseVariable instanceof ExportDefaultVariable ||
  7663. baseVariable instanceof SyntheticNamedExportVariable) {
  7664. if (baseVariable instanceof ExportDefaultVariable) {
  7665. const original = baseVariable.getOriginalVariable();
  7666. if (original === baseVariable)
  7667. break;
  7668. baseVariable = original;
  7669. }
  7670. if (baseVariable instanceof SyntheticNamedExportVariable) {
  7671. baseVariable = baseVariable.syntheticNamespace;
  7672. }
  7673. }
  7674. return (this.baseVariable = baseVariable);
  7675. }
  7676. getBaseVariableName() {
  7677. return this.syntheticNamespace.getBaseVariableName();
  7678. }
  7679. getName(getPropertyAccess) {
  7680. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  7681. }
  7682. includePath(path, context) {
  7683. super.includePath(path, context);
  7684. this.context.includeVariableInModule(this.syntheticNamespace, path, context);
  7685. }
  7686. setRenderNames(baseName, name) {
  7687. super.setRenderNames(baseName, name);
  7688. }
  7689. }
  7690. class ExternalChunk {
  7691. constructor(module, options, inputBase) {
  7692. this.options = options;
  7693. this.inputBase = inputBase;
  7694. this.defaultVariableName = '';
  7695. this.namespaceVariableName = '';
  7696. this.variableName = '';
  7697. this.fileName = null;
  7698. this.importAttributes = null;
  7699. this.id = module.id;
  7700. this.moduleInfo = module.info;
  7701. this.renormalizeRenderPath = module.renormalizeRenderPath;
  7702. this.suggestedVariableName = module.suggestedVariableName;
  7703. }
  7704. getFileName() {
  7705. if (this.fileName) {
  7706. return this.fileName;
  7707. }
  7708. const { paths } = this.options;
  7709. return (this.fileName =
  7710. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  7711. (this.renormalizeRenderPath ? normalize(relative(this.inputBase, this.id)) : this.id));
  7712. }
  7713. getImportAttributes(snippets) {
  7714. return (this.importAttributes ||= formatAttributes(['es', 'cjs'].includes(this.options.format) &&
  7715. this.options.externalImportAttributes &&
  7716. this.moduleInfo.attributes, snippets));
  7717. }
  7718. getImportPath(importer) {
  7719. return escapeId(this.renormalizeRenderPath
  7720. ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  7721. : this.getFileName());
  7722. }
  7723. }
  7724. function formatAttributes(attributes, { getObject }) {
  7725. if (!attributes) {
  7726. return null;
  7727. }
  7728. const assertionEntries = Object.entries(attributes).map(([key, value]) => [key, `'${value}'`]);
  7729. if (assertionEntries.length > 0) {
  7730. return getObject(assertionEntries, { lineBreakIndent: null });
  7731. }
  7732. return null;
  7733. }
  7734. function removeJsExtension(name) {
  7735. return name.endsWith('.js') ? name.slice(0, -3) : name;
  7736. }
  7737. function getCompleteAmdId(options, chunkId) {
  7738. if (options.autoId) {
  7739. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  7740. }
  7741. return options.id ?? '';
  7742. }
  7743. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
  7744. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  7745. if (!namedExportsMode) {
  7746. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  7747. }
  7748. let exportBlock = '';
  7749. if (namedExportsMode) {
  7750. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7751. if (!reexports) {
  7752. continue;
  7753. }
  7754. for (const specifier of reexports) {
  7755. if (specifier.reexported !== '*') {
  7756. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  7757. if (exportBlock)
  7758. exportBlock += n;
  7759. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  7760. const [left, right] = getDirectReturnFunction([], {
  7761. functionReturn: true,
  7762. lineBreakIndent: null,
  7763. name: null
  7764. });
  7765. exportBlock +=
  7766. `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
  7767. `${t}enumerable:${_}true,${n}` +
  7768. `${t}get:${_}${left}${importName}${right}${n}});`;
  7769. }
  7770. else if (specifier.reexported === '__proto__') {
  7771. exportBlock +=
  7772. `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  7773. `${t}enumerable:${_}true,${n}` +
  7774. `${t}value:${_}${importName}${n}});`;
  7775. }
  7776. else {
  7777. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  7778. }
  7779. }
  7780. }
  7781. }
  7782. }
  7783. for (const { exported, local } of exports) {
  7784. const lhs = `exports${getPropertyAccess(exported)}`;
  7785. const rhs = local;
  7786. if (lhs !== rhs) {
  7787. if (exportBlock)
  7788. exportBlock += n;
  7789. exportBlock +=
  7790. exported === '__proto__'
  7791. ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  7792. `${t}enumerable:${_}true,${n}` +
  7793. `${t}value:${_}${rhs}${n}});`
  7794. : `${lhs}${_}=${_}${rhs};`;
  7795. }
  7796. }
  7797. if (namedExportsMode) {
  7798. for (const { name, reexports } of dependencies) {
  7799. if (!reexports) {
  7800. continue;
  7801. }
  7802. for (const specifier of reexports) {
  7803. if (specifier.reexported === '*') {
  7804. if (exportBlock)
  7805. exportBlock += n;
  7806. if (!specifier.needsLiveBinding && reexportProtoFromExternal) {
  7807. const protoString = "'__proto__'";
  7808. exportBlock +=
  7809. `Object.prototype.hasOwnProperty.call(${name},${_}${protoString})${_}&&${n}` +
  7810. `${t}!Object.prototype.hasOwnProperty.call(exports,${_}${protoString})${_}&&${n}` +
  7811. `${t}Object.defineProperty(exports,${_}${protoString},${_}{${n}` +
  7812. `${t}${t}enumerable:${_}true,${n}` +
  7813. `${t}${t}value:${_}${name}[${protoString}]${n}` +
  7814. `${t}});${n}${n}`;
  7815. }
  7816. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  7817. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  7818. isAsync: false,
  7819. name: null
  7820. })}${copyPropertyIfNecessary});`;
  7821. }
  7822. }
  7823. }
  7824. }
  7825. if (exportBlock) {
  7826. return `${n}${n}${exportBlock}`;
  7827. }
  7828. return '';
  7829. }
  7830. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  7831. if (exports.length > 0) {
  7832. return exports[0].local;
  7833. }
  7834. else {
  7835. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7836. if (reexports) {
  7837. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  7838. }
  7839. }
  7840. }
  7841. }
  7842. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  7843. if (imported === 'default') {
  7844. if (!isChunk) {
  7845. const moduleInterop = interop(moduleId);
  7846. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  7847. ? defaultVariableName
  7848. : moduleVariableName;
  7849. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  7850. ? `${variableName}${getPropertyAccess('default')}`
  7851. : variableName;
  7852. }
  7853. return depNamedExportsMode
  7854. ? `${moduleVariableName}${getPropertyAccess('default')}`
  7855. : moduleVariableName;
  7856. }
  7857. if (imported === '*') {
  7858. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  7859. ? namespaceVariableName
  7860. : moduleVariableName;
  7861. }
  7862. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  7863. }
  7864. function getEsModuleValue(getObject) {
  7865. return getObject([['value', 'true']], {
  7866. lineBreakIndent: null
  7867. });
  7868. }
  7869. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  7870. if (hasNamedExports) {
  7871. if (addEsModule) {
  7872. if (addNamespaceToStringTag) {
  7873. return `Object.defineProperties(exports,${_}${getObject([
  7874. ['__esModule', getEsModuleValue(getObject)],
  7875. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  7876. ], {
  7877. lineBreakIndent: null
  7878. })});`;
  7879. }
  7880. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  7881. }
  7882. if (addNamespaceToStringTag) {
  7883. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  7884. }
  7885. }
  7886. return '';
  7887. }
  7888. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  7889. if (needsLiveBinding) {
  7890. const [left, right] = getDirectReturnFunction([], {
  7891. functionReturn: true,
  7892. lineBreakIndent: null,
  7893. name: null
  7894. });
  7895. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  7896. `${t}${t}enumerable:${_}true,${n}` +
  7897. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  7898. }
  7899. return `exports[k]${_}=${_}${name}[k]`;
  7900. };
  7901. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
  7902. const { _, cnst, n } = snippets;
  7903. const neededInteropHelpers = new Set();
  7904. const interopStatements = [];
  7905. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  7906. neededInteropHelpers.add(helper);
  7907. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  7908. };
  7909. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7910. if (isChunk) {
  7911. for (const { imported, reexported } of [
  7912. ...(imports || []),
  7913. ...(reexports || [])
  7914. ]) {
  7915. if (imported === '*' && reexported !== '*') {
  7916. if (!namedExportsMode) {
  7917. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  7918. }
  7919. break;
  7920. }
  7921. }
  7922. }
  7923. else {
  7924. const moduleInterop = interop(importPath);
  7925. let hasDefault = false;
  7926. let hasNamespace = false;
  7927. for (const { imported, reexported } of [
  7928. ...(imports || []),
  7929. ...(reexports || [])
  7930. ]) {
  7931. let helper;
  7932. let variableName;
  7933. if (imported === 'default') {
  7934. if (!hasDefault) {
  7935. hasDefault = true;
  7936. if (defaultVariableName !== namespaceVariableName) {
  7937. variableName = defaultVariableName;
  7938. helper = defaultInteropHelpersByInteropType[moduleInterop];
  7939. }
  7940. }
  7941. }
  7942. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  7943. hasNamespace = true;
  7944. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  7945. variableName = namespaceVariableName;
  7946. }
  7947. if (helper) {
  7948. addInteropStatement(variableName, helper, name);
  7949. }
  7950. }
  7951. }
  7952. }
  7953. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, symbols)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  7954. }
  7955. function addJsExtension(name) {
  7956. return name.endsWith('.js') ? name : name + '.js';
  7957. }
  7958. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  7959. // The assumption is that this makes sense for all relative ids:
  7960. // https://requirejs.org/docs/api.html#jsfiles
  7961. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  7962. if (id[0] !== '.') {
  7963. return id;
  7964. }
  7965. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  7966. }
  7967. const builtinModules = [
  7968. "node:assert",
  7969. "assert",
  7970. "node:assert/strict",
  7971. "assert/strict",
  7972. "node:async_hooks",
  7973. "async_hooks",
  7974. "node:buffer",
  7975. "buffer",
  7976. "node:child_process",
  7977. "child_process",
  7978. "node:cluster",
  7979. "cluster",
  7980. "node:console",
  7981. "console",
  7982. "node:constants",
  7983. "constants",
  7984. "node:crypto",
  7985. "crypto",
  7986. "node:dgram",
  7987. "dgram",
  7988. "node:diagnostics_channel",
  7989. "diagnostics_channel",
  7990. "node:dns",
  7991. "dns",
  7992. "node:dns/promises",
  7993. "dns/promises",
  7994. "node:domain",
  7995. "domain",
  7996. "node:events",
  7997. "events",
  7998. "node:fs",
  7999. "fs",
  8000. "node:fs/promises",
  8001. "fs/promises",
  8002. "node:http",
  8003. "http",
  8004. "node:http2",
  8005. "http2",
  8006. "node:https",
  8007. "https",
  8008. "node:inspector",
  8009. "inspector",
  8010. "node:inspector/promises",
  8011. "inspector/promises",
  8012. "node:module",
  8013. "module",
  8014. "node:net",
  8015. "net",
  8016. "node:os",
  8017. "os",
  8018. "node:path",
  8019. "path",
  8020. "node:path/posix",
  8021. "path/posix",
  8022. "node:path/win32",
  8023. "path/win32",
  8024. "node:perf_hooks",
  8025. "perf_hooks",
  8026. "node:process",
  8027. "process",
  8028. "node:querystring",
  8029. "querystring",
  8030. "node:quic",
  8031. "node:readline",
  8032. "readline",
  8033. "node:readline/promises",
  8034. "readline/promises",
  8035. "node:repl",
  8036. "repl",
  8037. "node:sea",
  8038. "node:sqlite",
  8039. "node:stream",
  8040. "stream",
  8041. "node:stream/consumers",
  8042. "stream/consumers",
  8043. "node:stream/promises",
  8044. "stream/promises",
  8045. "node:stream/web",
  8046. "stream/web",
  8047. "node:string_decoder",
  8048. "string_decoder",
  8049. "node:test",
  8050. "node:test/reporters",
  8051. "node:timers",
  8052. "timers",
  8053. "node:timers/promises",
  8054. "timers/promises",
  8055. "node:tls",
  8056. "tls",
  8057. "node:trace_events",
  8058. "trace_events",
  8059. "node:tty",
  8060. "tty",
  8061. "node:url",
  8062. "url",
  8063. "node:util",
  8064. "util",
  8065. "node:util/types",
  8066. "util/types",
  8067. "node:v8",
  8068. "v8",
  8069. "node:vm",
  8070. "vm",
  8071. "node:wasi",
  8072. "wasi",
  8073. "node:worker_threads",
  8074. "worker_threads",
  8075. "node:zlib",
  8076. "zlib"
  8077. ];
  8078. const nodeBuiltins = new Set(builtinModules);
  8079. function warnOnBuiltins(log, dependencies) {
  8080. const externalBuiltins = dependencies
  8081. .map(({ importPath }) => importPath)
  8082. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  8083. if (externalBuiltins.length === 0)
  8084. return;
  8085. log(LOGLEVEL_WARN, logMissingNodeBuiltins(externalBuiltins));
  8086. }
  8087. function amd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, log, outro, snippets }, { amd, esModule, externalLiveBindings, freeze, generatedCode: { symbols }, interop, reexportProtoFromExternal, strict }) {
  8088. warnOnBuiltins(log, dependencies);
  8089. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  8090. const parameters = dependencies.map(m => m.name);
  8091. const { n, getNonArrowFunctionIntro, _ } = snippets;
  8092. if (hasExports && (namedExportsMode || exports[0]?.local === 'exports.default')) {
  8093. parameters.unshift(`exports`);
  8094. deps.unshift(`'exports'`);
  8095. }
  8096. if (accessedGlobals.has('require')) {
  8097. parameters.unshift('require');
  8098. deps.unshift(`'require'`);
  8099. }
  8100. if (accessedGlobals.has('module')) {
  8101. parameters.unshift('module');
  8102. deps.unshift(`'module'`);
  8103. }
  8104. const completeAmdId = getCompleteAmdId(amd, id);
  8105. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  8106. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  8107. const useStrict = strict ? `${_}'use strict';` : '';
  8108. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  8109. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8110. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  8111. if (namespaceMarkers) {
  8112. namespaceMarkers = n + n + namespaceMarkers;
  8113. }
  8114. magicString
  8115. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8116. .indent(t)
  8117. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8118. // cf. https://v8.dev/blog/preparser#pife
  8119. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  8120. isAsync: false,
  8121. name: null
  8122. })}{${useStrict}${n}${n}`)
  8123. .append(`${n}${n}}));`);
  8124. }
  8125. function cjs(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, generatedCode: { symbols }, reexportProtoFromExternal, strict }) {
  8126. const { _, n } = snippets;
  8127. const useStrict = strict ? `'use strict';${n}${n}` : '';
  8128. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  8129. if (namespaceMarkers) {
  8130. namespaceMarkers += n + n;
  8131. }
  8132. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  8133. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  8134. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  8135. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, `module.exports${_}=${_}`);
  8136. magicString.append(`${exportBlock}${outro}`);
  8137. }
  8138. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  8139. let importBlock = '';
  8140. let definingVariable = false;
  8141. for (const { importPath, name, reexports, imports } of dependencies) {
  8142. if (!reexports && !imports) {
  8143. if (importBlock) {
  8144. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  8145. }
  8146. definingVariable = false;
  8147. importBlock += `require('${importPath}')`;
  8148. }
  8149. else {
  8150. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  8151. definingVariable = true;
  8152. importBlock += `${name}${_}=${_}require('${importPath}')`;
  8153. }
  8154. }
  8155. if (importBlock) {
  8156. return `${importBlock};${n}${n}`;
  8157. }
  8158. return '';
  8159. }
  8160. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, generatedCode: { symbols }, importAttributesKey }) {
  8161. const { n } = snippets;
  8162. const importBlock = getImportBlock(dependencies, importAttributesKey, snippets);
  8163. if (importBlock.length > 0)
  8164. intro += importBlock.join(n) + n + n;
  8165. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols);
  8166. if (intro)
  8167. magicString.prepend(intro);
  8168. const exportBlock = getExportBlock(exports, snippets);
  8169. if (exportBlock.length > 0)
  8170. magicString.append(n + n + exportBlock.join(n).trim());
  8171. if (outro)
  8172. magicString.append(outro);
  8173. magicString.trim();
  8174. }
  8175. function getImportBlock(dependencies, importAttributesKey, { _ }) {
  8176. const importBlock = [];
  8177. for (const { importPath, reexports, imports, name, attributes } of dependencies) {
  8178. const assertion = attributes ? `${_}${importAttributesKey}${_}${attributes}` : '';
  8179. const pathWithAssertion = `'${importPath}'${assertion};`;
  8180. if (!reexports && !imports) {
  8181. importBlock.push(`import${_}${pathWithAssertion}`);
  8182. continue;
  8183. }
  8184. if (imports) {
  8185. let defaultImport = null;
  8186. let starImport = null;
  8187. const importedNames = [];
  8188. for (const specifier of imports) {
  8189. if (specifier.imported === 'default') {
  8190. defaultImport = specifier;
  8191. }
  8192. else if (specifier.imported === '*') {
  8193. starImport = specifier;
  8194. }
  8195. else {
  8196. importedNames.push(specifier);
  8197. }
  8198. }
  8199. if (starImport) {
  8200. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  8201. }
  8202. if (defaultImport && importedNames.length === 0) {
  8203. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  8204. }
  8205. else if (importedNames.length > 0) {
  8206. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  8207. .map(specifier => specifier.imported === specifier.local
  8208. ? specifier.imported
  8209. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${specifier.local}`)
  8210. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  8211. }
  8212. }
  8213. if (reexports) {
  8214. let starExport = null;
  8215. const namespaceReexports = [];
  8216. const namedReexports = [];
  8217. for (const specifier of reexports) {
  8218. if (specifier.reexported === '*') {
  8219. starExport = specifier;
  8220. }
  8221. else if (specifier.imported === '*') {
  8222. namespaceReexports.push(specifier);
  8223. }
  8224. else {
  8225. namedReexports.push(specifier);
  8226. }
  8227. }
  8228. if (starExport) {
  8229. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  8230. }
  8231. if (namespaceReexports.length > 0) {
  8232. if (!imports ||
  8233. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  8234. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  8235. }
  8236. for (const specifier of namespaceReexports) {
  8237. importBlock.push(`export${_}{${_}${name === specifier.reexported
  8238. ? name
  8239. : `${name} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`} };`);
  8240. }
  8241. }
  8242. if (namedReexports.length > 0) {
  8243. importBlock.push(`export${_}{${_}${namedReexports
  8244. .map(specifier => specifier.imported === specifier.reexported
  8245. ? stringifyIdentifierIfNeeded(specifier.imported)
  8246. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`)
  8247. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  8248. }
  8249. }
  8250. }
  8251. return importBlock;
  8252. }
  8253. function getExportBlock(exports, { _, cnst }) {
  8254. const exportBlock = [];
  8255. const exportDeclaration = new Array(exports.length);
  8256. let index = 0;
  8257. for (const specifier of exports) {
  8258. if (specifier.expression) {
  8259. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  8260. }
  8261. exportDeclaration[index++] =
  8262. specifier.exported === specifier.local
  8263. ? specifier.local
  8264. : `${specifier.local} as ${stringifyIdentifierIfNeeded(specifier.exported)}`;
  8265. }
  8266. if (exportDeclaration.length > 0) {
  8267. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  8268. }
  8269. return exportBlock;
  8270. }
  8271. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  8272. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact, log) {
  8273. const parts = name.split('.');
  8274. // Check if the key exists in the object's prototype.
  8275. const isReserved = parts[0] in Object.prototype;
  8276. if (log && isReserved) {
  8277. log(LOGLEVEL_WARN, logReservedNamespace(parts[0]));
  8278. }
  8279. parts[0] =
  8280. (typeof globals === 'function'
  8281. ? globals(parts[0])
  8282. : isReserved
  8283. ? parts[0]
  8284. : globals[parts[0]]) || parts[0];
  8285. parts.pop();
  8286. let propertyPath = root;
  8287. return (parts
  8288. .map(part => {
  8289. propertyPath += getPropertyAccess(part);
  8290. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  8291. })
  8292. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  8293. }
  8294. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }, log) {
  8295. const parts = deepName.split('.');
  8296. // Check if the key exists in the object's prototype.
  8297. const isReserved = parts[0] in Object.prototype;
  8298. if (log && isReserved) {
  8299. log(LOGLEVEL_WARN, logReservedNamespace(parts[0]));
  8300. }
  8301. parts[0] =
  8302. (typeof globals === 'function'
  8303. ? globals(parts[0])
  8304. : isReserved
  8305. ? parts[0]
  8306. : globals[parts[0]]) || parts[0];
  8307. const last = parts.pop();
  8308. let propertyPath = root;
  8309. let deepAssignment = [
  8310. ...parts.map(part => {
  8311. propertyPath += getPropertyAccess(part);
  8312. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  8313. }),
  8314. `${propertyPath}${getPropertyAccess(last)}`
  8315. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  8316. if (parts.length > 0) {
  8317. deepAssignment = `(${deepAssignment})`;
  8318. }
  8319. return deepAssignment;
  8320. }
  8321. function trimEmptyImports(dependencies) {
  8322. let index = dependencies.length;
  8323. while (index--) {
  8324. const { imports, reexports } = dependencies[index];
  8325. if (imports || reexports) {
  8326. return dependencies.slice(0, index + 1);
  8327. }
  8328. }
  8329. return [];
  8330. }
  8331. function iife(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, namedExportsMode, log, outro, snippets }, { compact, esModule, extend, freeze, externalLiveBindings, reexportProtoFromExternal, globals, interop, name, generatedCode: { symbols }, strict }) {
  8332. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  8333. const isNamespaced = name && name.includes('.');
  8334. const useVariableAssignment = !extend && !isNamespaced;
  8335. if (name && useVariableAssignment && !isLegal(name)) {
  8336. return error(logIllegalIdentifierAsName(name));
  8337. }
  8338. warnOnBuiltins(log, dependencies);
  8339. const external = trimEmptyImports(dependencies);
  8340. const deps = external.map(dep => dep.globalName || 'null');
  8341. const parameters = external.map(m => m.name);
  8342. if (hasExports && !name) {
  8343. log(LOGLEVEL_WARN, logMissingNameOptionForIifeExport());
  8344. }
  8345. if (hasExports && (namedExportsMode || exports[0]?.local === 'exports.default')) {
  8346. if (extend) {
  8347. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  8348. parameters.unshift('exports');
  8349. }
  8350. else {
  8351. deps.unshift('{}');
  8352. parameters.unshift('exports');
  8353. }
  8354. }
  8355. const useStrict = strict ? `${t}'use strict';${n}` : '';
  8356. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  8357. magicString.prepend(`${intro}${interopBlock}`);
  8358. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  8359. isAsync: false,
  8360. name: null
  8361. })}{${n}${useStrict}${n}`;
  8362. if (hasExports) {
  8363. if (name && !(extend && namedExportsMode)) {
  8364. wrapperIntro =
  8365. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  8366. `${_}=${_}${wrapperIntro}`;
  8367. }
  8368. if (isNamespaced) {
  8369. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact, log) + wrapperIntro;
  8370. }
  8371. }
  8372. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  8373. if (hasExports && !extend && namedExportsMode) {
  8374. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  8375. }
  8376. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8377. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  8378. if (namespaceMarkers) {
  8379. namespaceMarkers = n + n + namespaceMarkers;
  8380. }
  8381. magicString
  8382. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8383. .indent(t)
  8384. .prepend(wrapperIntro)
  8385. .append(wrapperOutro);
  8386. }
  8387. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  8388. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, generatedCode: { symbols }, strict, systemNullSetters }) {
  8389. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  8390. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  8391. const registeredName = name ? `'${name}',${_}` : '';
  8392. const wrapperParameters = accessedGlobals.has('module')
  8393. ? ['exports', 'module']
  8394. : hasExports
  8395. ? ['exports']
  8396. : [];
  8397. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8398. // cf. https://v8.dev/blog/preparser#pife
  8399. let wrapperStart = `System.register(${registeredName}[` +
  8400. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  8401. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  8402. isAsync: false,
  8403. name: null
  8404. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  8405. getStarExcludesBlock(starExcludes, t, snippets) +
  8406. getImportBindingsBlock(importBindings, t, snippets) +
  8407. `${n}${t}return${_}{${setters.length > 0
  8408. ? `${n}${t}${t}setters:${_}[${setters
  8409. .map(setter => setter
  8410. ? `${getFunctionIntro(['module'], {
  8411. isAsync: false,
  8412. name: null
  8413. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  8414. : systemNullSetters
  8415. ? `null`
  8416. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  8417. .join(`,${_}`)}],`
  8418. : ''}${n}`;
  8419. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  8420. isAsync: usesTopLevelAwait,
  8421. name: null
  8422. })}{${n}${n}`;
  8423. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  8424. magicString
  8425. .prepend(intro +
  8426. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols) +
  8427. getHoistedExportsBlock(exports, t, snippets))
  8428. .append(`${outro}${n}${n}` +
  8429. getSyntheticExportsBlock(exports, t, snippets) +
  8430. getMissingExportsBlock(exports, t, snippets))
  8431. .indent(`${t}${t}${t}`)
  8432. .append(wrapperEnd)
  8433. .prepend(wrapperStart);
  8434. }
  8435. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  8436. const importBindings = [];
  8437. const setters = [];
  8438. let starExcludes = null;
  8439. for (const { imports, reexports } of dependencies) {
  8440. const setter = [];
  8441. if (imports) {
  8442. for (const specifier of imports) {
  8443. importBindings.push(specifier.local);
  8444. if (specifier.imported === '*') {
  8445. setter.push(`${specifier.local}${_}=${_}module;`);
  8446. }
  8447. else {
  8448. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  8449. }
  8450. }
  8451. }
  8452. if (reexports) {
  8453. const reexportedNames = [];
  8454. let hasStarReexport = false;
  8455. for (const { imported, reexported } of reexports) {
  8456. if (reexported === '*') {
  8457. hasStarReexport = true;
  8458. }
  8459. else {
  8460. reexportedNames.push([
  8461. reexported,
  8462. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  8463. ]);
  8464. }
  8465. }
  8466. if (reexportedNames.length > 1 || hasStarReexport) {
  8467. if (hasStarReexport) {
  8468. if (!starExcludes) {
  8469. starExcludes = getStarExcludes({ dependencies, exports });
  8470. }
  8471. reexportedNames.unshift([null, `__proto__:${_}null`]);
  8472. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  8473. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  8474. }
  8475. else {
  8476. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  8477. setter.push(`exports(${exportMapping});`);
  8478. }
  8479. }
  8480. else {
  8481. const [key, value] = reexportedNames[0];
  8482. setter.push(`exports(${JSON.stringify(key)},${_}${value});`);
  8483. }
  8484. }
  8485. setters.push(setter.join(`${n}${t}${t}${t}`));
  8486. }
  8487. return { importBindings, setters, starExcludes };
  8488. }
  8489. const getStarExcludes = ({ dependencies, exports }) => {
  8490. const starExcludes = new Set(exports.map(expt => expt.exported));
  8491. starExcludes.add('default');
  8492. for (const { reexports } of dependencies) {
  8493. if (reexports) {
  8494. for (const reexport of reexports) {
  8495. if (reexport.reexported !== '*')
  8496. starExcludes.add(reexport.reexported);
  8497. }
  8498. }
  8499. }
  8500. return starExcludes;
  8501. };
  8502. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => {
  8503. if (starExcludes) {
  8504. const fields = [...starExcludes].map(property => [
  8505. property,
  8506. '1'
  8507. ]);
  8508. fields.unshift([null, `__proto__:${_}null`]);
  8509. return `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(fields, {
  8510. lineBreakIndent: { base: t, t }
  8511. })};`;
  8512. }
  8513. return '';
  8514. };
  8515. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  8516. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  8517. function getExportsBlock(exports, t, { _, n }) {
  8518. if (exports.length === 0) {
  8519. return '';
  8520. }
  8521. if (exports.length === 1) {
  8522. return `exports(${JSON.stringify(exports[0].name)},${_}${exports[0].value});${n}${n}`;
  8523. }
  8524. return (`exports({${n}` +
  8525. exports
  8526. .map(({ name, value }) => `${t}${stringifyObjectKeyIfNeeded(name)}:${_}${value}`)
  8527. .join(`,${n}`) +
  8528. `${n}});${n}${n}`);
  8529. }
  8530. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  8531. .filter(expt => expt.expression)
  8532. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  8533. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  8534. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  8535. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  8536. function globalProperty(name, globalVariable, getPropertyAccess) {
  8537. if (!name)
  8538. return 'null';
  8539. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  8540. }
  8541. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  8542. let propertyPath = globalVariable;
  8543. return name
  8544. .split('.')
  8545. .map(part => (propertyPath += getPropertyAccess(part)))
  8546. .join(`${_}&&${_}`);
  8547. }
  8548. function umd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, log, outro, snippets }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, generatedCode: { symbols }, globals, noConflict, reexportProtoFromExternal, strict }) {
  8549. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  8550. const factoryVariable = compact ? 'f' : 'factory';
  8551. const globalVariable = compact ? 'g' : 'global';
  8552. if (hasExports && !name) {
  8553. return error(logMissingNameOptionForUmdExport());
  8554. }
  8555. warnOnBuiltins(log, dependencies);
  8556. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  8557. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  8558. const trimmedImports = trimEmptyImports(dependencies);
  8559. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  8560. const factoryParameters = trimmedImports.map(m => m.name);
  8561. if ((hasExports || noConflict) &&
  8562. (namedExportsMode || (hasExports && exports[0]?.local === 'exports.default'))) {
  8563. amdDeps.unshift(`'exports'`);
  8564. cjsDeps.unshift(`exports`);
  8565. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets, log));
  8566. factoryParameters.unshift('exports');
  8567. }
  8568. const completeAmdId = getCompleteAmdId(amd, id);
  8569. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  8570. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  8571. const define = amd.define;
  8572. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  8573. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  8574. let iifeExport;
  8575. if (noConflict) {
  8576. const noConflictExportsVariable = compact ? 'e' : 'exports';
  8577. let factory;
  8578. if (!namedExportsMode && hasExports) {
  8579. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets, log)};`;
  8580. }
  8581. else {
  8582. const module = globalDeps.shift();
  8583. factory =
  8584. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  8585. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  8586. }
  8587. iifeExport =
  8588. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  8589. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  8590. `${t}${t}${factory}${n}` +
  8591. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  8592. isAsync: false,
  8593. name: null
  8594. })}{${_}` +
  8595. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  8596. `${t}})()`;
  8597. }
  8598. else {
  8599. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  8600. if (!namedExportsMode && hasExports) {
  8601. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets, log);
  8602. }
  8603. }
  8604. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  8605. const wrapperParameters = [factoryVariable];
  8606. if (iifeNeedsGlobal) {
  8607. wrapperParameters.unshift(globalVariable);
  8608. }
  8609. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  8610. const iifeStart = iifeNeedsGlobal
  8611. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  8612. : '';
  8613. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  8614. const cjsIntro = iifeNeedsGlobal
  8615. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  8616. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  8617. : '';
  8618. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  8619. cjsIntro +
  8620. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  8621. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  8622. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8623. // cf. https://v8.dev/blog/preparser#pife
  8624. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  8625. isAsync: false,
  8626. name: null
  8627. })}{${useStrict}${n}`;
  8628. const wrapperOutro = n + n + '}));';
  8629. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  8630. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8631. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  8632. if (namespaceMarkers) {
  8633. namespaceMarkers = n + n + namespaceMarkers;
  8634. }
  8635. magicString
  8636. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8637. .trim()
  8638. .indent(t)
  8639. .append(wrapperOutro)
  8640. .prepend(wrapperIntro);
  8641. }
  8642. const finalisers = { amd, cjs, es, iife, system, umd };
  8643. function getDefaultExportFromCjs (x) {
  8644. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  8645. }
  8646. function getAugmentedNamespace(n) {
  8647. if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  8648. var f = n.default;
  8649. if (typeof f == "function") {
  8650. var a = function a () {
  8651. var isInstance = false;
  8652. try {
  8653. isInstance = this instanceof a;
  8654. } catch {}
  8655. if (isInstance) {
  8656. return Reflect.construct(f, arguments, this.constructor);
  8657. }
  8658. return f.apply(this, arguments);
  8659. };
  8660. a.prototype = f.prototype;
  8661. } else a = {};
  8662. Object.defineProperty(a, '__esModule', {value: true});
  8663. Object.keys(n).forEach(function (k) {
  8664. var d = Object.getOwnPropertyDescriptor(n, k);
  8665. Object.defineProperty(a, k, d.get ? d : {
  8666. enumerable: true,
  8667. get: function () {
  8668. return n[k];
  8669. }
  8670. });
  8671. });
  8672. return a;
  8673. }
  8674. var utils = {};
  8675. var constants;
  8676. var hasRequiredConstants;
  8677. function requireConstants () {
  8678. if (hasRequiredConstants) return constants;
  8679. hasRequiredConstants = 1;
  8680. const WIN_SLASH = '\\\\/';
  8681. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  8682. /**
  8683. * Posix glob regex
  8684. */
  8685. const DOT_LITERAL = '\\.';
  8686. const PLUS_LITERAL = '\\+';
  8687. const QMARK_LITERAL = '\\?';
  8688. const SLASH_LITERAL = '\\/';
  8689. const ONE_CHAR = '(?=.)';
  8690. const QMARK = '[^/]';
  8691. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  8692. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  8693. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  8694. const NO_DOT = `(?!${DOT_LITERAL})`;
  8695. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  8696. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  8697. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  8698. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  8699. const STAR = `${QMARK}*?`;
  8700. const SEP = '/';
  8701. const POSIX_CHARS = {
  8702. DOT_LITERAL,
  8703. PLUS_LITERAL,
  8704. QMARK_LITERAL,
  8705. SLASH_LITERAL,
  8706. ONE_CHAR,
  8707. QMARK,
  8708. END_ANCHOR,
  8709. DOTS_SLASH,
  8710. NO_DOT,
  8711. NO_DOTS,
  8712. NO_DOT_SLASH,
  8713. NO_DOTS_SLASH,
  8714. QMARK_NO_DOT,
  8715. STAR,
  8716. START_ANCHOR,
  8717. SEP
  8718. };
  8719. /**
  8720. * Windows glob regex
  8721. */
  8722. const WINDOWS_CHARS = {
  8723. ...POSIX_CHARS,
  8724. SLASH_LITERAL: `[${WIN_SLASH}]`,
  8725. QMARK: WIN_NO_SLASH,
  8726. STAR: `${WIN_NO_SLASH}*?`,
  8727. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  8728. NO_DOT: `(?!${DOT_LITERAL})`,
  8729. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  8730. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  8731. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  8732. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  8733. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  8734. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
  8735. SEP: '\\'
  8736. };
  8737. /**
  8738. * POSIX Bracket Regex
  8739. */
  8740. const POSIX_REGEX_SOURCE = {
  8741. alnum: 'a-zA-Z0-9',
  8742. alpha: 'a-zA-Z',
  8743. ascii: '\\x00-\\x7F',
  8744. blank: ' \\t',
  8745. cntrl: '\\x00-\\x1F\\x7F',
  8746. digit: '0-9',
  8747. graph: '\\x21-\\x7E',
  8748. lower: 'a-z',
  8749. print: '\\x20-\\x7E ',
  8750. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  8751. space: ' \\t\\r\\n\\v\\f',
  8752. upper: 'A-Z',
  8753. word: 'A-Za-z0-9_',
  8754. xdigit: 'A-Fa-f0-9'
  8755. };
  8756. constants = {
  8757. MAX_LENGTH: 1024 * 64,
  8758. POSIX_REGEX_SOURCE,
  8759. // regular expressions
  8760. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  8761. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  8762. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  8763. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  8764. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  8765. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  8766. // Replace globs with equivalent patterns to reduce parsing time.
  8767. REPLACEMENTS: {
  8768. __proto__: null,
  8769. '***': '*',
  8770. '**/**': '**',
  8771. '**/**/**': '**'
  8772. },
  8773. // Digits
  8774. CHAR_0: 48, /* 0 */
  8775. CHAR_9: 57, /* 9 */
  8776. // Alphabet chars.
  8777. CHAR_UPPERCASE_A: 65, /* A */
  8778. CHAR_LOWERCASE_A: 97, /* a */
  8779. CHAR_UPPERCASE_Z: 90, /* Z */
  8780. CHAR_LOWERCASE_Z: 122, /* z */
  8781. CHAR_LEFT_PARENTHESES: 40, /* ( */
  8782. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  8783. CHAR_ASTERISK: 42, /* * */
  8784. // Non-alphabetic chars.
  8785. CHAR_AMPERSAND: 38, /* & */
  8786. CHAR_AT: 64, /* @ */
  8787. CHAR_BACKWARD_SLASH: 92, /* \ */
  8788. CHAR_CARRIAGE_RETURN: 13, /* \r */
  8789. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  8790. CHAR_COLON: 58, /* : */
  8791. CHAR_COMMA: 44, /* , */
  8792. CHAR_DOT: 46, /* . */
  8793. CHAR_DOUBLE_QUOTE: 34, /* " */
  8794. CHAR_EQUAL: 61, /* = */
  8795. CHAR_EXCLAMATION_MARK: 33, /* ! */
  8796. CHAR_FORM_FEED: 12, /* \f */
  8797. CHAR_FORWARD_SLASH: 47, /* / */
  8798. CHAR_GRAVE_ACCENT: 96, /* ` */
  8799. CHAR_HASH: 35, /* # */
  8800. CHAR_HYPHEN_MINUS: 45, /* - */
  8801. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  8802. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  8803. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  8804. CHAR_LINE_FEED: 10, /* \n */
  8805. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  8806. CHAR_PERCENT: 37, /* % */
  8807. CHAR_PLUS: 43, /* + */
  8808. CHAR_QUESTION_MARK: 63, /* ? */
  8809. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  8810. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  8811. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  8812. CHAR_SEMICOLON: 59, /* ; */
  8813. CHAR_SINGLE_QUOTE: 39, /* ' */
  8814. CHAR_SPACE: 32, /* */
  8815. CHAR_TAB: 9, /* \t */
  8816. CHAR_UNDERSCORE: 95, /* _ */
  8817. CHAR_VERTICAL_LINE: 124, /* | */
  8818. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  8819. /**
  8820. * Create EXTGLOB_CHARS
  8821. */
  8822. extglobChars(chars) {
  8823. return {
  8824. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  8825. '?': { type: 'qmark', open: '(?:', close: ')?' },
  8826. '+': { type: 'plus', open: '(?:', close: ')+' },
  8827. '*': { type: 'star', open: '(?:', close: ')*' },
  8828. '@': { type: 'at', open: '(?:', close: ')' }
  8829. };
  8830. },
  8831. /**
  8832. * Create GLOB_CHARS
  8833. */
  8834. globChars(win32) {
  8835. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  8836. }
  8837. };
  8838. return constants;
  8839. }
  8840. /*global navigator*/
  8841. var hasRequiredUtils;
  8842. function requireUtils () {
  8843. if (hasRequiredUtils) return utils;
  8844. hasRequiredUtils = 1;
  8845. (function (exports) {
  8846. const {
  8847. REGEX_BACKSLASH,
  8848. REGEX_REMOVE_BACKSLASH,
  8849. REGEX_SPECIAL_CHARS,
  8850. REGEX_SPECIAL_CHARS_GLOBAL
  8851. } = /*@__PURE__*/ requireConstants();
  8852. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  8853. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  8854. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  8855. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  8856. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  8857. exports.isWindows = () => {
  8858. if (typeof navigator !== 'undefined' && navigator.platform) {
  8859. const platform = navigator.platform.toLowerCase();
  8860. return platform === 'win32' || platform === 'windows';
  8861. }
  8862. if (typeof process !== 'undefined' && process.platform) {
  8863. return process.platform === 'win32';
  8864. }
  8865. return false;
  8866. };
  8867. exports.removeBackslashes = str => {
  8868. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  8869. return match === '\\' ? '' : match;
  8870. });
  8871. };
  8872. exports.escapeLast = (input, char, lastIdx) => {
  8873. const idx = input.lastIndexOf(char, lastIdx);
  8874. if (idx === -1) return input;
  8875. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  8876. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  8877. };
  8878. exports.removePrefix = (input, state = {}) => {
  8879. let output = input;
  8880. if (output.startsWith('./')) {
  8881. output = output.slice(2);
  8882. state.prefix = './';
  8883. }
  8884. return output;
  8885. };
  8886. exports.wrapOutput = (input, state = {}, options = {}) => {
  8887. const prepend = options.contains ? '' : '^';
  8888. const append = options.contains ? '' : '$';
  8889. let output = `${prepend}(?:${input})${append}`;
  8890. if (state.negated === true) {
  8891. output = `(?:^(?!${output}).*$)`;
  8892. }
  8893. return output;
  8894. };
  8895. exports.basename = (path, { windows } = {}) => {
  8896. const segs = path.split(windows ? /[\\/]/ : '/');
  8897. const last = segs[segs.length - 1];
  8898. if (last === '') {
  8899. return segs[segs.length - 2];
  8900. }
  8901. return last;
  8902. };
  8903. } (utils));
  8904. return utils;
  8905. }
  8906. var scan_1;
  8907. var hasRequiredScan;
  8908. function requireScan () {
  8909. if (hasRequiredScan) return scan_1;
  8910. hasRequiredScan = 1;
  8911. const utils = /*@__PURE__*/ requireUtils();
  8912. const {
  8913. CHAR_ASTERISK, /* * */
  8914. CHAR_AT, /* @ */
  8915. CHAR_BACKWARD_SLASH, /* \ */
  8916. CHAR_COMMA, /* , */
  8917. CHAR_DOT, /* . */
  8918. CHAR_EXCLAMATION_MARK, /* ! */
  8919. CHAR_FORWARD_SLASH, /* / */
  8920. CHAR_LEFT_CURLY_BRACE, /* { */
  8921. CHAR_LEFT_PARENTHESES, /* ( */
  8922. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  8923. CHAR_PLUS, /* + */
  8924. CHAR_QUESTION_MARK, /* ? */
  8925. CHAR_RIGHT_CURLY_BRACE, /* } */
  8926. CHAR_RIGHT_PARENTHESES, /* ) */
  8927. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  8928. } = /*@__PURE__*/ requireConstants();
  8929. const isPathSeparator = code => {
  8930. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  8931. };
  8932. const depth = token => {
  8933. if (token.isPrefix !== true) {
  8934. token.depth = token.isGlobstar ? Infinity : 1;
  8935. }
  8936. };
  8937. /**
  8938. * Quickly scans a glob pattern and returns an object with a handful of
  8939. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  8940. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  8941. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  8942. *
  8943. * ```js
  8944. * const pm = require('picomatch');
  8945. * console.log(pm.scan('foo/bar/*.js'));
  8946. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  8947. * ```
  8948. * @param {String} `str`
  8949. * @param {Object} `options`
  8950. * @return {Object} Returns an object with tokens and regex source string.
  8951. * @api public
  8952. */
  8953. const scan = (input, options) => {
  8954. const opts = options || {};
  8955. const length = input.length - 1;
  8956. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  8957. const slashes = [];
  8958. const tokens = [];
  8959. const parts = [];
  8960. let str = input;
  8961. let index = -1;
  8962. let start = 0;
  8963. let lastIndex = 0;
  8964. let isBrace = false;
  8965. let isBracket = false;
  8966. let isGlob = false;
  8967. let isExtglob = false;
  8968. let isGlobstar = false;
  8969. let braceEscaped = false;
  8970. let backslashes = false;
  8971. let negated = false;
  8972. let negatedExtglob = false;
  8973. let finished = false;
  8974. let braces = 0;
  8975. let prev;
  8976. let code;
  8977. let token = { value: '', depth: 0, isGlob: false };
  8978. const eos = () => index >= length;
  8979. const peek = () => str.charCodeAt(index + 1);
  8980. const advance = () => {
  8981. prev = code;
  8982. return str.charCodeAt(++index);
  8983. };
  8984. while (index < length) {
  8985. code = advance();
  8986. let next;
  8987. if (code === CHAR_BACKWARD_SLASH) {
  8988. backslashes = token.backslashes = true;
  8989. code = advance();
  8990. if (code === CHAR_LEFT_CURLY_BRACE) {
  8991. braceEscaped = true;
  8992. }
  8993. continue;
  8994. }
  8995. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  8996. braces++;
  8997. while (eos() !== true && (code = advance())) {
  8998. if (code === CHAR_BACKWARD_SLASH) {
  8999. backslashes = token.backslashes = true;
  9000. advance();
  9001. continue;
  9002. }
  9003. if (code === CHAR_LEFT_CURLY_BRACE) {
  9004. braces++;
  9005. continue;
  9006. }
  9007. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  9008. isBrace = token.isBrace = true;
  9009. isGlob = token.isGlob = true;
  9010. finished = true;
  9011. if (scanToEnd === true) {
  9012. continue;
  9013. }
  9014. break;
  9015. }
  9016. if (braceEscaped !== true && code === CHAR_COMMA) {
  9017. isBrace = token.isBrace = true;
  9018. isGlob = token.isGlob = true;
  9019. finished = true;
  9020. if (scanToEnd === true) {
  9021. continue;
  9022. }
  9023. break;
  9024. }
  9025. if (code === CHAR_RIGHT_CURLY_BRACE) {
  9026. braces--;
  9027. if (braces === 0) {
  9028. braceEscaped = false;
  9029. isBrace = token.isBrace = true;
  9030. finished = true;
  9031. break;
  9032. }
  9033. }
  9034. }
  9035. if (scanToEnd === true) {
  9036. continue;
  9037. }
  9038. break;
  9039. }
  9040. if (code === CHAR_FORWARD_SLASH) {
  9041. slashes.push(index);
  9042. tokens.push(token);
  9043. token = { value: '', depth: 0, isGlob: false };
  9044. if (finished === true) continue;
  9045. if (prev === CHAR_DOT && index === (start + 1)) {
  9046. start += 2;
  9047. continue;
  9048. }
  9049. lastIndex = index + 1;
  9050. continue;
  9051. }
  9052. if (opts.noext !== true) {
  9053. const isExtglobChar = code === CHAR_PLUS
  9054. || code === CHAR_AT
  9055. || code === CHAR_ASTERISK
  9056. || code === CHAR_QUESTION_MARK
  9057. || code === CHAR_EXCLAMATION_MARK;
  9058. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  9059. isGlob = token.isGlob = true;
  9060. isExtglob = token.isExtglob = true;
  9061. finished = true;
  9062. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  9063. negatedExtglob = true;
  9064. }
  9065. if (scanToEnd === true) {
  9066. while (eos() !== true && (code = advance())) {
  9067. if (code === CHAR_BACKWARD_SLASH) {
  9068. backslashes = token.backslashes = true;
  9069. code = advance();
  9070. continue;
  9071. }
  9072. if (code === CHAR_RIGHT_PARENTHESES) {
  9073. isGlob = token.isGlob = true;
  9074. finished = true;
  9075. break;
  9076. }
  9077. }
  9078. continue;
  9079. }
  9080. break;
  9081. }
  9082. }
  9083. if (code === CHAR_ASTERISK) {
  9084. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  9085. isGlob = token.isGlob = true;
  9086. finished = true;
  9087. if (scanToEnd === true) {
  9088. continue;
  9089. }
  9090. break;
  9091. }
  9092. if (code === CHAR_QUESTION_MARK) {
  9093. isGlob = token.isGlob = true;
  9094. finished = true;
  9095. if (scanToEnd === true) {
  9096. continue;
  9097. }
  9098. break;
  9099. }
  9100. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  9101. while (eos() !== true && (next = advance())) {
  9102. if (next === CHAR_BACKWARD_SLASH) {
  9103. backslashes = token.backslashes = true;
  9104. advance();
  9105. continue;
  9106. }
  9107. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  9108. isBracket = token.isBracket = true;
  9109. isGlob = token.isGlob = true;
  9110. finished = true;
  9111. break;
  9112. }
  9113. }
  9114. if (scanToEnd === true) {
  9115. continue;
  9116. }
  9117. break;
  9118. }
  9119. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  9120. negated = token.negated = true;
  9121. start++;
  9122. continue;
  9123. }
  9124. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  9125. isGlob = token.isGlob = true;
  9126. if (scanToEnd === true) {
  9127. while (eos() !== true && (code = advance())) {
  9128. if (code === CHAR_LEFT_PARENTHESES) {
  9129. backslashes = token.backslashes = true;
  9130. code = advance();
  9131. continue;
  9132. }
  9133. if (code === CHAR_RIGHT_PARENTHESES) {
  9134. finished = true;
  9135. break;
  9136. }
  9137. }
  9138. continue;
  9139. }
  9140. break;
  9141. }
  9142. if (isGlob === true) {
  9143. finished = true;
  9144. if (scanToEnd === true) {
  9145. continue;
  9146. }
  9147. break;
  9148. }
  9149. }
  9150. if (opts.noext === true) {
  9151. isExtglob = false;
  9152. isGlob = false;
  9153. }
  9154. let base = str;
  9155. let prefix = '';
  9156. let glob = '';
  9157. if (start > 0) {
  9158. prefix = str.slice(0, start);
  9159. str = str.slice(start);
  9160. lastIndex -= start;
  9161. }
  9162. if (base && isGlob === true && lastIndex > 0) {
  9163. base = str.slice(0, lastIndex);
  9164. glob = str.slice(lastIndex);
  9165. } else if (isGlob === true) {
  9166. base = '';
  9167. glob = str;
  9168. } else {
  9169. base = str;
  9170. }
  9171. if (base && base !== '' && base !== '/' && base !== str) {
  9172. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  9173. base = base.slice(0, -1);
  9174. }
  9175. }
  9176. if (opts.unescape === true) {
  9177. if (glob) glob = utils.removeBackslashes(glob);
  9178. if (base && backslashes === true) {
  9179. base = utils.removeBackslashes(base);
  9180. }
  9181. }
  9182. const state = {
  9183. prefix,
  9184. input,
  9185. start,
  9186. base,
  9187. glob,
  9188. isBrace,
  9189. isBracket,
  9190. isGlob,
  9191. isExtglob,
  9192. isGlobstar,
  9193. negated,
  9194. negatedExtglob
  9195. };
  9196. if (opts.tokens === true) {
  9197. state.maxDepth = 0;
  9198. if (!isPathSeparator(code)) {
  9199. tokens.push(token);
  9200. }
  9201. state.tokens = tokens;
  9202. }
  9203. if (opts.parts === true || opts.tokens === true) {
  9204. let prevIndex;
  9205. for (let idx = 0; idx < slashes.length; idx++) {
  9206. const n = prevIndex ? prevIndex + 1 : start;
  9207. const i = slashes[idx];
  9208. const value = input.slice(n, i);
  9209. if (opts.tokens) {
  9210. if (idx === 0 && start !== 0) {
  9211. tokens[idx].isPrefix = true;
  9212. tokens[idx].value = prefix;
  9213. } else {
  9214. tokens[idx].value = value;
  9215. }
  9216. depth(tokens[idx]);
  9217. state.maxDepth += tokens[idx].depth;
  9218. }
  9219. if (idx !== 0 || value !== '') {
  9220. parts.push(value);
  9221. }
  9222. prevIndex = i;
  9223. }
  9224. if (prevIndex && prevIndex + 1 < input.length) {
  9225. const value = input.slice(prevIndex + 1);
  9226. parts.push(value);
  9227. if (opts.tokens) {
  9228. tokens[tokens.length - 1].value = value;
  9229. depth(tokens[tokens.length - 1]);
  9230. state.maxDepth += tokens[tokens.length - 1].depth;
  9231. }
  9232. }
  9233. state.slashes = slashes;
  9234. state.parts = parts;
  9235. }
  9236. return state;
  9237. };
  9238. scan_1 = scan;
  9239. return scan_1;
  9240. }
  9241. var parse_1;
  9242. var hasRequiredParse;
  9243. function requireParse () {
  9244. if (hasRequiredParse) return parse_1;
  9245. hasRequiredParse = 1;
  9246. const constants = /*@__PURE__*/ requireConstants();
  9247. const utils = /*@__PURE__*/ requireUtils();
  9248. /**
  9249. * Constants
  9250. */
  9251. const {
  9252. MAX_LENGTH,
  9253. POSIX_REGEX_SOURCE,
  9254. REGEX_NON_SPECIAL_CHARS,
  9255. REGEX_SPECIAL_CHARS_BACKREF,
  9256. REPLACEMENTS
  9257. } = constants;
  9258. /**
  9259. * Helpers
  9260. */
  9261. const expandRange = (args, options) => {
  9262. if (typeof options.expandRange === 'function') {
  9263. return options.expandRange(...args, options);
  9264. }
  9265. args.sort();
  9266. const value = `[${args.join('-')}]`;
  9267. return value;
  9268. };
  9269. /**
  9270. * Create the message for a syntax error
  9271. */
  9272. const syntaxError = (type, char) => {
  9273. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  9274. };
  9275. /**
  9276. * Parse the given input string.
  9277. * @param {String} input
  9278. * @param {Object} options
  9279. * @return {Object}
  9280. */
  9281. const parse = (input, options) => {
  9282. if (typeof input !== 'string') {
  9283. throw new TypeError('Expected a string');
  9284. }
  9285. input = REPLACEMENTS[input] || input;
  9286. const opts = { ...options };
  9287. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  9288. let len = input.length;
  9289. if (len > max) {
  9290. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  9291. }
  9292. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  9293. const tokens = [bos];
  9294. const capture = opts.capture ? '' : '?:';
  9295. // create constants based on platform, for windows or posix
  9296. const PLATFORM_CHARS = constants.globChars(opts.windows);
  9297. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  9298. const {
  9299. DOT_LITERAL,
  9300. PLUS_LITERAL,
  9301. SLASH_LITERAL,
  9302. ONE_CHAR,
  9303. DOTS_SLASH,
  9304. NO_DOT,
  9305. NO_DOT_SLASH,
  9306. NO_DOTS_SLASH,
  9307. QMARK,
  9308. QMARK_NO_DOT,
  9309. STAR,
  9310. START_ANCHOR
  9311. } = PLATFORM_CHARS;
  9312. const globstar = opts => {
  9313. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  9314. };
  9315. const nodot = opts.dot ? '' : NO_DOT;
  9316. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  9317. let star = opts.bash === true ? globstar(opts) : STAR;
  9318. if (opts.capture) {
  9319. star = `(${star})`;
  9320. }
  9321. // minimatch options support
  9322. if (typeof opts.noext === 'boolean') {
  9323. opts.noextglob = opts.noext;
  9324. }
  9325. const state = {
  9326. input,
  9327. index: -1,
  9328. start: 0,
  9329. dot: opts.dot === true,
  9330. consumed: '',
  9331. output: '',
  9332. prefix: '',
  9333. backtrack: false,
  9334. negated: false,
  9335. brackets: 0,
  9336. braces: 0,
  9337. parens: 0,
  9338. quotes: 0,
  9339. globstar: false,
  9340. tokens
  9341. };
  9342. input = utils.removePrefix(input, state);
  9343. len = input.length;
  9344. const extglobs = [];
  9345. const braces = [];
  9346. const stack = [];
  9347. let prev = bos;
  9348. let value;
  9349. /**
  9350. * Tokenizing helpers
  9351. */
  9352. const eos = () => state.index === len - 1;
  9353. const peek = state.peek = (n = 1) => input[state.index + n];
  9354. const advance = state.advance = () => input[++state.index] || '';
  9355. const remaining = () => input.slice(state.index + 1);
  9356. const consume = (value = '', num = 0) => {
  9357. state.consumed += value;
  9358. state.index += num;
  9359. };
  9360. const append = token => {
  9361. state.output += token.output != null ? token.output : token.value;
  9362. consume(token.value);
  9363. };
  9364. const negate = () => {
  9365. let count = 1;
  9366. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  9367. advance();
  9368. state.start++;
  9369. count++;
  9370. }
  9371. if (count % 2 === 0) {
  9372. return false;
  9373. }
  9374. state.negated = true;
  9375. state.start++;
  9376. return true;
  9377. };
  9378. const increment = type => {
  9379. state[type]++;
  9380. stack.push(type);
  9381. };
  9382. const decrement = type => {
  9383. state[type]--;
  9384. stack.pop();
  9385. };
  9386. /**
  9387. * Push tokens onto the tokens array. This helper speeds up
  9388. * tokenizing by 1) helping us avoid backtracking as much as possible,
  9389. * and 2) helping us avoid creating extra tokens when consecutive
  9390. * characters are plain text. This improves performance and simplifies
  9391. * lookbehinds.
  9392. */
  9393. const push = tok => {
  9394. if (prev.type === 'globstar') {
  9395. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  9396. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  9397. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  9398. state.output = state.output.slice(0, -prev.output.length);
  9399. prev.type = 'star';
  9400. prev.value = '*';
  9401. prev.output = star;
  9402. state.output += prev.output;
  9403. }
  9404. }
  9405. if (extglobs.length && tok.type !== 'paren') {
  9406. extglobs[extglobs.length - 1].inner += tok.value;
  9407. }
  9408. if (tok.value || tok.output) append(tok);
  9409. if (prev && prev.type === 'text' && tok.type === 'text') {
  9410. prev.output = (prev.output || prev.value) + tok.value;
  9411. prev.value += tok.value;
  9412. return;
  9413. }
  9414. tok.prev = prev;
  9415. tokens.push(tok);
  9416. prev = tok;
  9417. };
  9418. const extglobOpen = (type, value) => {
  9419. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  9420. token.prev = prev;
  9421. token.parens = state.parens;
  9422. token.output = state.output;
  9423. const output = (opts.capture ? '(' : '') + token.open;
  9424. increment('parens');
  9425. push({ type, value, output: state.output ? '' : ONE_CHAR });
  9426. push({ type: 'paren', extglob: true, value: advance(), output });
  9427. extglobs.push(token);
  9428. };
  9429. const extglobClose = token => {
  9430. let output = token.close + (opts.capture ? ')' : '');
  9431. let rest;
  9432. if (token.type === 'negate') {
  9433. let extglobStar = star;
  9434. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  9435. extglobStar = globstar(opts);
  9436. }
  9437. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  9438. output = token.close = `)$))${extglobStar}`;
  9439. }
  9440. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  9441. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  9442. // In this case, we need to parse the string and use it in the output of the original pattern.
  9443. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  9444. //
  9445. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  9446. const expression = parse(rest, { ...options, fastpaths: false }).output;
  9447. output = token.close = `)${expression})${extglobStar})`;
  9448. }
  9449. if (token.prev.type === 'bos') {
  9450. state.negatedExtglob = true;
  9451. }
  9452. }
  9453. push({ type: 'paren', extglob: true, value, output });
  9454. decrement('parens');
  9455. };
  9456. /**
  9457. * Fast paths
  9458. */
  9459. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  9460. let backslashes = false;
  9461. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  9462. if (first === '\\') {
  9463. backslashes = true;
  9464. return m;
  9465. }
  9466. if (first === '?') {
  9467. if (esc) {
  9468. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  9469. }
  9470. if (index === 0) {
  9471. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  9472. }
  9473. return QMARK.repeat(chars.length);
  9474. }
  9475. if (first === '.') {
  9476. return DOT_LITERAL.repeat(chars.length);
  9477. }
  9478. if (first === '*') {
  9479. if (esc) {
  9480. return esc + first + (rest ? star : '');
  9481. }
  9482. return star;
  9483. }
  9484. return esc ? m : `\\${m}`;
  9485. });
  9486. if (backslashes === true) {
  9487. if (opts.unescape === true) {
  9488. output = output.replace(/\\/g, '');
  9489. } else {
  9490. output = output.replace(/\\+/g, m => {
  9491. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  9492. });
  9493. }
  9494. }
  9495. if (output === input && opts.contains === true) {
  9496. state.output = input;
  9497. return state;
  9498. }
  9499. state.output = utils.wrapOutput(output, state, options);
  9500. return state;
  9501. }
  9502. /**
  9503. * Tokenize input until we reach end-of-string
  9504. */
  9505. while (!eos()) {
  9506. value = advance();
  9507. if (value === '\u0000') {
  9508. continue;
  9509. }
  9510. /**
  9511. * Escaped characters
  9512. */
  9513. if (value === '\\') {
  9514. const next = peek();
  9515. if (next === '/' && opts.bash !== true) {
  9516. continue;
  9517. }
  9518. if (next === '.' || next === ';') {
  9519. continue;
  9520. }
  9521. if (!next) {
  9522. value += '\\';
  9523. push({ type: 'text', value });
  9524. continue;
  9525. }
  9526. // collapse slashes to reduce potential for exploits
  9527. const match = /^\\+/.exec(remaining());
  9528. let slashes = 0;
  9529. if (match && match[0].length > 2) {
  9530. slashes = match[0].length;
  9531. state.index += slashes;
  9532. if (slashes % 2 !== 0) {
  9533. value += '\\';
  9534. }
  9535. }
  9536. if (opts.unescape === true) {
  9537. value = advance();
  9538. } else {
  9539. value += advance();
  9540. }
  9541. if (state.brackets === 0) {
  9542. push({ type: 'text', value });
  9543. continue;
  9544. }
  9545. }
  9546. /**
  9547. * If we're inside a regex character class, continue
  9548. * until we reach the closing bracket.
  9549. */
  9550. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  9551. if (opts.posix !== false && value === ':') {
  9552. const inner = prev.value.slice(1);
  9553. if (inner.includes('[')) {
  9554. prev.posix = true;
  9555. if (inner.includes(':')) {
  9556. const idx = prev.value.lastIndexOf('[');
  9557. const pre = prev.value.slice(0, idx);
  9558. const rest = prev.value.slice(idx + 2);
  9559. const posix = POSIX_REGEX_SOURCE[rest];
  9560. if (posix) {
  9561. prev.value = pre + posix;
  9562. state.backtrack = true;
  9563. advance();
  9564. if (!bos.output && tokens.indexOf(prev) === 1) {
  9565. bos.output = ONE_CHAR;
  9566. }
  9567. continue;
  9568. }
  9569. }
  9570. }
  9571. }
  9572. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  9573. value = `\\${value}`;
  9574. }
  9575. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  9576. value = `\\${value}`;
  9577. }
  9578. if (opts.posix === true && value === '!' && prev.value === '[') {
  9579. value = '^';
  9580. }
  9581. prev.value += value;
  9582. append({ value });
  9583. continue;
  9584. }
  9585. /**
  9586. * If we're inside a quoted string, continue
  9587. * until we reach the closing double quote.
  9588. */
  9589. if (state.quotes === 1 && value !== '"') {
  9590. value = utils.escapeRegex(value);
  9591. prev.value += value;
  9592. append({ value });
  9593. continue;
  9594. }
  9595. /**
  9596. * Double quotes
  9597. */
  9598. if (value === '"') {
  9599. state.quotes = state.quotes === 1 ? 0 : 1;
  9600. if (opts.keepQuotes === true) {
  9601. push({ type: 'text', value });
  9602. }
  9603. continue;
  9604. }
  9605. /**
  9606. * Parentheses
  9607. */
  9608. if (value === '(') {
  9609. increment('parens');
  9610. push({ type: 'paren', value });
  9611. continue;
  9612. }
  9613. if (value === ')') {
  9614. if (state.parens === 0 && opts.strictBrackets === true) {
  9615. throw new SyntaxError(syntaxError('opening', '('));
  9616. }
  9617. const extglob = extglobs[extglobs.length - 1];
  9618. if (extglob && state.parens === extglob.parens + 1) {
  9619. extglobClose(extglobs.pop());
  9620. continue;
  9621. }
  9622. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  9623. decrement('parens');
  9624. continue;
  9625. }
  9626. /**
  9627. * Square brackets
  9628. */
  9629. if (value === '[') {
  9630. if (opts.nobracket === true || !remaining().includes(']')) {
  9631. if (opts.nobracket !== true && opts.strictBrackets === true) {
  9632. throw new SyntaxError(syntaxError('closing', ']'));
  9633. }
  9634. value = `\\${value}`;
  9635. } else {
  9636. increment('brackets');
  9637. }
  9638. push({ type: 'bracket', value });
  9639. continue;
  9640. }
  9641. if (value === ']') {
  9642. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  9643. push({ type: 'text', value, output: `\\${value}` });
  9644. continue;
  9645. }
  9646. if (state.brackets === 0) {
  9647. if (opts.strictBrackets === true) {
  9648. throw new SyntaxError(syntaxError('opening', '['));
  9649. }
  9650. push({ type: 'text', value, output: `\\${value}` });
  9651. continue;
  9652. }
  9653. decrement('brackets');
  9654. const prevValue = prev.value.slice(1);
  9655. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  9656. value = `/${value}`;
  9657. }
  9658. prev.value += value;
  9659. append({ value });
  9660. // when literal brackets are explicitly disabled
  9661. // assume we should match with a regex character class
  9662. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  9663. continue;
  9664. }
  9665. const escaped = utils.escapeRegex(prev.value);
  9666. state.output = state.output.slice(0, -prev.value.length);
  9667. // when literal brackets are explicitly enabled
  9668. // assume we should escape the brackets to match literal characters
  9669. if (opts.literalBrackets === true) {
  9670. state.output += escaped;
  9671. prev.value = escaped;
  9672. continue;
  9673. }
  9674. // when the user specifies nothing, try to match both
  9675. prev.value = `(${capture}${escaped}|${prev.value})`;
  9676. state.output += prev.value;
  9677. continue;
  9678. }
  9679. /**
  9680. * Braces
  9681. */
  9682. if (value === '{' && opts.nobrace !== true) {
  9683. increment('braces');
  9684. const open = {
  9685. type: 'brace',
  9686. value,
  9687. output: '(',
  9688. outputIndex: state.output.length,
  9689. tokensIndex: state.tokens.length
  9690. };
  9691. braces.push(open);
  9692. push(open);
  9693. continue;
  9694. }
  9695. if (value === '}') {
  9696. const brace = braces[braces.length - 1];
  9697. if (opts.nobrace === true || !brace) {
  9698. push({ type: 'text', value, output: value });
  9699. continue;
  9700. }
  9701. let output = ')';
  9702. if (brace.dots === true) {
  9703. const arr = tokens.slice();
  9704. const range = [];
  9705. for (let i = arr.length - 1; i >= 0; i--) {
  9706. tokens.pop();
  9707. if (arr[i].type === 'brace') {
  9708. break;
  9709. }
  9710. if (arr[i].type !== 'dots') {
  9711. range.unshift(arr[i].value);
  9712. }
  9713. }
  9714. output = expandRange(range, opts);
  9715. state.backtrack = true;
  9716. }
  9717. if (brace.comma !== true && brace.dots !== true) {
  9718. const out = state.output.slice(0, brace.outputIndex);
  9719. const toks = state.tokens.slice(brace.tokensIndex);
  9720. brace.value = brace.output = '\\{';
  9721. value = output = '\\}';
  9722. state.output = out;
  9723. for (const t of toks) {
  9724. state.output += (t.output || t.value);
  9725. }
  9726. }
  9727. push({ type: 'brace', value, output });
  9728. decrement('braces');
  9729. braces.pop();
  9730. continue;
  9731. }
  9732. /**
  9733. * Pipes
  9734. */
  9735. if (value === '|') {
  9736. if (extglobs.length > 0) {
  9737. extglobs[extglobs.length - 1].conditions++;
  9738. }
  9739. push({ type: 'text', value });
  9740. continue;
  9741. }
  9742. /**
  9743. * Commas
  9744. */
  9745. if (value === ',') {
  9746. let output = value;
  9747. const brace = braces[braces.length - 1];
  9748. if (brace && stack[stack.length - 1] === 'braces') {
  9749. brace.comma = true;
  9750. output = '|';
  9751. }
  9752. push({ type: 'comma', value, output });
  9753. continue;
  9754. }
  9755. /**
  9756. * Slashes
  9757. */
  9758. if (value === '/') {
  9759. // if the beginning of the glob is "./", advance the start
  9760. // to the current index, and don't add the "./" characters
  9761. // to the state. This greatly simplifies lookbehinds when
  9762. // checking for BOS characters like "!" and "." (not "./")
  9763. if (prev.type === 'dot' && state.index === state.start + 1) {
  9764. state.start = state.index + 1;
  9765. state.consumed = '';
  9766. state.output = '';
  9767. tokens.pop();
  9768. prev = bos; // reset "prev" to the first token
  9769. continue;
  9770. }
  9771. push({ type: 'slash', value, output: SLASH_LITERAL });
  9772. continue;
  9773. }
  9774. /**
  9775. * Dots
  9776. */
  9777. if (value === '.') {
  9778. if (state.braces > 0 && prev.type === 'dot') {
  9779. if (prev.value === '.') prev.output = DOT_LITERAL;
  9780. const brace = braces[braces.length - 1];
  9781. prev.type = 'dots';
  9782. prev.output += value;
  9783. prev.value += value;
  9784. brace.dots = true;
  9785. continue;
  9786. }
  9787. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  9788. push({ type: 'text', value, output: DOT_LITERAL });
  9789. continue;
  9790. }
  9791. push({ type: 'dot', value, output: DOT_LITERAL });
  9792. continue;
  9793. }
  9794. /**
  9795. * Question marks
  9796. */
  9797. if (value === '?') {
  9798. const isGroup = prev && prev.value === '(';
  9799. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9800. extglobOpen('qmark', value);
  9801. continue;
  9802. }
  9803. if (prev && prev.type === 'paren') {
  9804. const next = peek();
  9805. let output = value;
  9806. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  9807. output = `\\${value}`;
  9808. }
  9809. push({ type: 'text', value, output });
  9810. continue;
  9811. }
  9812. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  9813. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  9814. continue;
  9815. }
  9816. push({ type: 'qmark', value, output: QMARK });
  9817. continue;
  9818. }
  9819. /**
  9820. * Exclamation
  9821. */
  9822. if (value === '!') {
  9823. if (opts.noextglob !== true && peek() === '(') {
  9824. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  9825. extglobOpen('negate', value);
  9826. continue;
  9827. }
  9828. }
  9829. if (opts.nonegate !== true && state.index === 0) {
  9830. negate();
  9831. continue;
  9832. }
  9833. }
  9834. /**
  9835. * Plus
  9836. */
  9837. if (value === '+') {
  9838. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9839. extglobOpen('plus', value);
  9840. continue;
  9841. }
  9842. if ((prev && prev.value === '(') || opts.regex === false) {
  9843. push({ type: 'plus', value, output: PLUS_LITERAL });
  9844. continue;
  9845. }
  9846. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  9847. push({ type: 'plus', value });
  9848. continue;
  9849. }
  9850. push({ type: 'plus', value: PLUS_LITERAL });
  9851. continue;
  9852. }
  9853. /**
  9854. * Plain text
  9855. */
  9856. if (value === '@') {
  9857. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9858. push({ type: 'at', extglob: true, value, output: '' });
  9859. continue;
  9860. }
  9861. push({ type: 'text', value });
  9862. continue;
  9863. }
  9864. /**
  9865. * Plain text
  9866. */
  9867. if (value !== '*') {
  9868. if (value === '$' || value === '^') {
  9869. value = `\\${value}`;
  9870. }
  9871. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  9872. if (match) {
  9873. value += match[0];
  9874. state.index += match[0].length;
  9875. }
  9876. push({ type: 'text', value });
  9877. continue;
  9878. }
  9879. /**
  9880. * Stars
  9881. */
  9882. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  9883. prev.type = 'star';
  9884. prev.star = true;
  9885. prev.value += value;
  9886. prev.output = star;
  9887. state.backtrack = true;
  9888. state.globstar = true;
  9889. consume(value);
  9890. continue;
  9891. }
  9892. let rest = remaining();
  9893. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  9894. extglobOpen('star', value);
  9895. continue;
  9896. }
  9897. if (prev.type === 'star') {
  9898. if (opts.noglobstar === true) {
  9899. consume(value);
  9900. continue;
  9901. }
  9902. const prior = prev.prev;
  9903. const before = prior.prev;
  9904. const isStart = prior.type === 'slash' || prior.type === 'bos';
  9905. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  9906. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  9907. push({ type: 'star', value, output: '' });
  9908. continue;
  9909. }
  9910. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  9911. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  9912. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  9913. push({ type: 'star', value, output: '' });
  9914. continue;
  9915. }
  9916. // strip consecutive `/**/`
  9917. while (rest.slice(0, 3) === '/**') {
  9918. const after = input[state.index + 4];
  9919. if (after && after !== '/') {
  9920. break;
  9921. }
  9922. rest = rest.slice(3);
  9923. consume('/**', 3);
  9924. }
  9925. if (prior.type === 'bos' && eos()) {
  9926. prev.type = 'globstar';
  9927. prev.value += value;
  9928. prev.output = globstar(opts);
  9929. state.output = prev.output;
  9930. state.globstar = true;
  9931. consume(value);
  9932. continue;
  9933. }
  9934. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  9935. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  9936. prior.output = `(?:${prior.output}`;
  9937. prev.type = 'globstar';
  9938. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  9939. prev.value += value;
  9940. state.globstar = true;
  9941. state.output += prior.output + prev.output;
  9942. consume(value);
  9943. continue;
  9944. }
  9945. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  9946. const end = rest[1] !== void 0 ? '|$' : '';
  9947. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  9948. prior.output = `(?:${prior.output}`;
  9949. prev.type = 'globstar';
  9950. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  9951. prev.value += value;
  9952. state.output += prior.output + prev.output;
  9953. state.globstar = true;
  9954. consume(value + advance());
  9955. push({ type: 'slash', value: '/', output: '' });
  9956. continue;
  9957. }
  9958. if (prior.type === 'bos' && rest[0] === '/') {
  9959. prev.type = 'globstar';
  9960. prev.value += value;
  9961. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  9962. state.output = prev.output;
  9963. state.globstar = true;
  9964. consume(value + advance());
  9965. push({ type: 'slash', value: '/', output: '' });
  9966. continue;
  9967. }
  9968. // remove single star from output
  9969. state.output = state.output.slice(0, -prev.output.length);
  9970. // reset previous token to globstar
  9971. prev.type = 'globstar';
  9972. prev.output = globstar(opts);
  9973. prev.value += value;
  9974. // reset output with globstar
  9975. state.output += prev.output;
  9976. state.globstar = true;
  9977. consume(value);
  9978. continue;
  9979. }
  9980. const token = { type: 'star', value, output: star };
  9981. if (opts.bash === true) {
  9982. token.output = '.*?';
  9983. if (prev.type === 'bos' || prev.type === 'slash') {
  9984. token.output = nodot + token.output;
  9985. }
  9986. push(token);
  9987. continue;
  9988. }
  9989. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  9990. token.output = value;
  9991. push(token);
  9992. continue;
  9993. }
  9994. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  9995. if (prev.type === 'dot') {
  9996. state.output += NO_DOT_SLASH;
  9997. prev.output += NO_DOT_SLASH;
  9998. } else if (opts.dot === true) {
  9999. state.output += NO_DOTS_SLASH;
  10000. prev.output += NO_DOTS_SLASH;
  10001. } else {
  10002. state.output += nodot;
  10003. prev.output += nodot;
  10004. }
  10005. if (peek() !== '*') {
  10006. state.output += ONE_CHAR;
  10007. prev.output += ONE_CHAR;
  10008. }
  10009. }
  10010. push(token);
  10011. }
  10012. while (state.brackets > 0) {
  10013. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  10014. state.output = utils.escapeLast(state.output, '[');
  10015. decrement('brackets');
  10016. }
  10017. while (state.parens > 0) {
  10018. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  10019. state.output = utils.escapeLast(state.output, '(');
  10020. decrement('parens');
  10021. }
  10022. while (state.braces > 0) {
  10023. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  10024. state.output = utils.escapeLast(state.output, '{');
  10025. decrement('braces');
  10026. }
  10027. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  10028. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  10029. }
  10030. // rebuild the output if we had to backtrack at any point
  10031. if (state.backtrack === true) {
  10032. state.output = '';
  10033. for (const token of state.tokens) {
  10034. state.output += token.output != null ? token.output : token.value;
  10035. if (token.suffix) {
  10036. state.output += token.suffix;
  10037. }
  10038. }
  10039. }
  10040. return state;
  10041. };
  10042. /**
  10043. * Fast paths for creating regular expressions for common glob patterns.
  10044. * This can significantly speed up processing and has very little downside
  10045. * impact when none of the fast paths match.
  10046. */
  10047. parse.fastpaths = (input, options) => {
  10048. const opts = { ...options };
  10049. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  10050. const len = input.length;
  10051. if (len > max) {
  10052. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  10053. }
  10054. input = REPLACEMENTS[input] || input;
  10055. // create constants based on platform, for windows or posix
  10056. const {
  10057. DOT_LITERAL,
  10058. SLASH_LITERAL,
  10059. ONE_CHAR,
  10060. DOTS_SLASH,
  10061. NO_DOT,
  10062. NO_DOTS,
  10063. NO_DOTS_SLASH,
  10064. STAR,
  10065. START_ANCHOR
  10066. } = constants.globChars(opts.windows);
  10067. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  10068. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  10069. const capture = opts.capture ? '' : '?:';
  10070. const state = { negated: false, prefix: '' };
  10071. let star = opts.bash === true ? '.*?' : STAR;
  10072. if (opts.capture) {
  10073. star = `(${star})`;
  10074. }
  10075. const globstar = opts => {
  10076. if (opts.noglobstar === true) return star;
  10077. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  10078. };
  10079. const create = str => {
  10080. switch (str) {
  10081. case '*':
  10082. return `${nodot}${ONE_CHAR}${star}`;
  10083. case '.*':
  10084. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  10085. case '*.*':
  10086. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  10087. case '*/*':
  10088. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  10089. case '**':
  10090. return nodot + globstar(opts);
  10091. case '**/*':
  10092. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  10093. case '**/*.*':
  10094. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  10095. case '**/.*':
  10096. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  10097. default: {
  10098. const match = /^(.*?)\.(\w+)$/.exec(str);
  10099. if (!match) return;
  10100. const source = create(match[1]);
  10101. if (!source) return;
  10102. return source + DOT_LITERAL + match[2];
  10103. }
  10104. }
  10105. };
  10106. const output = utils.removePrefix(input, state);
  10107. let source = create(output);
  10108. if (source && opts.strictSlashes !== true) {
  10109. source += `${SLASH_LITERAL}?`;
  10110. }
  10111. return source;
  10112. };
  10113. parse_1 = parse;
  10114. return parse_1;
  10115. }
  10116. var picomatch_1$1;
  10117. var hasRequiredPicomatch$1;
  10118. function requirePicomatch$1 () {
  10119. if (hasRequiredPicomatch$1) return picomatch_1$1;
  10120. hasRequiredPicomatch$1 = 1;
  10121. const scan = /*@__PURE__*/ requireScan();
  10122. const parse = /*@__PURE__*/ requireParse();
  10123. const utils = /*@__PURE__*/ requireUtils();
  10124. const constants = /*@__PURE__*/ requireConstants();
  10125. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  10126. /**
  10127. * Creates a matcher function from one or more glob patterns. The
  10128. * returned function takes a string to match as its first argument,
  10129. * and returns true if the string is a match. The returned matcher
  10130. * function also takes a boolean as the second argument that, when true,
  10131. * returns an object with additional information.
  10132. *
  10133. * ```js
  10134. * const picomatch = require('picomatch');
  10135. * // picomatch(glob[, options]);
  10136. *
  10137. * const isMatch = picomatch('*.!(*a)');
  10138. * console.log(isMatch('a.a')); //=> false
  10139. * console.log(isMatch('a.b')); //=> true
  10140. * ```
  10141. * @name picomatch
  10142. * @param {String|Array} `globs` One or more glob patterns.
  10143. * @param {Object=} `options`
  10144. * @return {Function=} Returns a matcher function.
  10145. * @api public
  10146. */
  10147. const picomatch = (glob, options, returnState = false) => {
  10148. if (Array.isArray(glob)) {
  10149. const fns = glob.map(input => picomatch(input, options, returnState));
  10150. const arrayMatcher = str => {
  10151. for (const isMatch of fns) {
  10152. const state = isMatch(str);
  10153. if (state) return state;
  10154. }
  10155. return false;
  10156. };
  10157. return arrayMatcher;
  10158. }
  10159. const isState = isObject(glob) && glob.tokens && glob.input;
  10160. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  10161. throw new TypeError('Expected pattern to be a non-empty string');
  10162. }
  10163. const opts = options || {};
  10164. const posix = opts.windows;
  10165. const regex = isState
  10166. ? picomatch.compileRe(glob, options)
  10167. : picomatch.makeRe(glob, options, false, true);
  10168. const state = regex.state;
  10169. delete regex.state;
  10170. let isIgnored = () => false;
  10171. if (opts.ignore) {
  10172. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  10173. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  10174. }
  10175. const matcher = (input, returnObject = false) => {
  10176. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  10177. const result = { glob, state, regex, posix, input, output, match, isMatch };
  10178. if (typeof opts.onResult === 'function') {
  10179. opts.onResult(result);
  10180. }
  10181. if (isMatch === false) {
  10182. result.isMatch = false;
  10183. return returnObject ? result : false;
  10184. }
  10185. if (isIgnored(input)) {
  10186. if (typeof opts.onIgnore === 'function') {
  10187. opts.onIgnore(result);
  10188. }
  10189. result.isMatch = false;
  10190. return returnObject ? result : false;
  10191. }
  10192. if (typeof opts.onMatch === 'function') {
  10193. opts.onMatch(result);
  10194. }
  10195. return returnObject ? result : true;
  10196. };
  10197. if (returnState) {
  10198. matcher.state = state;
  10199. }
  10200. return matcher;
  10201. };
  10202. /**
  10203. * Test `input` with the given `regex`. This is used by the main
  10204. * `picomatch()` function to test the input string.
  10205. *
  10206. * ```js
  10207. * const picomatch = require('picomatch');
  10208. * // picomatch.test(input, regex[, options]);
  10209. *
  10210. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  10211. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  10212. * ```
  10213. * @param {String} `input` String to test.
  10214. * @param {RegExp} `regex`
  10215. * @return {Object} Returns an object with matching info.
  10216. * @api public
  10217. */
  10218. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  10219. if (typeof input !== 'string') {
  10220. throw new TypeError('Expected input to be a string');
  10221. }
  10222. if (input === '') {
  10223. return { isMatch: false, output: '' };
  10224. }
  10225. const opts = options || {};
  10226. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  10227. let match = input === glob;
  10228. let output = (match && format) ? format(input) : input;
  10229. if (match === false) {
  10230. output = format ? format(input) : input;
  10231. match = output === glob;
  10232. }
  10233. if (match === false || opts.capture === true) {
  10234. if (opts.matchBase === true || opts.basename === true) {
  10235. match = picomatch.matchBase(input, regex, options, posix);
  10236. } else {
  10237. match = regex.exec(output);
  10238. }
  10239. }
  10240. return { isMatch: Boolean(match), match, output };
  10241. };
  10242. /**
  10243. * Match the basename of a filepath.
  10244. *
  10245. * ```js
  10246. * const picomatch = require('picomatch');
  10247. * // picomatch.matchBase(input, glob[, options]);
  10248. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  10249. * ```
  10250. * @param {String} `input` String to test.
  10251. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  10252. * @return {Boolean}
  10253. * @api public
  10254. */
  10255. picomatch.matchBase = (input, glob, options) => {
  10256. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  10257. return regex.test(utils.basename(input));
  10258. };
  10259. /**
  10260. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  10261. *
  10262. * ```js
  10263. * const picomatch = require('picomatch');
  10264. * // picomatch.isMatch(string, patterns[, options]);
  10265. *
  10266. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  10267. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  10268. * ```
  10269. * @param {String|Array} str The string to test.
  10270. * @param {String|Array} patterns One or more glob patterns to use for matching.
  10271. * @param {Object} [options] See available [options](#options).
  10272. * @return {Boolean} Returns true if any patterns match `str`
  10273. * @api public
  10274. */
  10275. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  10276. /**
  10277. * Parse a glob pattern to create the source string for a regular
  10278. * expression.
  10279. *
  10280. * ```js
  10281. * const picomatch = require('picomatch');
  10282. * const result = picomatch.parse(pattern[, options]);
  10283. * ```
  10284. * @param {String} `pattern`
  10285. * @param {Object} `options`
  10286. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  10287. * @api public
  10288. */
  10289. picomatch.parse = (pattern, options) => {
  10290. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  10291. return parse(pattern, { ...options, fastpaths: false });
  10292. };
  10293. /**
  10294. * Scan a glob pattern to separate the pattern into segments.
  10295. *
  10296. * ```js
  10297. * const picomatch = require('picomatch');
  10298. * // picomatch.scan(input[, options]);
  10299. *
  10300. * const result = picomatch.scan('!./foo/*.js');
  10301. * console.log(result);
  10302. * { prefix: '!./',
  10303. * input: '!./foo/*.js',
  10304. * start: 3,
  10305. * base: 'foo',
  10306. * glob: '*.js',
  10307. * isBrace: false,
  10308. * isBracket: false,
  10309. * isGlob: true,
  10310. * isExtglob: false,
  10311. * isGlobstar: false,
  10312. * negated: true }
  10313. * ```
  10314. * @param {String} `input` Glob pattern to scan.
  10315. * @param {Object} `options`
  10316. * @return {Object} Returns an object with
  10317. * @api public
  10318. */
  10319. picomatch.scan = (input, options) => scan(input, options);
  10320. /**
  10321. * Compile a regular expression from the `state` object returned by the
  10322. * [parse()](#parse) method.
  10323. *
  10324. * @param {Object} `state`
  10325. * @param {Object} `options`
  10326. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  10327. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  10328. * @return {RegExp}
  10329. * @api public
  10330. */
  10331. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  10332. if (returnOutput === true) {
  10333. return state.output;
  10334. }
  10335. const opts = options || {};
  10336. const prepend = opts.contains ? '' : '^';
  10337. const append = opts.contains ? '' : '$';
  10338. let source = `${prepend}(?:${state.output})${append}`;
  10339. if (state && state.negated === true) {
  10340. source = `^(?!${source}).*$`;
  10341. }
  10342. const regex = picomatch.toRegex(source, options);
  10343. if (returnState === true) {
  10344. regex.state = state;
  10345. }
  10346. return regex;
  10347. };
  10348. /**
  10349. * Create a regular expression from a parsed glob pattern.
  10350. *
  10351. * ```js
  10352. * const picomatch = require('picomatch');
  10353. * const state = picomatch.parse('*.js');
  10354. * // picomatch.compileRe(state[, options]);
  10355. *
  10356. * console.log(picomatch.compileRe(state));
  10357. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  10358. * ```
  10359. * @param {String} `state` The object returned from the `.parse` method.
  10360. * @param {Object} `options`
  10361. * @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.
  10362. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  10363. * @return {RegExp} Returns a regex created from the given pattern.
  10364. * @api public
  10365. */
  10366. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  10367. if (!input || typeof input !== 'string') {
  10368. throw new TypeError('Expected a non-empty string');
  10369. }
  10370. let parsed = { negated: false, fastpaths: true };
  10371. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  10372. parsed.output = parse.fastpaths(input, options);
  10373. }
  10374. if (!parsed.output) {
  10375. parsed = parse(input, options);
  10376. }
  10377. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  10378. };
  10379. /**
  10380. * Create a regular expression from the given regex source string.
  10381. *
  10382. * ```js
  10383. * const picomatch = require('picomatch');
  10384. * // picomatch.toRegex(source[, options]);
  10385. *
  10386. * const { output } = picomatch.parse('*.js');
  10387. * console.log(picomatch.toRegex(output));
  10388. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  10389. * ```
  10390. * @param {String} `source` Regular expression source string.
  10391. * @param {Object} `options`
  10392. * @return {RegExp}
  10393. * @api public
  10394. */
  10395. picomatch.toRegex = (source, options) => {
  10396. try {
  10397. const opts = options || {};
  10398. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  10399. } catch (err) {
  10400. if (options && options.debug === true) throw err;
  10401. return /$^/;
  10402. }
  10403. };
  10404. /**
  10405. * Picomatch constants.
  10406. * @return {Object}
  10407. */
  10408. picomatch.constants = constants;
  10409. /**
  10410. * Expose "picomatch"
  10411. */
  10412. picomatch_1$1 = picomatch;
  10413. return picomatch_1$1;
  10414. }
  10415. var picomatch_1;
  10416. var hasRequiredPicomatch;
  10417. function requirePicomatch () {
  10418. if (hasRequiredPicomatch) return picomatch_1;
  10419. hasRequiredPicomatch = 1;
  10420. const pico = /*@__PURE__*/ requirePicomatch$1();
  10421. const utils = /*@__PURE__*/ requireUtils();
  10422. function picomatch(glob, options, returnState = false) {
  10423. // default to os.platform()
  10424. if (options && (options.windows === null || options.windows === undefined)) {
  10425. // don't mutate the original options object
  10426. options = { ...options, windows: utils.isWindows() };
  10427. }
  10428. return pico(glob, options, returnState);
  10429. }
  10430. Object.assign(picomatch, pico);
  10431. picomatch_1 = picomatch;
  10432. return picomatch_1;
  10433. }
  10434. var picomatchExports = /*@__PURE__*/ requirePicomatch();
  10435. const picomatch = /*@__PURE__*/getDefaultExportFromCjs(picomatchExports);
  10436. const extractors = {
  10437. ArrayPattern(names, param) {
  10438. for (const element of param.elements) {
  10439. if (element)
  10440. extractors[element.type](names, element);
  10441. }
  10442. },
  10443. AssignmentPattern(names, param) {
  10444. extractors[param.left.type](names, param.left);
  10445. },
  10446. Identifier(names, param) {
  10447. names.push(param.name);
  10448. },
  10449. MemberExpression() { },
  10450. ObjectPattern(names, param) {
  10451. for (const prop of param.properties) {
  10452. // @ts-ignore Typescript reports that this is not a valid type
  10453. if (prop.type === 'RestElement') {
  10454. extractors.RestElement(names, prop);
  10455. }
  10456. else {
  10457. extractors[prop.value.type](names, prop.value);
  10458. }
  10459. }
  10460. },
  10461. RestElement(names, param) {
  10462. extractors[param.argument.type](names, param.argument);
  10463. }
  10464. };
  10465. const extractAssignedNames = function extractAssignedNames(param) {
  10466. const names = [];
  10467. extractors[param.type](names, param);
  10468. return names;
  10469. };
  10470. // Helper since Typescript can't detect readonly arrays with Array.isArray
  10471. function isArray(arg) {
  10472. return Array.isArray(arg);
  10473. }
  10474. function ensureArray$1(thing) {
  10475. if (isArray(thing))
  10476. return thing;
  10477. if (thing == null)
  10478. return [];
  10479. return [thing];
  10480. }
  10481. const normalizePathRegExp = new RegExp(`\\${win32.sep}`, 'g');
  10482. const normalizePath = function normalizePath(filename) {
  10483. return filename.replace(normalizePathRegExp, posix.sep);
  10484. };
  10485. function getMatcherString$1(id, resolutionBase) {
  10486. if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) {
  10487. return normalizePath(id);
  10488. }
  10489. // resolve('') is valid and will default to process.cwd()
  10490. const basePath = normalizePath(resolve(resolutionBase || ''))
  10491. // escape all possible (posix + win) path characters that might interfere with regex
  10492. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  10493. // Note that we use posix.join because:
  10494. // 1. the basePath has been normalized to use /
  10495. // 2. the incoming glob (id) matcher, also uses /
  10496. // otherwise Node will force backslash (\) on windows
  10497. return posix.join(basePath, normalizePath(id));
  10498. }
  10499. const createFilter$1 = function createFilter(include, exclude, options) {
  10500. const resolutionBase = options && options.resolve;
  10501. const getMatcher = (id) => id instanceof RegExp
  10502. ? id
  10503. : {
  10504. test: (what) => {
  10505. // this refactor is a tad overly verbose but makes for easy debugging
  10506. const pattern = getMatcherString$1(id, resolutionBase);
  10507. const fn = picomatch(pattern, { dot: true });
  10508. const result = fn(what);
  10509. return result;
  10510. }
  10511. };
  10512. const includeMatchers = ensureArray$1(include).map(getMatcher);
  10513. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  10514. if (!includeMatchers.length && !excludeMatchers.length)
  10515. return (id) => typeof id === 'string' && !id.includes('\0');
  10516. return function result(id) {
  10517. if (typeof id !== 'string')
  10518. return false;
  10519. if (id.includes('\0'))
  10520. return false;
  10521. const pathId = normalizePath(id);
  10522. for (let i = 0; i < excludeMatchers.length; ++i) {
  10523. const matcher = excludeMatchers[i];
  10524. if (matcher instanceof RegExp) {
  10525. matcher.lastIndex = 0;
  10526. }
  10527. if (matcher.test(pathId))
  10528. return false;
  10529. }
  10530. for (let i = 0; i < includeMatchers.length; ++i) {
  10531. const matcher = includeMatchers[i];
  10532. if (matcher instanceof RegExp) {
  10533. matcher.lastIndex = 0;
  10534. }
  10535. if (matcher.test(pathId))
  10536. return true;
  10537. }
  10538. return !includeMatchers.length;
  10539. };
  10540. };
  10541. 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';
  10542. 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';
  10543. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  10544. forbiddenIdentifiers.add('');
  10545. class ArrayPattern extends NodeBase {
  10546. addExportedVariables(variables, exportNamesByVariable) {
  10547. for (const element of this.elements) {
  10548. element?.addExportedVariables(variables, exportNamesByVariable);
  10549. }
  10550. }
  10551. declare(kind, destructuredInitPath, init) {
  10552. const variables = [];
  10553. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10554. for (const element of this.elements) {
  10555. if (element !== null) {
  10556. variables.push(...element.declare(kind, includedPatternPath, init));
  10557. }
  10558. }
  10559. return variables;
  10560. }
  10561. deoptimizeAssignment(destructuredInitPath, init) {
  10562. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10563. for (const element of this.elements) {
  10564. element?.deoptimizeAssignment(includedPatternPath, init);
  10565. }
  10566. }
  10567. // Patterns can only be deoptimized at the empty path at the moment
  10568. deoptimizePath() {
  10569. for (const element of this.elements) {
  10570. element?.deoptimizePath(EMPTY_PATH);
  10571. }
  10572. }
  10573. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10574. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10575. for (const element of this.elements) {
  10576. if (element?.hasEffectsWhenDestructuring(context, includedPatternPath, init)) {
  10577. return true;
  10578. }
  10579. }
  10580. return false;
  10581. }
  10582. // Patterns are only checked at the empty path at the moment
  10583. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  10584. for (const element of this.elements) {
  10585. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  10586. return true;
  10587. }
  10588. return false;
  10589. }
  10590. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  10591. let included = false;
  10592. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10593. for (const element of [...this.elements].reverse()) {
  10594. if (element) {
  10595. if (included && !element.included) {
  10596. element.includeNode(context);
  10597. }
  10598. included =
  10599. element.includeDestructuredIfNecessary(context, includedPatternPath, init) || included;
  10600. }
  10601. }
  10602. if (!this.included && included) {
  10603. this.includeNode(context);
  10604. }
  10605. return this.included;
  10606. }
  10607. render(code, options) {
  10608. let removedStart = this.start + 1;
  10609. for (const element of this.elements) {
  10610. if (!element)
  10611. continue;
  10612. if (element.included) {
  10613. element.render(code, options);
  10614. removedStart = element.end;
  10615. }
  10616. else {
  10617. code.remove(removedStart, this.end - 1);
  10618. break;
  10619. }
  10620. }
  10621. }
  10622. markDeclarationReached() {
  10623. for (const element of this.elements) {
  10624. element?.markDeclarationReached();
  10625. }
  10626. }
  10627. }
  10628. ArrayPattern.prototype.includeNode = onlyIncludeSelf;
  10629. const getIncludedPatternPath = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  10630. ? destructuredInitPath
  10631. : [...destructuredInitPath, UnknownInteger];
  10632. class ArrowFunctionExpression extends FunctionBase {
  10633. constructor() {
  10634. super(...arguments);
  10635. this.objectEntity = null;
  10636. }
  10637. get expression() {
  10638. return isFlagSet(this.flags, 8388608 /* Flag.expression */);
  10639. }
  10640. set expression(value) {
  10641. this.flags = setFlag(this.flags, 8388608 /* Flag.expression */, value);
  10642. }
  10643. createScope(parentScope) {
  10644. this.scope = new ReturnValueScope(parentScope, false);
  10645. }
  10646. hasEffects() {
  10647. return false;
  10648. }
  10649. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10650. if (this.annotationNoSideEffects &&
  10651. path.length === 0 &&
  10652. interaction.type === INTERACTION_CALLED) {
  10653. return false;
  10654. }
  10655. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  10656. return true;
  10657. }
  10658. if (interaction.type === INTERACTION_CALLED) {
  10659. const { ignore, brokenFlow } = context;
  10660. context.ignore = {
  10661. breaks: false,
  10662. continues: false,
  10663. labels: new Set(),
  10664. returnYield: true,
  10665. this: false
  10666. };
  10667. if (this.body.hasEffects(context))
  10668. return true;
  10669. context.ignore = ignore;
  10670. context.brokenFlow = brokenFlow;
  10671. }
  10672. return false;
  10673. }
  10674. onlyFunctionCallUsed() {
  10675. const isIIFE = this.parent.type === CallExpression$1 &&
  10676. this.parent.callee === this;
  10677. return isIIFE || super.onlyFunctionCallUsed();
  10678. }
  10679. include(context, includeChildrenRecursively) {
  10680. super.include(context, includeChildrenRecursively);
  10681. for (const parameter of this.params) {
  10682. if (!(parameter instanceof Identifier)) {
  10683. parameter.include(context, includeChildrenRecursively);
  10684. }
  10685. }
  10686. }
  10687. includeNode(context) {
  10688. this.included = true;
  10689. this.body.includePath(UNKNOWN_PATH, context);
  10690. for (const parameter of this.params) {
  10691. if (!(parameter instanceof Identifier)) {
  10692. parameter.includePath(UNKNOWN_PATH, context);
  10693. }
  10694. }
  10695. }
  10696. getObjectEntity() {
  10697. if (this.objectEntity !== null) {
  10698. return this.objectEntity;
  10699. }
  10700. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  10701. }
  10702. }
  10703. class ObjectPattern extends NodeBase {
  10704. addExportedVariables(variables, exportNamesByVariable) {
  10705. for (const property of this.properties) {
  10706. if (property.type === Property$1) {
  10707. property.value.addExportedVariables(variables, exportNamesByVariable);
  10708. }
  10709. else {
  10710. property.argument.addExportedVariables(variables, exportNamesByVariable);
  10711. }
  10712. }
  10713. }
  10714. declare(kind, destructuredInitPath, init) {
  10715. const variables = [];
  10716. for (const property of this.properties) {
  10717. variables.push(...property.declare(kind, destructuredInitPath, init));
  10718. }
  10719. return variables;
  10720. }
  10721. deoptimizeAssignment(destructuredInitPath, init) {
  10722. for (const property of this.properties) {
  10723. property.deoptimizeAssignment(destructuredInitPath, init);
  10724. }
  10725. }
  10726. deoptimizePath(path) {
  10727. if (path.length === 0) {
  10728. for (const property of this.properties) {
  10729. property.deoptimizePath(path);
  10730. }
  10731. }
  10732. }
  10733. hasEffectsOnInteractionAtPath(
  10734. // At the moment, this is only triggered for assignment left-hand sides,
  10735. // where the path is empty
  10736. _path, interaction, context) {
  10737. for (const property of this.properties) {
  10738. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  10739. return true;
  10740. }
  10741. return false;
  10742. }
  10743. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10744. for (const property of this.properties) {
  10745. if (property.hasEffectsWhenDestructuring(context, destructuredInitPath, init))
  10746. return true;
  10747. }
  10748. return false;
  10749. }
  10750. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  10751. if (!this.properties.length)
  10752. return this.included;
  10753. const lastProperty = this.properties.at(-1);
  10754. let included = lastProperty.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  10755. const lastPropertyIsRestElement = lastProperty.type === RestElement$1;
  10756. for (const property of this.properties.slice(0, -1)) {
  10757. if (lastPropertyIsRestElement && included && !property.included) {
  10758. property.includeNode(context);
  10759. }
  10760. included =
  10761. property.includeDestructuredIfNecessary(context, destructuredInitPath, init) || included;
  10762. }
  10763. if (!this.included && included) {
  10764. this.includeNode(context);
  10765. }
  10766. return this.included;
  10767. }
  10768. markDeclarationReached() {
  10769. for (const property of this.properties) {
  10770. property.markDeclarationReached();
  10771. }
  10772. }
  10773. render(code, options) {
  10774. if (this.properties.length > 0) {
  10775. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  10776. let lastSeparatorPos = null;
  10777. for (const { node, separator, start, end } of separatedNodes) {
  10778. if (!node.included) {
  10779. treeshakeNode(node, code, start, end);
  10780. continue;
  10781. }
  10782. lastSeparatorPos = separator;
  10783. node.render(code, options);
  10784. }
  10785. if (lastSeparatorPos) {
  10786. code.remove(lastSeparatorPos, this.end - 1);
  10787. }
  10788. }
  10789. }
  10790. }
  10791. ObjectPattern.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  10792. ObjectPattern.prototype.applyDeoptimizations = doNotDeoptimize;
  10793. class AssignmentExpression extends NodeBase {
  10794. constructor() {
  10795. super(...arguments);
  10796. this.isConstReassignment = false;
  10797. }
  10798. hasEffects(context) {
  10799. const { deoptimized, isConstReassignment, left, operator, right } = this;
  10800. if (!deoptimized)
  10801. this.applyDeoptimizations();
  10802. // MemberExpressions do not access the property before assignments if the
  10803. // operator is '='.
  10804. return (isConstReassignment ||
  10805. right.hasEffects(context) ||
  10806. left.hasEffectsAsAssignmentTarget(context, operator !== '=') ||
  10807. this.left.hasEffectsWhenDestructuring?.(context, EMPTY_PATH, right));
  10808. }
  10809. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10810. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  10811. }
  10812. include(context, includeChildrenRecursively) {
  10813. const { deoptimized, isConstReassignment, left, right, operator } = this;
  10814. if (!deoptimized)
  10815. this.applyDeoptimizations();
  10816. if (!this.included)
  10817. this.includeNode(context);
  10818. const hasEffectsContext = createHasEffectsContext();
  10819. if (includeChildrenRecursively ||
  10820. isConstReassignment ||
  10821. operator !== '=' ||
  10822. left.included ||
  10823. left.hasEffectsAsAssignmentTarget(hasEffectsContext, false) ||
  10824. left.hasEffectsWhenDestructuring?.(hasEffectsContext, EMPTY_PATH, right)) {
  10825. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  10826. }
  10827. right.include(context, includeChildrenRecursively);
  10828. }
  10829. includeNode(context) {
  10830. this.included = true;
  10831. if (!this.deoptimized)
  10832. this.applyDeoptimizations();
  10833. this.right.includePath(UNKNOWN_PATH, context);
  10834. }
  10835. initialise() {
  10836. super.initialise();
  10837. if (this.left instanceof Identifier) {
  10838. const variable = this.scope.variables.get(this.left.name);
  10839. if (variable?.kind === 'const') {
  10840. this.isConstReassignment = true;
  10841. this.scope.context.log(LOGLEVEL_WARN, logConstVariableReassignError(), this.left.start);
  10842. }
  10843. }
  10844. this.left.setAssignedValue(this.right);
  10845. }
  10846. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  10847. const { left, right, start, end, parent } = this;
  10848. if (left.included) {
  10849. left.render(code, options);
  10850. right.render(code, options);
  10851. }
  10852. else {
  10853. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  10854. code.remove(start, inclusionStart);
  10855. if (preventASI) {
  10856. removeLineBreaks(code, inclusionStart, right.start);
  10857. }
  10858. right.render(code, options, {
  10859. renderedParentType: renderedParentType || parent.type,
  10860. renderedSurroundingElement: renderedSurroundingElement || parent.type
  10861. });
  10862. }
  10863. if (options.format === 'system') {
  10864. if (left instanceof Identifier) {
  10865. const variable = left.variable;
  10866. const exportNames = options.exportNamesByVariable.get(variable);
  10867. if (exportNames) {
  10868. if (exportNames.length === 1) {
  10869. renderSystemExportExpression(variable, start, end, code, options);
  10870. }
  10871. else {
  10872. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  10873. }
  10874. return;
  10875. }
  10876. }
  10877. else {
  10878. const systemPatternExports = [];
  10879. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  10880. if (systemPatternExports.length > 0) {
  10881. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  10882. return;
  10883. }
  10884. }
  10885. }
  10886. if (left.included &&
  10887. left instanceof ObjectPattern &&
  10888. (renderedSurroundingElement === ExpressionStatement$1 ||
  10889. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  10890. code.appendRight(start, '(');
  10891. code.prependLeft(end, ')');
  10892. }
  10893. }
  10894. applyDeoptimizations() {
  10895. this.deoptimized = true;
  10896. this.left.deoptimizeAssignment(EMPTY_PATH, this.right);
  10897. this.scope.context.requestTreeshakingPass();
  10898. }
  10899. }
  10900. class AssignmentPattern extends NodeBase {
  10901. addExportedVariables(variables, exportNamesByVariable) {
  10902. this.left.addExportedVariables(variables, exportNamesByVariable);
  10903. }
  10904. declare(kind, destructuredInitPath, init) {
  10905. return this.left.declare(kind, destructuredInitPath, init);
  10906. }
  10907. deoptimizeAssignment(destructuredInitPath, init) {
  10908. this.left.deoptimizeAssignment(destructuredInitPath, init);
  10909. }
  10910. deoptimizePath(path) {
  10911. if (path.length === 0) {
  10912. this.left.deoptimizePath(path);
  10913. }
  10914. }
  10915. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10916. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  10917. }
  10918. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10919. return this.left.hasEffectsWhenDestructuring(context, destructuredInitPath, init);
  10920. }
  10921. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  10922. let included = this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init) ||
  10923. this.included;
  10924. if ((included ||= this.right.shouldBeIncluded(context))) {
  10925. this.right.include(context, false);
  10926. if (!this.left.included) {
  10927. this.left.includeNode(context);
  10928. // Unfortunately, we need to include the left side again now, so that
  10929. // any declared variables are properly included.
  10930. this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  10931. }
  10932. }
  10933. if (!this.included && included) {
  10934. this.includeNode(context);
  10935. }
  10936. return this.included;
  10937. }
  10938. includeNode(context) {
  10939. this.included = true;
  10940. if (!this.deoptimized)
  10941. this.applyDeoptimizations();
  10942. this.right.includePath(UNKNOWN_PATH, context);
  10943. }
  10944. markDeclarationReached() {
  10945. this.left.markDeclarationReached();
  10946. }
  10947. render(code, options, { isShorthandProperty } = BLANK) {
  10948. this.left.render(code, options, { isShorthandProperty });
  10949. this.right.render(code, options);
  10950. }
  10951. applyDeoptimizations() {
  10952. this.deoptimized = true;
  10953. this.left.deoptimizePath(EMPTY_PATH);
  10954. this.right.deoptimizePath(UNKNOWN_PATH);
  10955. this.scope.context.requestTreeshakingPass();
  10956. }
  10957. }
  10958. class AwaitExpression extends NodeBase {
  10959. hasEffects() {
  10960. if (!this.deoptimized)
  10961. this.applyDeoptimizations();
  10962. return true;
  10963. }
  10964. initialise() {
  10965. super.initialise();
  10966. let parent = this.parent;
  10967. do {
  10968. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  10969. return;
  10970. } while ((parent = parent.parent));
  10971. this.scope.context.usesTopLevelAwait = true;
  10972. }
  10973. include(context, includeChildrenRecursively) {
  10974. if (!this.included)
  10975. this.includeNode(context);
  10976. this.argument.include(context, includeChildrenRecursively);
  10977. }
  10978. includeNode(context) {
  10979. this.included = true;
  10980. if (!this.deoptimized)
  10981. this.applyDeoptimizations();
  10982. // Thenables need to be included
  10983. this.argument.includePath(THEN_PATH, context);
  10984. }
  10985. includePath(path, context) {
  10986. if (!this.deoptimized)
  10987. this.applyDeoptimizations();
  10988. if (!this.included)
  10989. this.includeNode(context);
  10990. this.argument.includePath(path, context);
  10991. }
  10992. }
  10993. const THEN_PATH = ['then'];
  10994. function getRenderedLiteralValue(value) {
  10995. if (value === undefined) {
  10996. return 'void 0';
  10997. }
  10998. if (typeof value === 'boolean') {
  10999. return String(value);
  11000. }
  11001. if (typeof value === 'string') {
  11002. return JSON.stringify(value);
  11003. }
  11004. if (typeof value === 'number') {
  11005. return getSimplifiedNumber(value);
  11006. }
  11007. return UnknownValue;
  11008. }
  11009. function getSimplifiedNumber(value) {
  11010. if (Object.is(-0, value)) {
  11011. return '-0';
  11012. }
  11013. const exp = value.toExponential();
  11014. const [base, exponent] = exp.split('e');
  11015. const floatLength = base.split('.')[1]?.length || 0;
  11016. const finalizedExp = `${base.replace('.', '')}e${parseInt(exponent) - floatLength}`;
  11017. const stringifiedValue = String(value).replace('+', '');
  11018. return finalizedExp.length < stringifiedValue.length ? finalizedExp : stringifiedValue;
  11019. }
  11020. const binaryOperators = {
  11021. '!=': (left, right) => left != right,
  11022. '!==': (left, right) => left !== right,
  11023. '%': (left, right) => left % right,
  11024. '&': (left, right) => left & right,
  11025. '*': (left, right) => left * right,
  11026. // At the moment, "**" will be transpiled to Math.pow
  11027. '**': (left, right) => left ** right,
  11028. '+': (left, right) => left + right,
  11029. '-': (left, right) => left - right,
  11030. '/': (left, right) => left / right,
  11031. '<': (left, right) => left < right,
  11032. '<<': (left, right) => left << right,
  11033. '<=': (left, right) => left <= right,
  11034. '==': (left, right) => left == right,
  11035. '===': (left, right) => left === right,
  11036. '>': (left, right) => left > right,
  11037. '>=': (left, right) => left >= right,
  11038. '>>': (left, right) => left >> right,
  11039. '>>>': (left, right) => left >>> right,
  11040. '^': (left, right) => left ^ right,
  11041. '|': (left, right) => left | right
  11042. // We use the fallback for cases where we return something unknown
  11043. // in: () => UnknownValue,
  11044. // instanceof: () => UnknownValue,
  11045. };
  11046. const UNASSIGNED$1 = Symbol('Unassigned');
  11047. class BinaryExpression extends NodeBase {
  11048. constructor() {
  11049. super(...arguments);
  11050. this.renderedLiteralValue = UNASSIGNED$1;
  11051. }
  11052. deoptimizeCache() {
  11053. this.renderedLiteralValue = UnknownValue;
  11054. }
  11055. getLiteralValueAtPath(path, recursionTracker, origin) {
  11056. if (path.length > 0)
  11057. return UnknownValue;
  11058. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  11059. if (typeof leftValue === 'symbol')
  11060. return UnknownValue;
  11061. // Optimize `'export' in namespace`
  11062. if (this.operator === 'in' && this.right.variable instanceof NamespaceVariable) {
  11063. const [variable] = this.right.variable.context.traceExport(String(leftValue));
  11064. if (variable instanceof ExternalVariable)
  11065. return UnknownValue;
  11066. if (variable instanceof SyntheticNamedExportVariable)
  11067. return UnknownValue;
  11068. return !!variable;
  11069. }
  11070. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  11071. if (typeof rightValue === 'symbol')
  11072. return UnknownValue;
  11073. const operatorFunction = binaryOperators[this.operator];
  11074. if (!operatorFunction)
  11075. return UnknownValue;
  11076. return operatorFunction(leftValue, rightValue);
  11077. }
  11078. getRenderedLiteralValue() {
  11079. // Only optimize `'export' in ns`
  11080. if (this.operator !== 'in' || !(this.right.variable instanceof NamespaceVariable)) {
  11081. return UnknownValue;
  11082. }
  11083. if (this.renderedLiteralValue !== UNASSIGNED$1)
  11084. return this.renderedLiteralValue;
  11085. return (this.renderedLiteralValue = getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  11086. }
  11087. hasEffects(context) {
  11088. // support some implicit type coercion runtime errors
  11089. if (this.operator === '+' &&
  11090. this.parent instanceof ExpressionStatement &&
  11091. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  11092. return true;
  11093. }
  11094. return super.hasEffects(context);
  11095. }
  11096. hasEffectsOnInteractionAtPath(path, { type }) {
  11097. return type !== INTERACTION_ACCESSED || path.length > 1;
  11098. }
  11099. include(context, includeChildrenRecursively, options) {
  11100. if (!this.included)
  11101. this.includeNode(context);
  11102. if (typeof this.getRenderedLiteralValue() === 'symbol') {
  11103. this.left.include(context, includeChildrenRecursively, options);
  11104. this.right.include(context, includeChildrenRecursively, options);
  11105. }
  11106. }
  11107. includeNode(context) {
  11108. this.included = true;
  11109. if (this.operator === 'in' && typeof this.getRenderedLiteralValue() === 'symbol') {
  11110. this.right.includePath(UNKNOWN_PATH, context);
  11111. }
  11112. }
  11113. removeAnnotations(code) {
  11114. this.left.removeAnnotations(code);
  11115. }
  11116. render(code, options, { renderedSurroundingElement } = BLANK) {
  11117. const renderedLiteralValue = this.getRenderedLiteralValue();
  11118. if (typeof renderedLiteralValue !== 'symbol') {
  11119. code.overwrite(this.start, this.end, renderedLiteralValue);
  11120. }
  11121. else {
  11122. this.left.render(code, options, { renderedSurroundingElement });
  11123. this.right.render(code, options);
  11124. }
  11125. }
  11126. }
  11127. BinaryExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  11128. class BreakStatement extends NodeBase {
  11129. hasEffects(context) {
  11130. if (this.label) {
  11131. if (!context.ignore.labels.has(this.label.name))
  11132. return true;
  11133. context.includedLabels.add(this.label.name);
  11134. }
  11135. else {
  11136. if (!context.ignore.breaks)
  11137. return true;
  11138. context.hasBreak = true;
  11139. }
  11140. context.brokenFlow = true;
  11141. return false;
  11142. }
  11143. include(context, includeChildrenRecursively) {
  11144. this.included = true;
  11145. if (this.label) {
  11146. this.label.include(context, includeChildrenRecursively);
  11147. context.includedLabels.add(this.label.name);
  11148. }
  11149. else {
  11150. context.hasBreak = true;
  11151. }
  11152. context.brokenFlow = true;
  11153. }
  11154. }
  11155. BreakStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11156. BreakStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11157. function renderCallArguments(code, options, node) {
  11158. if (node.arguments.length > 0) {
  11159. if (node.arguments[node.arguments.length - 1].included) {
  11160. for (const argument of node.arguments) {
  11161. argument.render(code, options);
  11162. }
  11163. }
  11164. else {
  11165. let lastIncludedIndex = node.arguments.length - 2;
  11166. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  11167. lastIncludedIndex--;
  11168. }
  11169. if (lastIncludedIndex >= 0) {
  11170. for (let index = 0; index <= lastIncludedIndex; index++) {
  11171. node.arguments[index].render(code, options);
  11172. }
  11173. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  11174. }
  11175. else {
  11176. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  11177. }
  11178. }
  11179. }
  11180. }
  11181. class CallExpressionBase extends NodeBase {
  11182. constructor() {
  11183. super(...arguments);
  11184. this.returnExpression = null;
  11185. this.deoptimizableDependentExpressions = [];
  11186. this.expressionsToBeDeoptimized = new Set();
  11187. }
  11188. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11189. const { args } = interaction;
  11190. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  11191. if (isPure)
  11192. return;
  11193. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  11194. if (deoptimizedExpressions.length === 0)
  11195. return;
  11196. if (returnExpression === UNKNOWN_EXPRESSION) {
  11197. for (const expression of deoptimizedExpressions) {
  11198. expression.deoptimizePath(UNKNOWN_PATH);
  11199. }
  11200. }
  11201. else {
  11202. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11203. for (const expression of deoptimizedExpressions) {
  11204. this.expressionsToBeDeoptimized.add(expression);
  11205. }
  11206. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11207. }, null);
  11208. }
  11209. }
  11210. deoptimizeCache() {
  11211. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  11212. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11213. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  11214. this.expressionsToBeDeoptimized = EMPTY_SET;
  11215. this.deoptimizableDependentExpressions = EMPTY_ARRAY;
  11216. for (const expression of deoptimizableDependentExpressions) {
  11217. expression.deoptimizeCache();
  11218. }
  11219. for (const expression of expressionsToBeDeoptimized) {
  11220. expression.deoptimizePath(UNKNOWN_PATH);
  11221. }
  11222. }
  11223. }
  11224. deoptimizePath(path) {
  11225. if (path.length === 0 ||
  11226. this.scope.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  11227. return;
  11228. }
  11229. const [returnExpression] = this.getReturnExpression();
  11230. if (returnExpression !== UNKNOWN_EXPRESSION) {
  11231. returnExpression.deoptimizePath(path);
  11232. }
  11233. }
  11234. getLiteralValueAtPath(path, recursionTracker, origin) {
  11235. const [returnExpression] = this.getReturnExpression(recursionTracker);
  11236. if (returnExpression === UNKNOWN_EXPRESSION) {
  11237. return UnknownValue;
  11238. }
  11239. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11240. this.deoptimizableDependentExpressions.push(origin);
  11241. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  11242. }, UnknownValue);
  11243. }
  11244. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11245. const returnExpression = this.getReturnExpression(recursionTracker);
  11246. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  11247. return returnExpression;
  11248. }
  11249. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11250. this.deoptimizableDependentExpressions.push(origin);
  11251. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11252. return [expression, isPure || returnExpression[1]];
  11253. }, UNKNOWN_RETURN_EXPRESSION);
  11254. }
  11255. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11256. const { type } = interaction;
  11257. if (type === INTERACTION_CALLED) {
  11258. const { args, withNew } = interaction;
  11259. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  11260. return false;
  11261. }
  11262. }
  11263. else if ((type === INTERACTION_ASSIGNED
  11264. ? context.assigned
  11265. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  11266. return false;
  11267. }
  11268. const [returnExpression, isPure] = this.getReturnExpression();
  11269. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  11270. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  11271. }
  11272. }
  11273. class CallExpression extends CallExpressionBase {
  11274. get hasCheckedForWarnings() {
  11275. return isFlagSet(this.flags, 134217728 /* Flag.checkedForWarnings */);
  11276. }
  11277. set hasCheckedForWarnings(value) {
  11278. this.flags = setFlag(this.flags, 134217728 /* Flag.checkedForWarnings */, value);
  11279. }
  11280. get optional() {
  11281. return isFlagSet(this.flags, 128 /* Flag.optional */);
  11282. }
  11283. set optional(value) {
  11284. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  11285. }
  11286. bind() {
  11287. super.bind();
  11288. this.interaction = {
  11289. args: [
  11290. this.callee instanceof MemberExpression && !this.callee.variable
  11291. ? this.callee.object
  11292. : null,
  11293. ...this.arguments
  11294. ],
  11295. type: INTERACTION_CALLED,
  11296. withNew: false
  11297. };
  11298. }
  11299. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  11300. return getChainElementLiteralValueAtPath(this, this.callee, path, recursionTracker, origin);
  11301. }
  11302. hasEffects(context) {
  11303. if (!this.deoptimized)
  11304. this.applyDeoptimizations();
  11305. for (const argument of this.arguments) {
  11306. if (argument.hasEffects(context))
  11307. return true;
  11308. }
  11309. if (this.annotationPure) {
  11310. return false;
  11311. }
  11312. return (this.callee.hasEffects(context) ||
  11313. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  11314. }
  11315. hasEffectsAsChainElement(context) {
  11316. const calleeHasEffects = 'hasEffectsAsChainElement' in this.callee
  11317. ? this.callee.hasEffectsAsChainElement(context)
  11318. : this.callee.hasEffects(context);
  11319. if (calleeHasEffects === IS_SKIPPED_CHAIN)
  11320. return IS_SKIPPED_CHAIN;
  11321. if (this.optional &&
  11322. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  11323. return (!this.annotationPure && calleeHasEffects) || IS_SKIPPED_CHAIN;
  11324. }
  11325. // We only apply deoptimizations lazily once we know we are not skipping
  11326. if (!this.deoptimized)
  11327. this.applyDeoptimizations();
  11328. for (const argument of this.arguments) {
  11329. if (argument.hasEffects(context))
  11330. return true;
  11331. }
  11332. return (!this.annotationPure &&
  11333. (calleeHasEffects ||
  11334. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)));
  11335. }
  11336. include(context, includeChildrenRecursively) {
  11337. if (!this.included)
  11338. this.includeNode(context);
  11339. if (includeChildrenRecursively) {
  11340. super.include(context, true);
  11341. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  11342. this.callee instanceof Identifier &&
  11343. this.callee.variable) {
  11344. this.callee.variable.markCalledFromTryStatement();
  11345. }
  11346. }
  11347. else {
  11348. this.callee.include(context, false);
  11349. this.callee.includeCallArguments(this.interaction, context);
  11350. }
  11351. }
  11352. includeNode(context) {
  11353. this.included = true;
  11354. if (!this.deoptimized)
  11355. this.applyDeoptimizations();
  11356. this.callee.includePath(UNKNOWN_PATH, context);
  11357. }
  11358. initialise() {
  11359. super.initialise();
  11360. if (this.annotations &&
  11361. this.scope.context.options.treeshake.annotations) {
  11362. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  11363. }
  11364. }
  11365. render(code, options, { renderedSurroundingElement } = BLANK) {
  11366. this.callee.render(code, options, {
  11367. isCalleeOfRenderedParent: true,
  11368. renderedSurroundingElement
  11369. });
  11370. renderCallArguments(code, options, this);
  11371. if (this.callee instanceof Identifier && !this.hasCheckedForWarnings) {
  11372. this.hasCheckedForWarnings = true;
  11373. const variable = this.scope.findVariable(this.callee.name);
  11374. if (variable.isNamespace) {
  11375. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(this.callee.name), this.start);
  11376. }
  11377. if (this.callee.name === 'eval') {
  11378. this.scope.context.log(LOGLEVEL_WARN, logEval(this.scope.context.module.id), this.start);
  11379. }
  11380. }
  11381. }
  11382. applyDeoptimizations() {
  11383. this.deoptimized = true;
  11384. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  11385. this.scope.context.requestTreeshakingPass();
  11386. }
  11387. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  11388. if (this.returnExpression === null) {
  11389. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11390. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  11391. }
  11392. return this.returnExpression;
  11393. }
  11394. }
  11395. class CatchClause extends NodeBase {
  11396. createScope(parentScope) {
  11397. this.scope = new ParameterScope(parentScope, true);
  11398. }
  11399. parseNode(esTreeNode) {
  11400. const { body, param, type } = esTreeNode;
  11401. this.type = type;
  11402. if (param) {
  11403. this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
  11404. this.param.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  11405. }
  11406. this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
  11407. return super.parseNode(esTreeNode);
  11408. }
  11409. }
  11410. CatchClause.prototype.preventChildBlockScope = true;
  11411. CatchClause.prototype.includeNode = onlyIncludeSelf;
  11412. class ChainExpression extends NodeBase {
  11413. // deoptimizations are not relevant as we are not caching values
  11414. deoptimizeCache() { }
  11415. getLiteralValueAtPath(path, recursionTracker, origin) {
  11416. const literalValue = this.expression.getLiteralValueAtPathAsChainElement(path, recursionTracker, origin);
  11417. return literalValue === IS_SKIPPED_CHAIN ? undefined : literalValue;
  11418. }
  11419. hasEffects(context) {
  11420. return this.expression.hasEffectsAsChainElement(context) === true;
  11421. }
  11422. includePath(path, context) {
  11423. this.included = true;
  11424. this.expression.includePath(path, context);
  11425. }
  11426. removeAnnotations(code) {
  11427. this.expression.removeAnnotations(code);
  11428. }
  11429. }
  11430. ChainExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11431. ChainExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  11432. class ClassBodyScope extends ChildScope {
  11433. constructor(parent, classNode) {
  11434. const { context } = parent;
  11435. super(parent, context);
  11436. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, EMPTY_PATH, context, 'other')));
  11437. this.instanceScope = new ChildScope(this, context);
  11438. this.instanceScope.variables.set('this', new ThisVariable(context));
  11439. }
  11440. findLexicalBoundary() {
  11441. return this;
  11442. }
  11443. }
  11444. class ClassBody extends NodeBase {
  11445. createScope(parentScope) {
  11446. this.scope = new ClassBodyScope(parentScope, this.parent);
  11447. }
  11448. include(context, includeChildrenRecursively) {
  11449. this.included = true;
  11450. this.scope.context.includeVariableInModule(this.scope.thisVariable, UNKNOWN_PATH, context);
  11451. for (const definition of this.body) {
  11452. definition.include(context, includeChildrenRecursively);
  11453. }
  11454. }
  11455. parseNode(esTreeNode) {
  11456. const body = (this.body = new Array(esTreeNode.body.length));
  11457. let index = 0;
  11458. for (const definition of esTreeNode.body) {
  11459. body[index++] = new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition);
  11460. }
  11461. return super.parseNode(esTreeNode);
  11462. }
  11463. }
  11464. ClassBody.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11465. ClassBody.prototype.applyDeoptimizations = doNotDeoptimize;
  11466. class ClassExpression extends ClassNode {
  11467. render(code, options, { renderedSurroundingElement } = BLANK) {
  11468. super.render(code, options);
  11469. if (renderedSurroundingElement === ExpressionStatement$1) {
  11470. code.appendRight(this.start, '(');
  11471. code.prependLeft(this.end, ')');
  11472. }
  11473. }
  11474. }
  11475. function tryCastLiteralValueToBoolean(literalValue) {
  11476. if (typeof literalValue === 'symbol') {
  11477. if (literalValue === UnknownFalsyValue) {
  11478. return false;
  11479. }
  11480. if (literalValue === UnknownTruthyValue) {
  11481. return true;
  11482. }
  11483. return UnknownValue;
  11484. }
  11485. return !!literalValue;
  11486. }
  11487. class MultiExpression extends ExpressionEntity {
  11488. constructor(expressions) {
  11489. super();
  11490. this.expressions = expressions;
  11491. }
  11492. deoptimizePath(path) {
  11493. for (const expression of this.expressions) {
  11494. expression.deoptimizePath(path);
  11495. }
  11496. }
  11497. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11498. return [
  11499. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  11500. false
  11501. ];
  11502. }
  11503. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11504. for (const expression of this.expressions) {
  11505. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  11506. return true;
  11507. }
  11508. return false;
  11509. }
  11510. }
  11511. class ConditionalExpression extends NodeBase {
  11512. constructor() {
  11513. super(...arguments);
  11514. this.expressionsToBeDeoptimized = [];
  11515. this.usedBranch = null;
  11516. }
  11517. get isBranchResolutionAnalysed() {
  11518. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  11519. }
  11520. set isBranchResolutionAnalysed(value) {
  11521. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  11522. }
  11523. get hasDeoptimizedCache() {
  11524. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  11525. }
  11526. set hasDeoptimizedCache(value) {
  11527. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  11528. }
  11529. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11530. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11531. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11532. }
  11533. deoptimizeCache() {
  11534. if (this.hasDeoptimizedCache)
  11535. return;
  11536. this.hasDeoptimizedCache = true;
  11537. if (this.usedBranch !== null) {
  11538. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  11539. this.usedBranch = null;
  11540. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  11541. if (this.included) {
  11542. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  11543. }
  11544. const { expressionsToBeDeoptimized } = this;
  11545. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  11546. for (const expression of expressionsToBeDeoptimized) {
  11547. expression.deoptimizeCache();
  11548. }
  11549. }
  11550. }
  11551. deoptimizePath(path) {
  11552. const usedBranch = this.getUsedBranch();
  11553. if (usedBranch) {
  11554. usedBranch.deoptimizePath(path);
  11555. }
  11556. else {
  11557. this.consequent.deoptimizePath(path);
  11558. this.alternate.deoptimizePath(path);
  11559. }
  11560. }
  11561. getLiteralValueAtPath(path, recursionTracker, origin) {
  11562. const usedBranch = this.getUsedBranch();
  11563. if (!usedBranch) {
  11564. if (this.hasDeoptimizedCache) {
  11565. return UnknownValue;
  11566. }
  11567. const consequentValue = this.consequent.getLiteralValueAtPath(path, recursionTracker, origin);
  11568. const castedConsequentValue = tryCastLiteralValueToBoolean(consequentValue);
  11569. if (castedConsequentValue === UnknownValue)
  11570. return UnknownValue;
  11571. const alternateValue = this.alternate.getLiteralValueAtPath(path, recursionTracker, origin);
  11572. const castedAlternateValue = tryCastLiteralValueToBoolean(alternateValue);
  11573. if (castedConsequentValue !== castedAlternateValue)
  11574. return UnknownValue;
  11575. this.expressionsToBeDeoptimized.push(origin);
  11576. if (consequentValue !== alternateValue)
  11577. return castedConsequentValue ? UnknownTruthyValue : UnknownFalsyValue;
  11578. return consequentValue;
  11579. }
  11580. this.expressionsToBeDeoptimized.push(origin);
  11581. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  11582. }
  11583. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11584. const usedBranch = this.getUsedBranch();
  11585. if (!usedBranch)
  11586. return [
  11587. new MultiExpression([
  11588. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  11589. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  11590. ]),
  11591. false
  11592. ];
  11593. this.expressionsToBeDeoptimized.push(origin);
  11594. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11595. }
  11596. hasEffects(context) {
  11597. if (this.test.hasEffects(context))
  11598. return true;
  11599. const usedBranch = this.getUsedBranch();
  11600. if (!usedBranch) {
  11601. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  11602. }
  11603. return usedBranch.hasEffects(context);
  11604. }
  11605. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11606. const usedBranch = this.getUsedBranch();
  11607. if (!usedBranch) {
  11608. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  11609. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  11610. }
  11611. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  11612. }
  11613. include(context, includeChildrenRecursively) {
  11614. this.included = true;
  11615. const usedBranch = this.getUsedBranch();
  11616. if (usedBranch === null || includeChildrenRecursively || this.test.shouldBeIncluded(context)) {
  11617. this.test.include(context, includeChildrenRecursively);
  11618. this.consequent.include(context, includeChildrenRecursively);
  11619. this.alternate.include(context, includeChildrenRecursively);
  11620. }
  11621. else {
  11622. usedBranch.include(context, includeChildrenRecursively);
  11623. }
  11624. }
  11625. includePath(path, context) {
  11626. this.included = true;
  11627. const usedBranch = this.getUsedBranch();
  11628. if (usedBranch === null || this.test.shouldBeIncluded(context)) {
  11629. this.consequent.includePath(path, context);
  11630. this.alternate.includePath(path, context);
  11631. }
  11632. else {
  11633. usedBranch.includePath(path, context);
  11634. }
  11635. }
  11636. includeCallArguments(interaction, context) {
  11637. const usedBranch = this.getUsedBranch();
  11638. if (usedBranch) {
  11639. usedBranch.includeCallArguments(interaction, context);
  11640. }
  11641. else {
  11642. this.consequent.includeCallArguments(interaction, context);
  11643. this.alternate.includeCallArguments(interaction, context);
  11644. }
  11645. }
  11646. removeAnnotations(code) {
  11647. this.test.removeAnnotations(code);
  11648. }
  11649. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  11650. if (this.test.included) {
  11651. this.test.render(code, options, { renderedSurroundingElement });
  11652. this.consequent.render(code, options);
  11653. this.alternate.render(code, options);
  11654. }
  11655. else {
  11656. const usedBranch = this.getUsedBranch();
  11657. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  11658. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  11659. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  11660. : colonPos) + 1);
  11661. if (preventASI) {
  11662. removeLineBreaks(code, inclusionStart, usedBranch.start);
  11663. }
  11664. code.remove(this.start, inclusionStart);
  11665. if (this.consequent.included) {
  11666. code.remove(colonPos, this.end);
  11667. }
  11668. this.test.removeAnnotations(code);
  11669. usedBranch.render(code, options, {
  11670. isCalleeOfRenderedParent,
  11671. preventASI: true,
  11672. renderedParentType: renderedParentType || this.parent.type,
  11673. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  11674. });
  11675. }
  11676. }
  11677. getUsedBranch() {
  11678. if (this.isBranchResolutionAnalysed) {
  11679. return this.usedBranch;
  11680. }
  11681. this.isBranchResolutionAnalysed = true;
  11682. const testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  11683. return typeof testValue === 'symbol'
  11684. ? null
  11685. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  11686. }
  11687. }
  11688. ConditionalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11689. ConditionalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  11690. class ContinueStatement extends NodeBase {
  11691. hasEffects(context) {
  11692. if (this.label) {
  11693. if (!context.ignore.labels.has(this.label.name))
  11694. return true;
  11695. context.includedLabels.add(this.label.name);
  11696. }
  11697. else {
  11698. if (!context.ignore.continues)
  11699. return true;
  11700. context.hasContinue = true;
  11701. }
  11702. context.brokenFlow = true;
  11703. return false;
  11704. }
  11705. include(context, includeChildrenRecursively) {
  11706. this.included = true;
  11707. if (this.label) {
  11708. this.label.include(context, includeChildrenRecursively);
  11709. context.includedLabels.add(this.label.name);
  11710. }
  11711. else {
  11712. context.hasContinue = true;
  11713. }
  11714. context.brokenFlow = true;
  11715. }
  11716. }
  11717. ContinueStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11718. ContinueStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11719. class DebuggerStatement extends NodeBase {
  11720. hasEffects() {
  11721. return true;
  11722. }
  11723. }
  11724. DebuggerStatement.prototype.includeNode = onlyIncludeSelf;
  11725. class Decorator extends NodeBase {
  11726. hasEffects(context) {
  11727. return (this.expression.hasEffects(context) ||
  11728. this.expression.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context));
  11729. }
  11730. }
  11731. Decorator.prototype.includeNode = onlyIncludeSelf;
  11732. function hasLoopBodyEffects(context, body) {
  11733. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  11734. const { breaks, continues } = ignore;
  11735. ignore.breaks = true;
  11736. ignore.continues = true;
  11737. context.hasBreak = false;
  11738. context.hasContinue = false;
  11739. if (body.hasEffects(context))
  11740. return true;
  11741. ignore.breaks = breaks;
  11742. ignore.continues = continues;
  11743. context.hasBreak = hasBreak;
  11744. context.hasContinue = hasContinue;
  11745. context.brokenFlow = brokenFlow;
  11746. return false;
  11747. }
  11748. function includeLoopBody(context, body, includeChildrenRecursively) {
  11749. const { brokenFlow, hasBreak, hasContinue } = context;
  11750. context.hasBreak = false;
  11751. context.hasContinue = false;
  11752. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11753. context.hasBreak = hasBreak;
  11754. context.hasContinue = hasContinue;
  11755. context.brokenFlow = brokenFlow;
  11756. }
  11757. class DoWhileStatement extends NodeBase {
  11758. hasEffects(context) {
  11759. if (this.test.hasEffects(context))
  11760. return true;
  11761. return hasLoopBodyEffects(context, this.body);
  11762. }
  11763. include(context, includeChildrenRecursively) {
  11764. this.included = true;
  11765. this.test.include(context, includeChildrenRecursively);
  11766. includeLoopBody(context, this.body, includeChildrenRecursively);
  11767. }
  11768. }
  11769. DoWhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11770. DoWhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11771. class EmptyStatement extends NodeBase {
  11772. hasEffects() {
  11773. return false;
  11774. }
  11775. }
  11776. EmptyStatement.prototype.includeNode = onlyIncludeSelf;
  11777. class ExportAllDeclaration extends NodeBase {
  11778. hasEffects() {
  11779. return false;
  11780. }
  11781. initialise() {
  11782. super.initialise();
  11783. this.scope.context.addExport(this);
  11784. }
  11785. render(code, _options, nodeRenderOptions) {
  11786. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  11787. }
  11788. }
  11789. ExportAllDeclaration.prototype.needsBoundaries = true;
  11790. ExportAllDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11791. ExportAllDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  11792. class ExportNamedDeclaration extends NodeBase {
  11793. bind() {
  11794. // Do not bind specifiers
  11795. this.declaration?.bind();
  11796. }
  11797. hasEffects(context) {
  11798. return !!this.declaration?.hasEffects(context);
  11799. }
  11800. initialise() {
  11801. super.initialise();
  11802. this.scope.context.addExport(this);
  11803. }
  11804. removeAnnotations(code) {
  11805. this.declaration?.removeAnnotations(code);
  11806. }
  11807. render(code, options, nodeRenderOptions) {
  11808. const { start, end } = nodeRenderOptions;
  11809. if (this.declaration === null) {
  11810. code.remove(start, end);
  11811. }
  11812. else {
  11813. let endBoundary = this.declaration.start;
  11814. // the start of the decorator may be before the start of the class declaration
  11815. if (this.declaration instanceof ClassDeclaration) {
  11816. const decorators = this.declaration.decorators;
  11817. for (const decorator of decorators) {
  11818. endBoundary = Math.min(endBoundary, decorator.start);
  11819. }
  11820. if (endBoundary <= this.start) {
  11821. endBoundary = this.declaration.start;
  11822. }
  11823. }
  11824. code.remove(this.start, endBoundary);
  11825. this.declaration.render(code, options, { end, start });
  11826. }
  11827. }
  11828. }
  11829. ExportNamedDeclaration.prototype.needsBoundaries = true;
  11830. ExportNamedDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11831. ExportNamedDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  11832. class ExportSpecifier extends NodeBase {
  11833. }
  11834. ExportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11835. ExportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  11836. class ForInStatement extends NodeBase {
  11837. createScope(parentScope) {
  11838. this.scope = new BlockScope(parentScope);
  11839. }
  11840. hasEffects(context) {
  11841. const { body, deoptimized, left, right } = this;
  11842. if (!deoptimized)
  11843. this.applyDeoptimizations();
  11844. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  11845. return true;
  11846. return hasLoopBodyEffects(context, body);
  11847. }
  11848. include(context, includeChildrenRecursively) {
  11849. const { body, deoptimized, left, right } = this;
  11850. if (!deoptimized)
  11851. this.applyDeoptimizations();
  11852. if (!this.included)
  11853. this.includeNode(context);
  11854. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  11855. right.include(context, includeChildrenRecursively);
  11856. includeLoopBody(context, body, includeChildrenRecursively);
  11857. }
  11858. includeNode(context) {
  11859. this.included = true;
  11860. if (!this.deoptimized)
  11861. this.applyDeoptimizations();
  11862. this.right.includePath(UNKNOWN_PATH, context);
  11863. }
  11864. initialise() {
  11865. super.initialise();
  11866. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  11867. }
  11868. render(code, options) {
  11869. this.left.render(code, options, NO_SEMICOLON);
  11870. this.right.render(code, options, NO_SEMICOLON);
  11871. // handle no space between "in" and the right side
  11872. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  11873. code.prependLeft(this.right.start, ' ');
  11874. }
  11875. this.body.render(code, options);
  11876. }
  11877. applyDeoptimizations() {
  11878. this.deoptimized = true;
  11879. this.left.deoptimizePath(EMPTY_PATH);
  11880. this.scope.context.requestTreeshakingPass();
  11881. }
  11882. }
  11883. class ForOfStatement extends NodeBase {
  11884. get await() {
  11885. return isFlagSet(this.flags, 131072 /* Flag.await */);
  11886. }
  11887. set await(value) {
  11888. this.flags = setFlag(this.flags, 131072 /* Flag.await */, value);
  11889. }
  11890. createScope(parentScope) {
  11891. this.scope = new BlockScope(parentScope);
  11892. }
  11893. hasEffects() {
  11894. if (!this.deoptimized)
  11895. this.applyDeoptimizations();
  11896. // Placeholder until proper Symbol.Iterator support
  11897. return true;
  11898. }
  11899. include(context, includeChildrenRecursively) {
  11900. const { body, deoptimized, left, right } = this;
  11901. if (!deoptimized)
  11902. this.applyDeoptimizations();
  11903. if (!this.included)
  11904. this.includeNode(context);
  11905. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  11906. right.include(context, includeChildrenRecursively);
  11907. includeLoopBody(context, body, includeChildrenRecursively);
  11908. }
  11909. includeNode(context) {
  11910. this.included = true;
  11911. if (!this.deoptimized)
  11912. this.applyDeoptimizations();
  11913. this.right.includePath(UNKNOWN_PATH, context);
  11914. }
  11915. initialise() {
  11916. super.initialise();
  11917. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  11918. }
  11919. render(code, options) {
  11920. this.left.render(code, options, NO_SEMICOLON);
  11921. this.right.render(code, options, NO_SEMICOLON);
  11922. // handle no space between "of" and the right side
  11923. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  11924. code.prependLeft(this.right.start, ' ');
  11925. }
  11926. this.body.render(code, options);
  11927. }
  11928. applyDeoptimizations() {
  11929. this.deoptimized = true;
  11930. this.left.deoptimizePath(EMPTY_PATH);
  11931. this.right.deoptimizePath(UNKNOWN_PATH);
  11932. this.scope.context.requestTreeshakingPass();
  11933. }
  11934. }
  11935. class ForStatement extends NodeBase {
  11936. createScope(parentScope) {
  11937. this.scope = new BlockScope(parentScope);
  11938. }
  11939. hasEffects(context) {
  11940. if (this.init?.hasEffects(context) ||
  11941. this.test?.hasEffects(context) ||
  11942. this.update?.hasEffects(context)) {
  11943. return true;
  11944. }
  11945. return hasLoopBodyEffects(context, this.body);
  11946. }
  11947. include(context, includeChildrenRecursively) {
  11948. this.included = true;
  11949. this.init?.include(context, includeChildrenRecursively, {
  11950. asSingleStatement: true
  11951. });
  11952. this.test?.include(context, includeChildrenRecursively);
  11953. this.update?.include(context, includeChildrenRecursively);
  11954. includeLoopBody(context, this.body, includeChildrenRecursively);
  11955. }
  11956. render(code, options) {
  11957. this.init?.render(code, options, NO_SEMICOLON);
  11958. this.test?.render(code, options, NO_SEMICOLON);
  11959. this.update?.render(code, options, NO_SEMICOLON);
  11960. this.body.render(code, options);
  11961. }
  11962. }
  11963. ForStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11964. ForStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11965. class FunctionExpression extends FunctionNode {
  11966. createScope(parentScope) {
  11967. super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
  11968. }
  11969. parseNode(esTreeNode) {
  11970. if (esTreeNode.id !== null) {
  11971. this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
  11972. }
  11973. return super.parseNode(esTreeNode);
  11974. }
  11975. onlyFunctionCallUsed() {
  11976. const isIIFE = this.parent.type === CallExpression$1 &&
  11977. this.parent.callee === this &&
  11978. (this.id === null || this.id.variable.getOnlyFunctionCallUsed());
  11979. return isIIFE || super.onlyFunctionCallUsed();
  11980. }
  11981. render(code, options, { renderedSurroundingElement } = BLANK) {
  11982. super.render(code, options);
  11983. if (renderedSurroundingElement === ExpressionStatement$1) {
  11984. code.appendRight(this.start, '(');
  11985. code.prependLeft(this.end, ')');
  11986. }
  11987. }
  11988. }
  11989. class TrackingScope extends BlockScope {
  11990. constructor() {
  11991. super(...arguments);
  11992. this.hoistedDeclarations = [];
  11993. }
  11994. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  11995. this.hoistedDeclarations.push(identifier);
  11996. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  11997. }
  11998. }
  11999. const unset = Symbol('unset');
  12000. class IfStatement extends NodeBase {
  12001. constructor() {
  12002. super(...arguments);
  12003. this.testValue = unset;
  12004. }
  12005. deoptimizeCache() {
  12006. this.testValue = UnknownValue;
  12007. }
  12008. hasEffects(context) {
  12009. if (this.test.hasEffects(context)) {
  12010. return true;
  12011. }
  12012. const testValue = this.getTestValue();
  12013. if (typeof testValue === 'symbol') {
  12014. const { brokenFlow } = context;
  12015. if (this.consequent.hasEffects(context))
  12016. return true;
  12017. const consequentBrokenFlow = context.brokenFlow;
  12018. context.brokenFlow = brokenFlow;
  12019. if (this.alternate === null)
  12020. return false;
  12021. if (this.alternate.hasEffects(context))
  12022. return true;
  12023. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  12024. return false;
  12025. }
  12026. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  12027. }
  12028. include(context, includeChildrenRecursively) {
  12029. this.included = true;
  12030. if (includeChildrenRecursively) {
  12031. this.includeRecursively(includeChildrenRecursively, context);
  12032. }
  12033. else {
  12034. const testValue = this.getTestValue();
  12035. if (typeof testValue === 'symbol') {
  12036. this.includeUnknownTest(context);
  12037. }
  12038. else {
  12039. this.includeKnownTest(context, testValue);
  12040. }
  12041. }
  12042. }
  12043. parseNode(esTreeNode) {
  12044. this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
  12045. if (esTreeNode.alternate) {
  12046. this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
  12047. }
  12048. return super.parseNode(esTreeNode);
  12049. }
  12050. render(code, options) {
  12051. const { snippets: { getPropertyAccess } } = options;
  12052. // Note that unknown test values are always included
  12053. const testValue = this.getTestValue();
  12054. const hoistedDeclarations = [];
  12055. const includesIfElse = this.test.included;
  12056. const noTreeshake = !this.scope.context.options.treeshake;
  12057. if (includesIfElse) {
  12058. this.test.render(code, options);
  12059. }
  12060. else {
  12061. code.remove(this.start, this.consequent.start);
  12062. }
  12063. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  12064. this.consequent.render(code, options);
  12065. }
  12066. else {
  12067. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  12068. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  12069. }
  12070. if (this.alternate) {
  12071. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  12072. if (includesIfElse) {
  12073. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  12074. code.prependLeft(this.alternate.start, ' ');
  12075. }
  12076. }
  12077. else {
  12078. code.remove(this.consequent.end, this.alternate.start);
  12079. }
  12080. this.alternate.render(code, options);
  12081. }
  12082. else {
  12083. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  12084. code.overwrite(this.alternate.start, this.end, ';');
  12085. }
  12086. else {
  12087. code.remove(this.consequent.end, this.end);
  12088. }
  12089. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  12090. }
  12091. }
  12092. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  12093. }
  12094. getTestValue() {
  12095. if (this.testValue === unset) {
  12096. return (this.testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  12097. }
  12098. return this.testValue;
  12099. }
  12100. includeKnownTest(context, testValue) {
  12101. if (this.test.shouldBeIncluded(context)) {
  12102. this.test.include(context, false);
  12103. }
  12104. if (testValue && this.consequent.shouldBeIncluded(context)) {
  12105. this.consequent.include(context, false, { asSingleStatement: true });
  12106. }
  12107. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  12108. this.alternate.include(context, false, { asSingleStatement: true });
  12109. }
  12110. }
  12111. includeRecursively(includeChildrenRecursively, context) {
  12112. this.test.include(context, includeChildrenRecursively);
  12113. this.consequent.include(context, includeChildrenRecursively);
  12114. this.alternate?.include(context, includeChildrenRecursively);
  12115. }
  12116. includeUnknownTest(context) {
  12117. this.test.include(context, false);
  12118. const { brokenFlow } = context;
  12119. let consequentBrokenFlow = false;
  12120. if (this.consequent.shouldBeIncluded(context)) {
  12121. this.consequent.include(context, false, { asSingleStatement: true });
  12122. consequentBrokenFlow = context.brokenFlow;
  12123. context.brokenFlow = brokenFlow;
  12124. }
  12125. if (this.alternate?.shouldBeIncluded(context)) {
  12126. this.alternate.include(context, false, { asSingleStatement: true });
  12127. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  12128. }
  12129. }
  12130. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  12131. const hoistedVariables = [
  12132. ...new Set(hoistedDeclarations.map(identifier => {
  12133. const variable = identifier.variable;
  12134. return variable.included ? variable.getName(getPropertyAccess) : '';
  12135. }))
  12136. ]
  12137. .filter(Boolean)
  12138. .join(', ');
  12139. if (hoistedVariables) {
  12140. const parentType = this.parent.type;
  12141. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  12142. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  12143. if (needsBraces) {
  12144. code.appendLeft(this.end, ` }`);
  12145. }
  12146. }
  12147. }
  12148. shouldKeepAlternateBranch() {
  12149. let currentParent = this.parent;
  12150. do {
  12151. if (currentParent instanceof IfStatement && currentParent.alternate) {
  12152. return true;
  12153. }
  12154. if (currentParent instanceof BlockStatement) {
  12155. return false;
  12156. }
  12157. currentParent = currentParent.parent;
  12158. } while (currentParent);
  12159. return false;
  12160. }
  12161. }
  12162. IfStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12163. IfStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  12164. class ImportAttribute extends NodeBase {
  12165. }
  12166. class ImportDeclaration extends NodeBase {
  12167. // Do not bind specifiers or attributes
  12168. bind() { }
  12169. hasEffects() {
  12170. return false;
  12171. }
  12172. initialise() {
  12173. super.initialise();
  12174. this.scope.context.addImport(this);
  12175. }
  12176. render(code, _options, nodeRenderOptions) {
  12177. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  12178. }
  12179. }
  12180. ImportDeclaration.prototype.needsBoundaries = true;
  12181. ImportDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12182. ImportDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  12183. class ImportDefaultSpecifier extends NodeBase {
  12184. }
  12185. ImportDefaultSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12186. ImportDefaultSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12187. function isReassignedExportsMember(variable, exportNamesByVariable) {
  12188. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  12189. }
  12190. class VariableDeclarator extends NodeBase {
  12191. declareDeclarator(kind, isUsingDeclaration) {
  12192. this.isUsingDeclaration = isUsingDeclaration;
  12193. this.id.declare(kind, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION);
  12194. }
  12195. deoptimizePath(path) {
  12196. this.id.deoptimizePath(path);
  12197. }
  12198. hasEffects(context) {
  12199. const initEffect = this.init?.hasEffects(context);
  12200. this.id.markDeclarationReached();
  12201. return (initEffect ||
  12202. this.isUsingDeclaration ||
  12203. this.id.hasEffects(context) ||
  12204. (this.scope.context.options.treeshake
  12205. .propertyReadSideEffects &&
  12206. this.id.hasEffectsWhenDestructuring(context, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION)));
  12207. }
  12208. include(context, includeChildrenRecursively) {
  12209. const { id, init } = this;
  12210. if (!this.included)
  12211. this.includeNode();
  12212. init?.include(context, includeChildrenRecursively);
  12213. id.markDeclarationReached();
  12214. if (includeChildrenRecursively) {
  12215. id.include(context, includeChildrenRecursively);
  12216. }
  12217. else {
  12218. id.includeDestructuredIfNecessary(context, EMPTY_PATH, init || UNDEFINED_EXPRESSION);
  12219. }
  12220. }
  12221. removeAnnotations(code) {
  12222. this.init?.removeAnnotations(code);
  12223. }
  12224. render(code, options) {
  12225. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  12226. const { end, id, init, start } = this;
  12227. const renderId = id.included || this.isUsingDeclaration;
  12228. if (renderId) {
  12229. id.render(code, options);
  12230. }
  12231. else {
  12232. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  12233. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  12234. }
  12235. if (init) {
  12236. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  12237. const renderedVariable = id.variable.getName(getPropertyAccess);
  12238. if (renderedVariable !== id.name) {
  12239. code.appendLeft(init.start + 5, ` ${id.name}`);
  12240. }
  12241. }
  12242. init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  12243. }
  12244. else if (id instanceof Identifier &&
  12245. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  12246. code.appendLeft(end, `${_}=${_}void 0`);
  12247. }
  12248. }
  12249. includeNode() {
  12250. this.included = true;
  12251. const { id, init } = this;
  12252. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  12253. const { name, variable } = id;
  12254. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  12255. if (accessedVariable !== variable) {
  12256. accessedVariable.forbidName(name);
  12257. }
  12258. }
  12259. }
  12260. }
  12261. }
  12262. VariableDeclarator.prototype.applyDeoptimizations = doNotDeoptimize;
  12263. function getChunkInfoWithPath(chunk) {
  12264. return { fileName: chunk.getFileName(), ...chunk.getPreRenderedChunkInfo() };
  12265. }
  12266. class ImportExpression extends NodeBase {
  12267. constructor() {
  12268. super(...arguments);
  12269. this.inlineNamespace = null;
  12270. this.hasUnknownAccessedKey = false;
  12271. this.accessedPropKey = new Set();
  12272. this.attributes = null;
  12273. this.mechanism = null;
  12274. this.namespaceExportName = undefined;
  12275. this.resolution = null;
  12276. this.resolutionString = null;
  12277. }
  12278. get shouldIncludeDynamicAttributes() {
  12279. return isFlagSet(this.flags, 268435456 /* Flag.shouldIncludeDynamicAttributes */);
  12280. }
  12281. set shouldIncludeDynamicAttributes(value) {
  12282. this.flags = setFlag(this.flags, 268435456 /* Flag.shouldIncludeDynamicAttributes */, value);
  12283. }
  12284. bind() {
  12285. this.source.bind();
  12286. this.options?.bind();
  12287. }
  12288. /**
  12289. * Get imported variables for deterministic usage, valid cases are:
  12290. *
  12291. * 1. `const { foo } = await import('bar')`.
  12292. * 2. `(await import('bar')).foo`
  12293. * 3. `import('bar').then(({ foo }) => {})`
  12294. *
  12295. * Returns empty array if it's side-effect only import.
  12296. * Returns undefined if it's not fully deterministic.
  12297. */
  12298. getDeterministicImportedNames() {
  12299. const parent1 = this.parent;
  12300. // Side-effect only: import('bar')
  12301. if (parent1 instanceof ExpressionStatement) {
  12302. return EMPTY_ARRAY;
  12303. }
  12304. if (parent1 instanceof AwaitExpression) {
  12305. const parent2 = parent1.parent;
  12306. // Side effect only: await import('bar')
  12307. if (parent2 instanceof ExpressionStatement) {
  12308. return EMPTY_ARRAY;
  12309. }
  12310. // Case 1: const { foo } / module = await import('bar')
  12311. if (parent2 instanceof VariableDeclarator) {
  12312. const declaration = parent2.id;
  12313. if (declaration instanceof Identifier) {
  12314. return this.hasUnknownAccessedKey ? undefined : [...this.accessedPropKey];
  12315. }
  12316. if (declaration instanceof ObjectPattern) {
  12317. return getDeterministicObjectDestructure(declaration);
  12318. }
  12319. }
  12320. // Case 2: (await import('bar')).foo
  12321. if (parent2 instanceof MemberExpression) {
  12322. const id = parent2.property;
  12323. if (!parent2.computed && id instanceof Identifier) {
  12324. return [id.name];
  12325. }
  12326. }
  12327. return;
  12328. }
  12329. if (parent1 instanceof MemberExpression) {
  12330. const callExpression = parent1.parent;
  12331. const property = parent1.property;
  12332. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  12333. return;
  12334. }
  12335. const memberName = property.name;
  12336. // side-effect only, when only chaining .catch or .finally
  12337. if (callExpression.parent instanceof ExpressionStatement &&
  12338. ['catch', 'finally'].includes(memberName)) {
  12339. return EMPTY_ARRAY;
  12340. }
  12341. if (memberName !== 'then')
  12342. return;
  12343. // Side-effect only: import('bar').then()
  12344. if (callExpression.arguments.length === 0) {
  12345. return EMPTY_ARRAY;
  12346. }
  12347. const thenCallback = callExpression.arguments[0];
  12348. if (callExpression.arguments.length !== 1 ||
  12349. !(thenCallback instanceof ArrowFunctionExpression ||
  12350. thenCallback instanceof FunctionExpression)) {
  12351. return;
  12352. }
  12353. // Side-effect only: import('bar').then(() => {})
  12354. if (thenCallback.params.length === 0) {
  12355. return EMPTY_ARRAY;
  12356. }
  12357. const declaration = thenCallback.params[0];
  12358. if (thenCallback.params.length === 1 && declaration instanceof ObjectPattern) {
  12359. return getDeterministicObjectDestructure(declaration);
  12360. }
  12361. return this.hasUnknownAccessedKey ? undefined : [...this.accessedPropKey];
  12362. }
  12363. }
  12364. hasEffects() {
  12365. return true;
  12366. }
  12367. include(context, includeChildrenRecursively) {
  12368. if (!this.included)
  12369. this.includeNode(context);
  12370. this.source.include(context, includeChildrenRecursively);
  12371. if (this.shouldIncludeDynamicAttributes)
  12372. this.options?.include(context, includeChildrenRecursively);
  12373. }
  12374. includeNode(context) {
  12375. this.included = true;
  12376. if (this.shouldIncludeDynamicAttributes)
  12377. this.options?.includePath(UNKNOWN_PATH, context);
  12378. this.scope.context.includeDynamicImport(this);
  12379. this.scope.addAccessedDynamicImport(this);
  12380. }
  12381. includePath(path, context) {
  12382. if (!this.included)
  12383. this.includeNode(context);
  12384. // Technically, this is not correct as dynamic imports return a Promise.
  12385. if (this.hasUnknownAccessedKey)
  12386. return;
  12387. if (path[0] === UnknownKey) {
  12388. this.hasUnknownAccessedKey = true;
  12389. }
  12390. else if (typeof path[0] === 'string') {
  12391. this.accessedPropKey.add(path[0]);
  12392. }
  12393. // Update included paths
  12394. this.scope.context.includeDynamicImport(this);
  12395. }
  12396. initialise() {
  12397. super.initialise();
  12398. this.scope.context.addDynamicImport(this);
  12399. }
  12400. parseNode(esTreeNode) {
  12401. this.sourceAstNode = esTreeNode.source;
  12402. return super.parseNode(esTreeNode);
  12403. }
  12404. render(code, options) {
  12405. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess }, importAttributesKey } = options;
  12406. if (this.inlineNamespace) {
  12407. const [left, right] = getDirectReturnFunction([], {
  12408. functionReturn: true,
  12409. lineBreakIndent: null,
  12410. name: null
  12411. });
  12412. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  12413. return;
  12414. }
  12415. if (this.mechanism) {
  12416. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  12417. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  12418. }
  12419. if (this.resolutionString) {
  12420. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  12421. if (this.namespaceExportName) {
  12422. const [left, right] = getDirectReturnFunction(['n'], {
  12423. functionReturn: true,
  12424. lineBreakIndent: null,
  12425. name: null
  12426. });
  12427. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  12428. }
  12429. }
  12430. else {
  12431. this.source.render(code, options);
  12432. }
  12433. if (this.attributes !== true) {
  12434. if (this.options) {
  12435. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  12436. }
  12437. if (this.attributes) {
  12438. code.appendLeft(this.end - 1, `,${_}${getObject([[importAttributesKey, this.attributes]], {
  12439. lineBreakIndent: null
  12440. })}`);
  12441. }
  12442. }
  12443. }
  12444. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, attributes, ownChunk, targetChunk) {
  12445. const { format } = options;
  12446. this.inlineNamespace = null;
  12447. this.resolution = resolution;
  12448. this.resolutionString = resolutionString;
  12449. this.namespaceExportName = namespaceExportName;
  12450. this.attributes = attributes;
  12451. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  12452. let helper;
  12453. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver, ownChunk, targetChunk));
  12454. if (helper) {
  12455. accessedGlobals.push(helper);
  12456. }
  12457. if (accessedGlobals.length > 0) {
  12458. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  12459. }
  12460. }
  12461. setInternalResolution(inlineNamespace) {
  12462. this.inlineNamespace = inlineNamespace;
  12463. }
  12464. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver, ownChunk, targetChunk) {
  12465. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  12466. {
  12467. chunk: getChunkInfoWithPath(ownChunk),
  12468. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  12469. format,
  12470. getTargetChunkImports() {
  12471. if (targetChunk === null)
  12472. return null;
  12473. const chunkInfos = [];
  12474. const importerPath = ownChunk.getFileName();
  12475. for (const dep of targetChunk.dependencies) {
  12476. const resolvedImportPath = `'${dep.getImportPath(importerPath)}'`;
  12477. if (dep instanceof ExternalChunk) {
  12478. chunkInfos.push({
  12479. fileName: dep.getFileName(),
  12480. resolvedImportPath,
  12481. type: 'external'
  12482. });
  12483. }
  12484. else {
  12485. chunkInfos.push({
  12486. chunk: dep.getPreRenderedChunkInfo(),
  12487. fileName: dep.getFileName(),
  12488. resolvedImportPath,
  12489. type: 'internal'
  12490. });
  12491. }
  12492. }
  12493. return chunkInfos;
  12494. },
  12495. moduleId: this.scope.context.module.id,
  12496. targetChunk: targetChunk ? getChunkInfoWithPath(targetChunk) : null,
  12497. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  12498. }
  12499. ]);
  12500. if (mechanism) {
  12501. return { helper: null, mechanism };
  12502. }
  12503. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  12504. switch (format) {
  12505. case 'cjs': {
  12506. if (dynamicImportInCjs &&
  12507. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  12508. return { helper: null, mechanism: null };
  12509. }
  12510. const helper = getInteropHelper(resolution, exportMode, interop);
  12511. let left = `require(`;
  12512. let right = `)`;
  12513. if (helper) {
  12514. left = `/*#__PURE__*/${helper}(${left}`;
  12515. right += ')';
  12516. }
  12517. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  12518. functionReturn: true,
  12519. lineBreakIndent: null,
  12520. name: null
  12521. });
  12522. left = `Promise.resolve().then(${functionLeft}${left}`;
  12523. right += `${functionRight})`;
  12524. if (!arrowFunctions && hasDynamicTarget) {
  12525. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12526. needsArrowReturnParens: false,
  12527. needsWrappedFunction: true
  12528. });
  12529. right = ')';
  12530. }
  12531. return {
  12532. helper,
  12533. mechanism: { left, right }
  12534. };
  12535. }
  12536. case 'amd': {
  12537. const resolve = compact ? 'c' : 'resolve';
  12538. const reject = compact ? 'e' : 'reject';
  12539. const helper = getInteropHelper(resolution, exportMode, interop);
  12540. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  12541. functionReturn: false,
  12542. lineBreakIndent: null,
  12543. name: null
  12544. });
  12545. const resolveNamespace = helper
  12546. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  12547. : resolve;
  12548. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  12549. functionReturn: false,
  12550. lineBreakIndent: null,
  12551. name: null
  12552. });
  12553. let left = `new Promise(${handlerLeft}require([`;
  12554. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  12555. if (!arrowFunctions && hasDynamicTarget) {
  12556. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12557. needsArrowReturnParens: false,
  12558. needsWrappedFunction: true
  12559. });
  12560. right = ')';
  12561. }
  12562. return {
  12563. helper,
  12564. mechanism: { left, right }
  12565. };
  12566. }
  12567. case 'system': {
  12568. return {
  12569. helper: null,
  12570. mechanism: {
  12571. left: 'module.import(',
  12572. right: ')'
  12573. }
  12574. };
  12575. }
  12576. }
  12577. return { helper: null, mechanism: null };
  12578. }
  12579. }
  12580. ImportExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  12581. function getInteropHelper(resolution, exportMode, interop) {
  12582. return exportMode === 'external'
  12583. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  12584. : exportMode === 'default'
  12585. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  12586. : null;
  12587. }
  12588. const accessedImportGlobals = {
  12589. amd: ['require'],
  12590. cjs: ['require'],
  12591. system: ['module']
  12592. };
  12593. function getDeterministicObjectDestructure(objectPattern) {
  12594. const variables = [];
  12595. for (const property of objectPattern.properties) {
  12596. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  12597. return;
  12598. variables.push(property.key.name);
  12599. }
  12600. return variables;
  12601. }
  12602. class ImportNamespaceSpecifier extends NodeBase {
  12603. }
  12604. ImportNamespaceSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12605. ImportNamespaceSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12606. class ImportSpecifier extends NodeBase {
  12607. }
  12608. ImportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12609. ImportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12610. class JSXIdentifier extends IdentifierBase {
  12611. constructor() {
  12612. super(...arguments);
  12613. this.isNativeElement = false;
  12614. }
  12615. bind() {
  12616. const type = this.getType();
  12617. if (type === 0 /* IdentifierType.Reference */) {
  12618. this.variable = this.scope.findVariable(this.name);
  12619. this.variable.addReference(this);
  12620. }
  12621. else if (type === 1 /* IdentifierType.NativeElementName */) {
  12622. this.isNativeElement = true;
  12623. }
  12624. }
  12625. include(context) {
  12626. if (!this.included)
  12627. this.includeNode(context);
  12628. }
  12629. includeNode(context) {
  12630. this.included = true;
  12631. if (!this.deoptimized)
  12632. this.applyDeoptimizations();
  12633. if (this.variable !== null) {
  12634. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  12635. }
  12636. }
  12637. includePath(path, context) {
  12638. if (!this.included) {
  12639. this.included = true;
  12640. if (this.variable !== null) {
  12641. this.scope.context.includeVariableInModule(this.variable, path, context);
  12642. }
  12643. }
  12644. else if (path.length > 0) {
  12645. this.variable?.includePath(path, context);
  12646. }
  12647. }
  12648. render(code, { snippets: { getPropertyAccess }, useOriginalName }) {
  12649. if (this.variable) {
  12650. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  12651. if (name !== this.name) {
  12652. code.overwrite(this.start, this.end, name, {
  12653. contentOnly: true,
  12654. storeName: true
  12655. });
  12656. }
  12657. }
  12658. else if (this.isNativeElement &&
  12659. this.scope.context.options.jsx.mode !== 'preserve') {
  12660. code.update(this.start, this.end, JSON.stringify(this.name));
  12661. }
  12662. }
  12663. getType() {
  12664. switch (this.parent.type) {
  12665. case 'JSXOpeningElement':
  12666. case 'JSXClosingElement': {
  12667. return this.name.startsWith(this.name.charAt(0).toUpperCase())
  12668. ? 0 /* IdentifierType.Reference */
  12669. : 1 /* IdentifierType.NativeElementName */;
  12670. }
  12671. case 'JSXMemberExpression': {
  12672. return this.parent.object === this
  12673. ? 0 /* IdentifierType.Reference */
  12674. : 2 /* IdentifierType.Other */;
  12675. }
  12676. case 'JSXAttribute':
  12677. case 'JSXNamespacedName': {
  12678. return 2 /* IdentifierType.Other */;
  12679. }
  12680. default: {
  12681. /* istanbul ignore next */
  12682. throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
  12683. }
  12684. }
  12685. }
  12686. }
  12687. class JSXAttribute extends NodeBase {
  12688. render(code, options, { jsxMode } = BLANK) {
  12689. super.render(code, options);
  12690. if (['classic', 'automatic'].includes(jsxMode)) {
  12691. const { name, value } = this;
  12692. const key = name instanceof JSXIdentifier ? name.name : `${name.namespace.name}:${name.name.name}`;
  12693. if (!(jsxMode === 'automatic' && key === 'key')) {
  12694. const safeKey = stringifyObjectKeyIfNeeded(key);
  12695. if (key !== safeKey) {
  12696. code.overwrite(name.start, name.end, safeKey, { contentOnly: true });
  12697. }
  12698. if (value) {
  12699. code.overwrite(name.end, value.start, ': ', { contentOnly: true });
  12700. // foo="aa \n aa"
  12701. if (value instanceof Literal &&
  12702. typeof value.value === 'string' &&
  12703. value.value.includes('\n')) {
  12704. code.overwrite(value.start, value.end, JSON.stringify(value.value), {
  12705. contentOnly: true
  12706. });
  12707. }
  12708. }
  12709. else {
  12710. code.appendLeft(name.end, ': true');
  12711. }
  12712. }
  12713. }
  12714. }
  12715. }
  12716. JSXAttribute.prototype.includeNode = onlyIncludeSelf;
  12717. class JSXClosingBase extends NodeBase {
  12718. render(code, options) {
  12719. const { mode } = this.scope.context.options.jsx;
  12720. if (mode !== 'preserve') {
  12721. code.overwrite(this.start, this.end, ')', { contentOnly: true });
  12722. }
  12723. else {
  12724. super.render(code, options);
  12725. }
  12726. }
  12727. }
  12728. JSXClosingBase.prototype.includeNode = onlyIncludeSelf;
  12729. class JSXClosingElement extends JSXClosingBase {
  12730. }
  12731. class JSXClosingFragment extends JSXClosingBase {
  12732. }
  12733. class JSXSpreadAttribute extends NodeBase {
  12734. render(code, options) {
  12735. this.argument.render(code, options);
  12736. const { mode } = this.scope.context.options.jsx;
  12737. if (mode !== 'preserve') {
  12738. code.overwrite(this.start, this.argument.start, '', { contentOnly: true });
  12739. code.overwrite(this.argument.end, this.end, '', { contentOnly: true });
  12740. }
  12741. }
  12742. }
  12743. class JSXEmptyExpression extends NodeBase {
  12744. }
  12745. JSXEmptyExpression.prototype.includeNode = onlyIncludeSelf;
  12746. class JSXExpressionContainer extends NodeBase {
  12747. includeNode(context) {
  12748. this.included = true;
  12749. if (!this.deoptimized)
  12750. this.applyDeoptimizations();
  12751. this.expression.includePath(UNKNOWN_PATH, context);
  12752. }
  12753. render(code, options) {
  12754. const { mode } = this.scope.context.options.jsx;
  12755. if (mode !== 'preserve') {
  12756. code.remove(this.start, this.expression.start);
  12757. code.remove(this.expression.end, this.end);
  12758. }
  12759. this.expression.render(code, options);
  12760. }
  12761. }
  12762. const RE_WHITESPACE_TRIM = /^[ \t]*\r?\n[ \t\r\n]*|[ \t]*\r?\n[ \t\r\n]*$/g;
  12763. const RE_WHITESPACE_MERGE = /[ \t]*\r?\n[ \t\r\n]*/g;
  12764. class JSXText extends NodeBase {
  12765. shouldRender() {
  12766. return !!this.getRenderedText();
  12767. }
  12768. render(code) {
  12769. const { mode } = this.scope.context.options.jsx;
  12770. if (mode !== 'preserve') {
  12771. code.overwrite(this.start, this.end, JSON.stringify(this.getRenderedText()), {
  12772. contentOnly: true
  12773. });
  12774. }
  12775. }
  12776. getRenderedText() {
  12777. if (this.renderedText === undefined)
  12778. this.renderedText = this.value
  12779. .replace(RE_WHITESPACE_TRIM, '')
  12780. .replace(RE_WHITESPACE_MERGE, ' ');
  12781. return this.renderedText;
  12782. }
  12783. }
  12784. JSXText.prototype.includeNode = onlyIncludeSelf;
  12785. function getRenderedJsxChildren(children) {
  12786. let renderedChildren = 0;
  12787. for (const child of children) {
  12788. if (!(child instanceof JSXExpressionContainer && child.expression instanceof JSXEmptyExpression) &&
  12789. (!(child instanceof JSXText) || child.shouldRender())) {
  12790. renderedChildren++;
  12791. }
  12792. }
  12793. return renderedChildren;
  12794. }
  12795. function getAndIncludeFactoryVariable(factory, preserve, importSource, node, context) {
  12796. const [baseName, nestedName] = factory.split('.');
  12797. let factoryVariable;
  12798. if (importSource) {
  12799. factoryVariable = node.scope.context.getImportedJsxFactoryVariable(nestedName ? 'default' : baseName, node.start, importSource);
  12800. if (preserve) {
  12801. // This pretends we are accessing an included global variable of the same name
  12802. const globalVariable = node.scope.findGlobal(baseName);
  12803. globalVariable.includePath(UNKNOWN_PATH, context);
  12804. // This excludes this variable from renaming
  12805. factoryVariable.globalName = baseName;
  12806. }
  12807. }
  12808. else {
  12809. factoryVariable = node.scope.findGlobal(baseName);
  12810. }
  12811. node.scope.context.includeVariableInModule(factoryVariable, UNKNOWN_PATH, context);
  12812. if (factoryVariable instanceof LocalVariable) {
  12813. factoryVariable.consolidateInitializers();
  12814. factoryVariable.addUsedPlace(node);
  12815. node.scope.context.requestTreeshakingPass();
  12816. }
  12817. return factoryVariable;
  12818. }
  12819. class JSXElementBase extends NodeBase {
  12820. constructor() {
  12821. super(...arguments);
  12822. this.factoryVariable = null;
  12823. this.factory = null;
  12824. }
  12825. initialise() {
  12826. super.initialise();
  12827. const { importSource } = (this.jsxMode = this.getRenderingMode());
  12828. if (importSource) {
  12829. this.scope.context.addImportSource(importSource);
  12830. }
  12831. }
  12832. include(context, includeChildrenRecursively) {
  12833. if (!this.included)
  12834. this.includeNode(context);
  12835. for (const child of this.children) {
  12836. child.include(context, includeChildrenRecursively);
  12837. }
  12838. }
  12839. includeNode(context) {
  12840. this.included = true;
  12841. const { factory, importSource, mode } = this.jsxMode;
  12842. if (factory) {
  12843. this.factory = factory;
  12844. this.factoryVariable = getAndIncludeFactoryVariable(factory, mode === 'preserve', importSource, this, context);
  12845. }
  12846. }
  12847. getRenderingMode() {
  12848. const jsx = this.scope.context.options.jsx;
  12849. const { mode, factory, importSource } = jsx;
  12850. if (mode === 'automatic') {
  12851. return {
  12852. factory: getRenderedJsxChildren(this.children) > 1 ? 'jsxs' : 'jsx',
  12853. importSource: jsx.jsxImportSource,
  12854. mode
  12855. };
  12856. }
  12857. return { factory, importSource, mode };
  12858. }
  12859. renderChildren(code, options, openingEnd) {
  12860. const { children } = this;
  12861. let hasMultipleChildren = false;
  12862. let childrenEnd = openingEnd;
  12863. let firstChild = null;
  12864. for (const child of children) {
  12865. if ((child instanceof JSXExpressionContainer &&
  12866. child.expression instanceof JSXEmptyExpression) ||
  12867. (child instanceof JSXText && !child.shouldRender())) {
  12868. code.remove(childrenEnd, child.end);
  12869. }
  12870. else {
  12871. code.appendLeft(childrenEnd, ', ');
  12872. child.render(code, options);
  12873. if (firstChild) {
  12874. hasMultipleChildren = true;
  12875. }
  12876. else {
  12877. firstChild = child;
  12878. }
  12879. }
  12880. childrenEnd = child.end;
  12881. }
  12882. return { childrenEnd, firstChild, hasMultipleChildren };
  12883. }
  12884. }
  12885. JSXElementBase.prototype.applyDeoptimizations = doNotDeoptimize;
  12886. class JSXElement extends JSXElementBase {
  12887. include(context, includeChildrenRecursively) {
  12888. super.include(context, includeChildrenRecursively);
  12889. this.openingElement.include(context, includeChildrenRecursively);
  12890. this.closingElement?.include(context, includeChildrenRecursively);
  12891. }
  12892. render(code, options) {
  12893. switch (this.jsxMode.mode) {
  12894. case 'classic': {
  12895. this.renderClassicMode(code, options);
  12896. break;
  12897. }
  12898. case 'automatic': {
  12899. this.renderAutomaticMode(code, options);
  12900. break;
  12901. }
  12902. default: {
  12903. super.render(code, options);
  12904. }
  12905. }
  12906. }
  12907. getRenderingMode() {
  12908. const jsx = this.scope.context.options.jsx;
  12909. const { mode, factory, importSource } = jsx;
  12910. if (mode === 'automatic') {
  12911. // In the case there is a key after a spread attribute, we fall back to
  12912. // classic mode, see https://github.com/facebook/react/issues/20031#issuecomment-710346866
  12913. // for reasoning.
  12914. let hasSpread = false;
  12915. for (const attribute of this.openingElement.attributes) {
  12916. if (attribute instanceof JSXSpreadAttribute) {
  12917. hasSpread = true;
  12918. }
  12919. else if (hasSpread && attribute.name.name === 'key') {
  12920. return { factory, importSource, mode: 'classic' };
  12921. }
  12922. }
  12923. }
  12924. return super.getRenderingMode();
  12925. }
  12926. renderClassicMode(code, options) {
  12927. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12928. const { closingElement, end, factory, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  12929. const [, ...nestedName] = factory.split('.');
  12930. const { firstAttribute, hasAttributes, hasSpread, inObject, previousEnd } = this.renderAttributes(code, options, [factoryVariable.getName(getPropertyAccess, useOriginalName), ...nestedName].join('.'), false);
  12931. this.wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, 'null', previousEnd);
  12932. this.renderChildren(code, options, openingEnd);
  12933. if (selfClosing) {
  12934. code.appendLeft(end, ')');
  12935. }
  12936. else {
  12937. closingElement.render(code, options);
  12938. }
  12939. }
  12940. renderAutomaticMode(code, options) {
  12941. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12942. const { closingElement, end, factoryVariable, openingElement: { end: openindEnd, selfClosing } } = this;
  12943. let { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd } = this.renderAttributes(code, options, factoryVariable.getName(getPropertyAccess, useOriginalName), true);
  12944. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openindEnd);
  12945. if (firstChild) {
  12946. code.prependRight(firstChild.start, `children: ${hasMultipleChildren ? '[' : ''}`);
  12947. if (!inObject) {
  12948. code.prependRight(firstChild.start, '{ ');
  12949. inObject = true;
  12950. }
  12951. previousEnd = closingElement.start;
  12952. if (hasMultipleChildren) {
  12953. code.appendLeft(previousEnd, ']');
  12954. }
  12955. }
  12956. this.wrapAttributes(code, inObject, hasAttributes || !!firstChild, hasSpread, firstAttribute || firstChild, '{}', childrenEnd);
  12957. if (keyAttribute) {
  12958. const { value } = keyAttribute;
  12959. // This will appear to the left of the moved code...
  12960. code.appendLeft(childrenEnd, ', ');
  12961. if (value) {
  12962. code.move(value.start, value.end, childrenEnd);
  12963. }
  12964. else {
  12965. code.appendLeft(childrenEnd, 'true');
  12966. }
  12967. }
  12968. if (selfClosing) {
  12969. // Moving the key attribute will also move the parenthesis to the right position
  12970. code.appendLeft(keyAttribute?.value?.end || end, ')');
  12971. }
  12972. else {
  12973. closingElement.render(code, options);
  12974. }
  12975. }
  12976. renderAttributes(code, options, factoryName, extractKeyAttribute) {
  12977. const { jsxMode: { mode }, openingElement } = this;
  12978. const { attributes, end: openingEnd, start: openingStart, name: { start: nameStart, end: nameEnd } } = openingElement;
  12979. code.update(openingStart, nameStart, `/*#__PURE__*/${factoryName}(`);
  12980. openingElement.render(code, options, { jsxMode: mode });
  12981. let keyAttribute = null;
  12982. let hasSpread = false;
  12983. let inObject = false;
  12984. let previousEnd = nameEnd;
  12985. let hasAttributes = false;
  12986. let firstAttribute = null;
  12987. for (const attribute of attributes) {
  12988. if (attribute instanceof JSXAttribute) {
  12989. if (extractKeyAttribute && attribute.name.name === 'key') {
  12990. keyAttribute = attribute;
  12991. code.remove(previousEnd, attribute.value?.start || attribute.end);
  12992. continue;
  12993. }
  12994. code.appendLeft(previousEnd, ',');
  12995. if (!inObject) {
  12996. code.prependRight(attribute.start, '{ ');
  12997. inObject = true;
  12998. }
  12999. hasAttributes = true;
  13000. }
  13001. else {
  13002. if (inObject) {
  13003. if (hasAttributes) {
  13004. code.appendLeft(previousEnd, ' ');
  13005. }
  13006. code.appendLeft(previousEnd, '},');
  13007. inObject = false;
  13008. }
  13009. else {
  13010. code.appendLeft(previousEnd, ',');
  13011. }
  13012. hasSpread = true;
  13013. }
  13014. previousEnd = attribute.end;
  13015. if (!firstAttribute) {
  13016. firstAttribute = attribute;
  13017. }
  13018. }
  13019. code.remove(attributes.at(-1)?.end || previousEnd, openingEnd);
  13020. return { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd };
  13021. }
  13022. wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, missingAttributesFallback, attributesEnd) {
  13023. if (inObject) {
  13024. code.appendLeft(attributesEnd, ' }');
  13025. }
  13026. if (hasSpread) {
  13027. if (hasAttributes) {
  13028. const { start } = firstAttribute;
  13029. if (firstAttribute instanceof JSXSpreadAttribute) {
  13030. code.prependRight(start, '{}, ');
  13031. }
  13032. code.prependRight(start, 'Object.assign(');
  13033. code.appendLeft(attributesEnd, ')');
  13034. }
  13035. }
  13036. else if (!hasAttributes) {
  13037. code.appendLeft(attributesEnd, `, ${missingAttributesFallback}`);
  13038. }
  13039. }
  13040. }
  13041. class JSXFragment extends JSXElementBase {
  13042. include(context, includeChildrenRecursively) {
  13043. super.include(context, includeChildrenRecursively);
  13044. this.openingFragment.include(context, includeChildrenRecursively);
  13045. this.closingFragment.include(context, includeChildrenRecursively);
  13046. }
  13047. render(code, options) {
  13048. switch (this.jsxMode.mode) {
  13049. case 'classic': {
  13050. this.renderClassicMode(code, options);
  13051. break;
  13052. }
  13053. case 'automatic': {
  13054. this.renderAutomaticMode(code, options);
  13055. break;
  13056. }
  13057. default: {
  13058. super.render(code, options);
  13059. }
  13060. }
  13061. }
  13062. renderClassicMode(code, options) {
  13063. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13064. const { closingFragment, factory, factoryVariable, openingFragment, start } = this;
  13065. const [, ...nestedName] = factory.split('.');
  13066. openingFragment.render(code, options);
  13067. code.prependRight(start, `/*#__PURE__*/${[
  13068. factoryVariable.getName(getPropertyAccess, useOriginalName),
  13069. ...nestedName
  13070. ].join('.')}(`);
  13071. code.appendLeft(openingFragment.end, ', null');
  13072. this.renderChildren(code, options, openingFragment.end);
  13073. closingFragment.render(code, options);
  13074. }
  13075. renderAutomaticMode(code, options) {
  13076. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13077. const { closingFragment, factoryVariable, openingFragment, start } = this;
  13078. openingFragment.render(code, options);
  13079. code.prependRight(start, `/*#__PURE__*/${factoryVariable.getName(getPropertyAccess, useOriginalName)}(`);
  13080. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingFragment.end);
  13081. if (firstChild) {
  13082. code.prependRight(firstChild.start, `{ children: ${hasMultipleChildren ? '[' : ''}`);
  13083. if (hasMultipleChildren) {
  13084. code.appendLeft(closingFragment.start, ']');
  13085. }
  13086. code.appendLeft(childrenEnd, ' }');
  13087. }
  13088. else {
  13089. code.appendLeft(openingFragment.end, ', {}');
  13090. }
  13091. closingFragment.render(code, options);
  13092. }
  13093. }
  13094. class JSXMemberExpression extends NodeBase {
  13095. includeNode(context) {
  13096. this.included = true;
  13097. if (!this.deoptimized)
  13098. this.applyDeoptimizations();
  13099. this.object.includePath([this.property.name], context);
  13100. }
  13101. includePath(path, context) {
  13102. if (!this.included)
  13103. this.includeNode(context);
  13104. this.object.includePath([this.property.name, ...path], context);
  13105. }
  13106. }
  13107. class JSXNamespacedName extends NodeBase {
  13108. }
  13109. JSXNamespacedName.prototype.includeNode = onlyIncludeSelf;
  13110. class JSXOpeningElement extends NodeBase {
  13111. render(code, options, { jsxMode = this.scope.context.options.jsx.mode } = {}) {
  13112. this.name.render(code, options);
  13113. for (const attribute of this.attributes) {
  13114. attribute.render(code, options, { jsxMode });
  13115. }
  13116. }
  13117. }
  13118. JSXOpeningElement.prototype.includeNode = onlyIncludeSelf;
  13119. class JSXOpeningFragment extends NodeBase {
  13120. constructor() {
  13121. super(...arguments);
  13122. this.fragment = null;
  13123. this.fragmentVariable = null;
  13124. }
  13125. includeNode(context) {
  13126. this.included = true;
  13127. if (!this.deoptimized)
  13128. this.applyDeoptimizations();
  13129. const jsx = this.scope.context.options.jsx;
  13130. if (jsx.mode === 'automatic') {
  13131. this.fragment = 'Fragment';
  13132. this.fragmentVariable = getAndIncludeFactoryVariable('Fragment', false, jsx.jsxImportSource, this, context);
  13133. }
  13134. else {
  13135. const { fragment, importSource, mode } = jsx;
  13136. if (fragment != null) {
  13137. this.fragment = fragment;
  13138. this.fragmentVariable = getAndIncludeFactoryVariable(fragment, mode === 'preserve', importSource, this, context);
  13139. }
  13140. }
  13141. }
  13142. render(code, options) {
  13143. const { mode } = this.scope.context.options.jsx;
  13144. if (mode !== 'preserve') {
  13145. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13146. const [, ...nestedFragment] = this.fragment.split('.');
  13147. const fragment = [
  13148. this.fragmentVariable.getName(getPropertyAccess, useOriginalName),
  13149. ...nestedFragment
  13150. ].join('.');
  13151. code.update(this.start, this.end, fragment);
  13152. }
  13153. }
  13154. }
  13155. class JSXSpreadChild extends NodeBase {
  13156. render(code, options) {
  13157. super.render(code, options);
  13158. const { mode } = this.scope.context.options.jsx;
  13159. if (mode !== 'preserve') {
  13160. code.overwrite(this.start, this.expression.start, '...', { contentOnly: true });
  13161. code.overwrite(this.expression.end, this.end, '', { contentOnly: true });
  13162. }
  13163. }
  13164. }
  13165. class LabeledStatement extends NodeBase {
  13166. hasEffects(context) {
  13167. const { brokenFlow, includedLabels } = context;
  13168. context.ignore.labels.add(this.label.name);
  13169. context.includedLabels = new Set();
  13170. let bodyHasEffects = false;
  13171. if (this.body.hasEffects(context)) {
  13172. bodyHasEffects = true;
  13173. }
  13174. else {
  13175. context.ignore.labels.delete(this.label.name);
  13176. if (context.includedLabels.has(this.label.name)) {
  13177. context.includedLabels.delete(this.label.name);
  13178. context.brokenFlow = brokenFlow;
  13179. }
  13180. }
  13181. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  13182. return bodyHasEffects;
  13183. }
  13184. include(context, includeChildrenRecursively) {
  13185. if (!this.included)
  13186. this.includeNode(context);
  13187. const { brokenFlow, includedLabels } = context;
  13188. context.includedLabels = new Set();
  13189. this.body.include(context, includeChildrenRecursively);
  13190. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  13191. this.label.include(context, includeChildrenRecursively);
  13192. context.includedLabels.delete(this.label.name);
  13193. context.brokenFlow = brokenFlow;
  13194. }
  13195. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  13196. }
  13197. includeNode(context) {
  13198. this.included = true;
  13199. this.body.includePath(UNKNOWN_PATH, context);
  13200. }
  13201. render(code, options) {
  13202. if (this.label.included) {
  13203. this.label.render(code, options);
  13204. }
  13205. else {
  13206. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  13207. }
  13208. this.body.render(code, options);
  13209. }
  13210. }
  13211. LabeledStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13212. class LogicalExpression extends NodeBase {
  13213. constructor() {
  13214. super(...arguments);
  13215. // We collect deoptimization information if usedBranch !== null
  13216. this.expressionsToBeDeoptimized = [];
  13217. this.usedBranch = null;
  13218. }
  13219. //private isBranchResolutionAnalysed = false;
  13220. get isBranchResolutionAnalysed() {
  13221. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  13222. }
  13223. set isBranchResolutionAnalysed(value) {
  13224. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  13225. }
  13226. get hasDeoptimizedCache() {
  13227. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  13228. }
  13229. set hasDeoptimizedCache(value) {
  13230. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  13231. }
  13232. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13233. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13234. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13235. }
  13236. deoptimizeCache() {
  13237. if (this.hasDeoptimizedCache)
  13238. return;
  13239. this.hasDeoptimizedCache = true;
  13240. if (this.usedBranch) {
  13241. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  13242. this.usedBranch = null;
  13243. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  13244. if (this.included) {
  13245. // As we are not tracking inclusions, we just include everything
  13246. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  13247. }
  13248. }
  13249. const { scope: { context }, expressionsToBeDeoptimized } = this;
  13250. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  13251. for (const expression of expressionsToBeDeoptimized) {
  13252. expression.deoptimizeCache();
  13253. }
  13254. // Request another pass because we need to ensure "include" runs again if
  13255. // it is rendered
  13256. context.requestTreeshakingPass();
  13257. }
  13258. deoptimizePath(path) {
  13259. const usedBranch = this.getUsedBranch();
  13260. if (usedBranch) {
  13261. usedBranch.deoptimizePath(path);
  13262. }
  13263. else {
  13264. this.left.deoptimizePath(path);
  13265. this.right.deoptimizePath(path);
  13266. }
  13267. }
  13268. getLiteralValueAtPath(path, recursionTracker, origin) {
  13269. if (origin === this)
  13270. return UnknownValue;
  13271. const usedBranch = this.getUsedBranch();
  13272. if (usedBranch) {
  13273. this.expressionsToBeDeoptimized.push(origin);
  13274. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  13275. }
  13276. else if (!this.hasDeoptimizedCache && !path.length) {
  13277. const rightValue = this.right.getLiteralValueAtPath(path, recursionTracker, origin);
  13278. const booleanOrUnknown = tryCastLiteralValueToBoolean(rightValue);
  13279. if (typeof booleanOrUnknown !== 'symbol') {
  13280. if (!booleanOrUnknown && this.operator === '&&') {
  13281. this.expressionsToBeDeoptimized.push(origin);
  13282. return UnknownFalsyValue;
  13283. }
  13284. if (booleanOrUnknown && this.operator === '||') {
  13285. this.expressionsToBeDeoptimized.push(origin);
  13286. return UnknownTruthyValue;
  13287. }
  13288. }
  13289. }
  13290. return UnknownValue;
  13291. }
  13292. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13293. const usedBranch = this.getUsedBranch();
  13294. if (usedBranch) {
  13295. this.expressionsToBeDeoptimized.push(origin);
  13296. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13297. }
  13298. return [
  13299. new MultiExpression([
  13300. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  13301. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  13302. ]),
  13303. false
  13304. ];
  13305. }
  13306. hasEffects(context) {
  13307. if (this.left.hasEffects(context)) {
  13308. return true;
  13309. }
  13310. if (this.getUsedBranch() !== this.left) {
  13311. return this.right.hasEffects(context);
  13312. }
  13313. return false;
  13314. }
  13315. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13316. const usedBranch = this.getUsedBranch();
  13317. if (usedBranch) {
  13318. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  13319. }
  13320. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  13321. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  13322. }
  13323. include(context, includeChildrenRecursively) {
  13324. this.included = true;
  13325. const usedBranch = this.getUsedBranch();
  13326. if (includeChildrenRecursively ||
  13327. !usedBranch ||
  13328. (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  13329. this.left.include(context, includeChildrenRecursively);
  13330. this.right.include(context, includeChildrenRecursively);
  13331. }
  13332. else {
  13333. usedBranch.include(context, includeChildrenRecursively);
  13334. }
  13335. }
  13336. includePath(path, context) {
  13337. this.included = true;
  13338. const usedBranch = this.getUsedBranch();
  13339. if (!usedBranch || (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  13340. this.left.includePath(path, context);
  13341. this.right.includePath(path, context);
  13342. }
  13343. else {
  13344. usedBranch.includePath(path, context);
  13345. }
  13346. }
  13347. removeAnnotations(code) {
  13348. this.left.removeAnnotations(code);
  13349. }
  13350. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  13351. if (!this.left.included || !this.right.included) {
  13352. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  13353. if (this.right.included) {
  13354. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  13355. code.remove(this.start, removePos);
  13356. if (preventASI) {
  13357. removeLineBreaks(code, removePos, this.right.start);
  13358. }
  13359. this.left.removeAnnotations(code);
  13360. }
  13361. else {
  13362. code.remove(findLastWhiteSpaceReverse(code.original, this.left.end, operatorPos), this.end);
  13363. }
  13364. this.getUsedBranch().render(code, options, {
  13365. isCalleeOfRenderedParent,
  13366. preventASI,
  13367. renderedParentType: renderedParentType || this.parent.type,
  13368. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  13369. });
  13370. }
  13371. else {
  13372. this.left.render(code, options, {
  13373. preventASI,
  13374. renderedSurroundingElement
  13375. });
  13376. this.right.render(code, options);
  13377. }
  13378. }
  13379. getUsedBranch() {
  13380. if (!this.isBranchResolutionAnalysed) {
  13381. this.isBranchResolutionAnalysed = true;
  13382. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  13383. const booleanOrUnknown = tryCastLiteralValueToBoolean(leftValue);
  13384. if (typeof booleanOrUnknown === 'symbol' ||
  13385. (this.operator === '??' && typeof leftValue === 'symbol')) {
  13386. return null;
  13387. }
  13388. else {
  13389. this.usedBranch =
  13390. (this.operator === '||' && booleanOrUnknown) ||
  13391. (this.operator === '&&' && !booleanOrUnknown) ||
  13392. (this.operator === '??' && leftValue != null)
  13393. ? this.left
  13394. : this.right;
  13395. }
  13396. }
  13397. return this.usedBranch;
  13398. }
  13399. }
  13400. LogicalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13401. LogicalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13402. class NewExpression extends NodeBase {
  13403. hasEffects(context) {
  13404. if (!this.deoptimized)
  13405. this.applyDeoptimizations();
  13406. for (const argument of this.arguments) {
  13407. if (argument.hasEffects(context))
  13408. return true;
  13409. }
  13410. if (this.annotationPure) {
  13411. return false;
  13412. }
  13413. return (this.callee.hasEffects(context) ||
  13414. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  13415. }
  13416. hasEffectsOnInteractionAtPath(path, { type }) {
  13417. return path.length > 0 || type !== INTERACTION_ACCESSED;
  13418. }
  13419. include(context, includeChildrenRecursively) {
  13420. if (!this.included)
  13421. this.includeNode(context);
  13422. if (includeChildrenRecursively) {
  13423. super.include(context, true);
  13424. }
  13425. else {
  13426. this.callee.include(context, false);
  13427. this.callee.includeCallArguments(this.interaction, context);
  13428. }
  13429. }
  13430. includeNode(context) {
  13431. this.included = true;
  13432. if (!this.deoptimized)
  13433. this.applyDeoptimizations();
  13434. this.callee.includePath(UNKNOWN_PATH, context);
  13435. }
  13436. initialise() {
  13437. super.initialise();
  13438. this.interaction = {
  13439. args: [null, ...this.arguments],
  13440. type: INTERACTION_CALLED,
  13441. withNew: true
  13442. };
  13443. if (this.annotations &&
  13444. this.scope.context.options.treeshake.annotations) {
  13445. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  13446. }
  13447. }
  13448. render(code, options) {
  13449. this.callee.render(code, options);
  13450. renderCallArguments(code, options, this);
  13451. }
  13452. applyDeoptimizations() {
  13453. this.deoptimized = true;
  13454. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  13455. this.scope.context.requestTreeshakingPass();
  13456. }
  13457. }
  13458. class ObjectExpression extends NodeBase {
  13459. constructor() {
  13460. super(...arguments);
  13461. this.objectEntity = null;
  13462. this.protoProp = null;
  13463. }
  13464. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13465. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13466. }
  13467. deoptimizeCache() {
  13468. this.getObjectEntity().deoptimizeAllProperties();
  13469. }
  13470. deoptimizePath(path) {
  13471. this.getObjectEntity().deoptimizePath(path);
  13472. }
  13473. getLiteralValueAtPath(path, recursionTracker, origin) {
  13474. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  13475. }
  13476. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13477. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13478. }
  13479. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13480. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  13481. }
  13482. include(context, includeChildrenRecursively) {
  13483. if (!this.included)
  13484. this.includeNode(context);
  13485. this.getObjectEntity().include(context, includeChildrenRecursively);
  13486. this.protoProp?.include(context, includeChildrenRecursively);
  13487. }
  13488. includeNode(context) {
  13489. this.included = true;
  13490. this.protoProp?.includePath(UNKNOWN_PATH, context);
  13491. }
  13492. includePath(path, context) {
  13493. if (!this.included)
  13494. this.includeNode(context);
  13495. this.getObjectEntity().includePath(path, context);
  13496. }
  13497. render(code, options, { renderedSurroundingElement } = BLANK) {
  13498. if (renderedSurroundingElement === ExpressionStatement$1 ||
  13499. renderedSurroundingElement === ArrowFunctionExpression$1) {
  13500. code.appendRight(this.start, '(');
  13501. code.prependLeft(this.end, ')');
  13502. }
  13503. if (this.properties.length > 0) {
  13504. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  13505. let lastSeparatorPos = null;
  13506. for (const { node, separator, start, end } of separatedNodes) {
  13507. if (!node.included) {
  13508. treeshakeNode(node, code, start, end);
  13509. continue;
  13510. }
  13511. lastSeparatorPos = separator;
  13512. node.render(code, options);
  13513. }
  13514. if (lastSeparatorPos) {
  13515. code.remove(lastSeparatorPos, this.end - 1);
  13516. }
  13517. }
  13518. }
  13519. getObjectEntity() {
  13520. if (this.objectEntity !== null) {
  13521. return this.objectEntity;
  13522. }
  13523. let prototype = OBJECT_PROTOTYPE;
  13524. const properties = [];
  13525. for (const property of this.properties) {
  13526. if (property instanceof SpreadElement) {
  13527. properties.push({ key: UnknownKey, kind: 'init', property });
  13528. continue;
  13529. }
  13530. let key;
  13531. if (property.computed) {
  13532. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  13533. if (typeof keyValue === 'symbol') {
  13534. properties.push({ key: UnknownKey, kind: property.kind, property });
  13535. continue;
  13536. }
  13537. else {
  13538. key = String(keyValue);
  13539. }
  13540. }
  13541. else {
  13542. key =
  13543. property.key instanceof Identifier
  13544. ? property.key.name
  13545. : String(property.key.value);
  13546. if (key === '__proto__' && property.kind === 'init') {
  13547. this.protoProp = property;
  13548. prototype =
  13549. property.value instanceof Literal && property.value.value === null
  13550. ? null
  13551. : property.value;
  13552. continue;
  13553. }
  13554. }
  13555. properties.push({ key, kind: property.kind, property });
  13556. }
  13557. return (this.objectEntity = new ObjectEntity(properties, prototype));
  13558. }
  13559. }
  13560. ObjectExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13561. class PanicError extends NodeBase {
  13562. initialise() {
  13563. const id = this.scope.context.module.id;
  13564. // This simulates the current nested error structure. We could also just
  13565. // replace it with a flat error.
  13566. const parseError = getRollupError(logParseError(this.message));
  13567. const moduleParseError = logModuleParseError(parseError, id);
  13568. return error(moduleParseError);
  13569. }
  13570. }
  13571. class ParseError extends NodeBase {
  13572. initialise() {
  13573. const pos = this.start;
  13574. const id = this.scope.context.module.id;
  13575. // This simulates the current nested error structure. We could also just
  13576. // replace it with a flat error.
  13577. const parseError = getRollupError(logParseError(this.message, pos));
  13578. const moduleParseError = logModuleParseError(parseError, id);
  13579. this.scope.context.error(moduleParseError, pos);
  13580. }
  13581. }
  13582. class PrivateIdentifier extends NodeBase {
  13583. }
  13584. PrivateIdentifier.prototype.includeNode = onlyIncludeSelf;
  13585. class Program extends NodeBase {
  13586. constructor() {
  13587. super(...arguments);
  13588. this.hasCachedEffect = null;
  13589. this.hasLoggedEffect = false;
  13590. }
  13591. hasCachedEffects() {
  13592. if (!this.included) {
  13593. return false;
  13594. }
  13595. return this.hasCachedEffect === null
  13596. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  13597. : this.hasCachedEffect;
  13598. }
  13599. hasEffects(context) {
  13600. for (const node of this.body) {
  13601. if (node.hasEffects(context)) {
  13602. if (this.scope.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  13603. this.hasLoggedEffect = true;
  13604. const { code, log, module } = this.scope.context;
  13605. log(LOGLEVEL_INFO, logFirstSideEffect(code, module.id, locate(code, node.start, { offsetLine: 1 })), node.start);
  13606. }
  13607. return (this.hasCachedEffect = true);
  13608. }
  13609. }
  13610. return false;
  13611. }
  13612. include(context, includeChildrenRecursively) {
  13613. this.included = true;
  13614. for (const node of this.body) {
  13615. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  13616. node.include(context, includeChildrenRecursively);
  13617. }
  13618. }
  13619. }
  13620. initialise() {
  13621. super.initialise();
  13622. if (this.invalidAnnotations)
  13623. for (const { start, end, type } of this.invalidAnnotations) {
  13624. this.scope.context.magicString.remove(start, end);
  13625. if (type === 'pure' || type === 'noSideEffects') {
  13626. this.scope.context.log(LOGLEVEL_WARN, logInvalidAnnotation(this.scope.context.code.slice(start, end), this.scope.context.module.id, type), start);
  13627. }
  13628. }
  13629. }
  13630. render(code, options) {
  13631. let start = this.start;
  13632. if (code.original.startsWith('#!')) {
  13633. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  13634. code.remove(0, start);
  13635. }
  13636. if (this.body.length > 0) {
  13637. // Keep all consecutive lines that start with a comment
  13638. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  13639. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  13640. if (firstLineBreak[0] === -1) {
  13641. break;
  13642. }
  13643. start += firstLineBreak[1];
  13644. }
  13645. renderStatementList(this.body, code, start, this.end, options);
  13646. }
  13647. else {
  13648. super.render(code, options);
  13649. }
  13650. }
  13651. }
  13652. Program.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13653. Program.prototype.applyDeoptimizations = doNotDeoptimize;
  13654. class Property extends MethodBase {
  13655. //declare method: boolean;
  13656. get method() {
  13657. return isFlagSet(this.flags, 262144 /* Flag.method */);
  13658. }
  13659. set method(value) {
  13660. this.flags = setFlag(this.flags, 262144 /* Flag.method */, value);
  13661. }
  13662. //declare shorthand: boolean;
  13663. get shorthand() {
  13664. return isFlagSet(this.flags, 524288 /* Flag.shorthand */);
  13665. }
  13666. set shorthand(value) {
  13667. this.flags = setFlag(this.flags, 524288 /* Flag.shorthand */, value);
  13668. }
  13669. declare(kind, destructuredInitPath, init) {
  13670. return this.value.declare(kind, this.getPathInProperty(destructuredInitPath), init);
  13671. }
  13672. deoptimizeAssignment(destructuredInitPath, init) {
  13673. this.value.deoptimizeAssignment?.(this.getPathInProperty(destructuredInitPath), init);
  13674. }
  13675. hasEffects(context) {
  13676. return this.key.hasEffects(context) || this.value.hasEffects(context);
  13677. }
  13678. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  13679. return this.value.hasEffectsWhenDestructuring?.(context, this.getPathInProperty(destructuredInitPath), init);
  13680. }
  13681. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  13682. const path = this.getPathInProperty(destructuredInitPath);
  13683. let included = this.value.includeDestructuredIfNecessary(context, path, init) ||
  13684. this.included;
  13685. if ((included ||= this.key.hasEffects(createHasEffectsContext()))) {
  13686. this.key.include(context, false);
  13687. if (!this.value.included) {
  13688. this.value.includeNode(context);
  13689. // Unfortunately, we need to include the value again now, so that any
  13690. // declared variables are properly included.
  13691. this.value.includeDestructuredIfNecessary(context, path, init);
  13692. }
  13693. }
  13694. if (!this.included && included) {
  13695. this.includeNode(context);
  13696. }
  13697. return this.included;
  13698. }
  13699. include(context, includeChildrenRecursively) {
  13700. this.included = true;
  13701. this.key.include(context, includeChildrenRecursively);
  13702. this.value.include(context, includeChildrenRecursively);
  13703. }
  13704. includePath(path, context) {
  13705. this.included = true;
  13706. this.value.includePath(path, context);
  13707. }
  13708. markDeclarationReached() {
  13709. this.value.markDeclarationReached();
  13710. }
  13711. render(code, options) {
  13712. if (!this.shorthand) {
  13713. this.key.render(code, options);
  13714. }
  13715. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  13716. }
  13717. getPathInProperty(destructuredInitPath) {
  13718. return destructuredInitPath.at(-1) === UnknownKey
  13719. ? destructuredInitPath
  13720. : // For now, we only consider static paths as we do not know how to
  13721. // deoptimize the path in the dynamic case.
  13722. this.computed
  13723. ? [...destructuredInitPath, UnknownKey]
  13724. : this.key instanceof Identifier
  13725. ? [...destructuredInitPath, this.key.name]
  13726. : [...destructuredInitPath, String(this.key.value)];
  13727. }
  13728. }
  13729. Property.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13730. Property.prototype.applyDeoptimizations = doNotDeoptimize;
  13731. class PropertyDefinition extends NodeBase {
  13732. get computed() {
  13733. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  13734. }
  13735. set computed(value) {
  13736. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  13737. }
  13738. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13739. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13740. }
  13741. deoptimizePath(path) {
  13742. this.value?.deoptimizePath(path);
  13743. }
  13744. getLiteralValueAtPath(path, recursionTracker, origin) {
  13745. return this.value
  13746. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  13747. : UnknownValue;
  13748. }
  13749. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13750. return this.value
  13751. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  13752. : UNKNOWN_RETURN_EXPRESSION;
  13753. }
  13754. hasEffects(context) {
  13755. return (this.key.hasEffects(context) ||
  13756. (this.static && !!this.value?.hasEffects(context)) ||
  13757. checkEffectForNodes(this.decorators, context));
  13758. }
  13759. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13760. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  13761. }
  13762. includeNode(context) {
  13763. this.included = true;
  13764. this.value?.includePath(UNKNOWN_PATH, context);
  13765. for (const decorator of this.decorators) {
  13766. decorator.includePath(UNKNOWN_PATH, context);
  13767. }
  13768. }
  13769. }
  13770. PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
  13771. class ReturnStatement extends NodeBase {
  13772. hasEffects(context) {
  13773. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  13774. return true;
  13775. context.brokenFlow = true;
  13776. return false;
  13777. }
  13778. include(context, includeChildrenRecursively) {
  13779. if (!this.included)
  13780. this.includeNode(context);
  13781. this.argument?.include(context, includeChildrenRecursively);
  13782. context.brokenFlow = true;
  13783. }
  13784. includeNode(context) {
  13785. this.included = true;
  13786. this.argument?.includePath(UNKNOWN_PATH, context);
  13787. }
  13788. initialise() {
  13789. super.initialise();
  13790. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  13791. }
  13792. render(code, options) {
  13793. if (this.argument) {
  13794. this.argument.render(code, options, { preventASI: true });
  13795. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  13796. code.prependLeft(this.start + 6, ' ');
  13797. }
  13798. }
  13799. }
  13800. }
  13801. ReturnStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13802. class SequenceExpression extends NodeBase {
  13803. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13804. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13805. }
  13806. deoptimizePath(path) {
  13807. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  13808. }
  13809. getLiteralValueAtPath(path, recursionTracker, origin) {
  13810. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  13811. }
  13812. hasEffects(context) {
  13813. for (const expression of this.expressions) {
  13814. if (expression.hasEffects(context))
  13815. return true;
  13816. }
  13817. return false;
  13818. }
  13819. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13820. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  13821. }
  13822. include(context, includeChildrenRecursively) {
  13823. this.included = true;
  13824. const lastExpression = this.expressions[this.expressions.length - 1];
  13825. for (const expression of this.expressions) {
  13826. if (includeChildrenRecursively ||
  13827. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  13828. expression.shouldBeIncluded(context)) {
  13829. expression.include(context, includeChildrenRecursively);
  13830. }
  13831. }
  13832. }
  13833. includePath(path, context) {
  13834. this.included = true;
  13835. this.expressions[this.expressions.length - 1].includePath(path, context);
  13836. }
  13837. removeAnnotations(code) {
  13838. this.expressions[0].removeAnnotations(code);
  13839. }
  13840. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  13841. let includedNodes = 0;
  13842. let lastSeparatorPos = null;
  13843. const lastNode = this.expressions[this.expressions.length - 1];
  13844. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  13845. if (!node.included) {
  13846. treeshakeNode(node, code, start, end);
  13847. continue;
  13848. }
  13849. includedNodes++;
  13850. lastSeparatorPos = separator;
  13851. if (includedNodes === 1 && preventASI) {
  13852. removeLineBreaks(code, start, node.start);
  13853. }
  13854. if (includedNodes === 1) {
  13855. const parentType = renderedParentType || this.parent.type;
  13856. node.render(code, options, {
  13857. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  13858. renderedParentType: parentType,
  13859. renderedSurroundingElement: parentType
  13860. });
  13861. }
  13862. else {
  13863. node.render(code, options);
  13864. }
  13865. }
  13866. if (lastSeparatorPos) {
  13867. code.remove(lastSeparatorPos, this.end);
  13868. }
  13869. }
  13870. }
  13871. SequenceExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13872. SequenceExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13873. class Super extends NodeBase {
  13874. bind() {
  13875. this.variable = this.scope.findVariable('this');
  13876. }
  13877. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13878. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13879. }
  13880. deoptimizePath(path) {
  13881. this.variable.deoptimizePath(path);
  13882. }
  13883. include(context) {
  13884. if (!this.included)
  13885. this.includeNode(context);
  13886. }
  13887. includeNode(context) {
  13888. this.included = true;
  13889. if (!this.deoptimized)
  13890. this.applyDeoptimizations();
  13891. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  13892. }
  13893. }
  13894. class SwitchCase extends NodeBase {
  13895. hasEffects(context) {
  13896. if (this.test?.hasEffects(context))
  13897. return true;
  13898. for (const node of this.consequent) {
  13899. if (context.brokenFlow)
  13900. break;
  13901. if (node.hasEffects(context))
  13902. return true;
  13903. }
  13904. return false;
  13905. }
  13906. include(context, includeChildrenRecursively) {
  13907. this.included = true;
  13908. this.test?.include(context, includeChildrenRecursively);
  13909. for (const node of this.consequent) {
  13910. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  13911. node.include(context, includeChildrenRecursively);
  13912. }
  13913. }
  13914. render(code, options, nodeRenderOptions) {
  13915. if (this.test) {
  13916. this.test.render(code, options);
  13917. if (this.test.start === this.start + 4) {
  13918. code.prependLeft(this.test.start, ' ');
  13919. }
  13920. }
  13921. if (this.consequent.length > 0) {
  13922. const testEnd = this.test
  13923. ? this.test.end
  13924. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  13925. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  13926. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  13927. }
  13928. }
  13929. }
  13930. SwitchCase.prototype.needsBoundaries = true;
  13931. SwitchCase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13932. SwitchCase.prototype.applyDeoptimizations = doNotDeoptimize;
  13933. class SwitchStatement extends NodeBase {
  13934. createScope(parentScope) {
  13935. this.parentScope = parentScope;
  13936. this.scope = new BlockScope(parentScope);
  13937. }
  13938. hasEffects(context) {
  13939. if (this.discriminant.hasEffects(context))
  13940. return true;
  13941. const { brokenFlow, hasBreak, ignore } = context;
  13942. const { breaks } = ignore;
  13943. ignore.breaks = true;
  13944. context.hasBreak = false;
  13945. let onlyHasBrokenFlow = true;
  13946. for (const switchCase of this.cases) {
  13947. if (switchCase.hasEffects(context))
  13948. return true;
  13949. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  13950. context.hasBreak = false;
  13951. context.brokenFlow = brokenFlow;
  13952. }
  13953. if (this.defaultCase !== null) {
  13954. context.brokenFlow = onlyHasBrokenFlow;
  13955. }
  13956. ignore.breaks = breaks;
  13957. context.hasBreak = hasBreak;
  13958. return false;
  13959. }
  13960. include(context, includeChildrenRecursively) {
  13961. this.included = true;
  13962. this.discriminant.include(context, includeChildrenRecursively);
  13963. const { brokenFlow, hasBreak } = context;
  13964. context.hasBreak = false;
  13965. let onlyHasBrokenFlow = true;
  13966. let isCaseIncluded = includeChildrenRecursively ||
  13967. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  13968. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  13969. const switchCase = this.cases[caseIndex];
  13970. if (switchCase.included) {
  13971. isCaseIncluded = true;
  13972. }
  13973. if (!isCaseIncluded) {
  13974. const hasEffectsContext = createHasEffectsContext();
  13975. hasEffectsContext.ignore.breaks = true;
  13976. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  13977. }
  13978. if (isCaseIncluded) {
  13979. switchCase.include(context, includeChildrenRecursively);
  13980. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  13981. context.hasBreak = false;
  13982. context.brokenFlow = brokenFlow;
  13983. }
  13984. else {
  13985. onlyHasBrokenFlow = brokenFlow;
  13986. }
  13987. }
  13988. if (isCaseIncluded && this.defaultCase !== null) {
  13989. context.brokenFlow = onlyHasBrokenFlow;
  13990. }
  13991. context.hasBreak = hasBreak;
  13992. }
  13993. initialise() {
  13994. super.initialise();
  13995. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  13996. if (this.cases[caseIndex].test === null) {
  13997. this.defaultCase = caseIndex;
  13998. return;
  13999. }
  14000. }
  14001. this.defaultCase = null;
  14002. }
  14003. parseNode(esTreeNode) {
  14004. this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
  14005. return super.parseNode(esTreeNode);
  14006. }
  14007. render(code, options) {
  14008. this.discriminant.render(code, options);
  14009. if (this.cases.length > 0) {
  14010. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  14011. }
  14012. }
  14013. }
  14014. SwitchStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14015. SwitchStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14016. class TaggedTemplateExpression extends CallExpressionBase {
  14017. get hasCheckedForWarnings() {
  14018. return isFlagSet(this.flags, 134217728 /* Flag.checkedForWarnings */);
  14019. }
  14020. set hasCheckedForWarnings(value) {
  14021. this.flags = setFlag(this.flags, 134217728 /* Flag.checkedForWarnings */, value);
  14022. }
  14023. bind() {
  14024. super.bind();
  14025. }
  14026. hasEffects(context) {
  14027. if (!this.deoptimized)
  14028. this.applyDeoptimizations();
  14029. for (const argument of this.quasi.expressions) {
  14030. if (argument.hasEffects(context))
  14031. return true;
  14032. }
  14033. return (this.tag.hasEffects(context) ||
  14034. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  14035. }
  14036. include(context, includeChildrenRecursively) {
  14037. if (!this.included)
  14038. this.includeNode(context);
  14039. if (includeChildrenRecursively) {
  14040. super.include(context, true);
  14041. }
  14042. else {
  14043. this.quasi.include(context, false);
  14044. this.tag.include(context, false);
  14045. this.tag.includeCallArguments(this.interaction, context);
  14046. }
  14047. }
  14048. initialise() {
  14049. super.initialise();
  14050. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  14051. this.interaction = {
  14052. args: [
  14053. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  14054. ...this.args
  14055. ],
  14056. type: INTERACTION_CALLED,
  14057. withNew: false
  14058. };
  14059. }
  14060. render(code, options) {
  14061. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  14062. this.quasi.render(code, options);
  14063. if (!this.hasCheckedForWarnings && this.tag.type === Identifier$1) {
  14064. this.hasCheckedForWarnings = true;
  14065. const name = this.tag.name;
  14066. const variable = this.scope.findVariable(name);
  14067. if (variable.isNamespace) {
  14068. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(name), this.start);
  14069. }
  14070. }
  14071. }
  14072. applyDeoptimizations() {
  14073. this.deoptimized = true;
  14074. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  14075. this.scope.context.requestTreeshakingPass();
  14076. }
  14077. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  14078. if (this.returnExpression === null) {
  14079. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  14080. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  14081. }
  14082. return this.returnExpression;
  14083. }
  14084. }
  14085. TaggedTemplateExpression.prototype.includeNode = onlyIncludeSelf;
  14086. class TemplateElement extends NodeBase {
  14087. get tail() {
  14088. return isFlagSet(this.flags, 1048576 /* Flag.tail */);
  14089. }
  14090. set tail(value) {
  14091. this.flags = setFlag(this.flags, 1048576 /* Flag.tail */, value);
  14092. }
  14093. // Do not try to bind value
  14094. bind() { }
  14095. hasEffects() {
  14096. return false;
  14097. }
  14098. parseNode(esTreeNode) {
  14099. this.value = esTreeNode.value;
  14100. return super.parseNode(esTreeNode);
  14101. }
  14102. render() { }
  14103. }
  14104. TemplateElement.prototype.includeNode = onlyIncludeSelf;
  14105. class TemplateLiteral extends NodeBase {
  14106. deoptimizeArgumentsOnInteractionAtPath() { }
  14107. getLiteralValueAtPath(path) {
  14108. if (path.length > 0 || this.quasis.length !== 1) {
  14109. return UnknownValue;
  14110. }
  14111. return this.quasis[0].value.cooked;
  14112. }
  14113. getReturnExpressionWhenCalledAtPath(path) {
  14114. if (path.length !== 1) {
  14115. return UNKNOWN_RETURN_EXPRESSION;
  14116. }
  14117. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  14118. }
  14119. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14120. if (interaction.type === INTERACTION_ACCESSED) {
  14121. return path.length > 1;
  14122. }
  14123. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  14124. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  14125. }
  14126. return true;
  14127. }
  14128. includeNode(context) {
  14129. this.included = true;
  14130. if (!this.deoptimized)
  14131. this.applyDeoptimizations();
  14132. for (const node of this.expressions) {
  14133. node.includePath(UNKNOWN_PATH, context);
  14134. }
  14135. }
  14136. render(code, options) {
  14137. code.indentExclusionRanges.push([this.start, this.end]);
  14138. super.render(code, options);
  14139. }
  14140. }
  14141. class ModuleScope extends ChildScope {
  14142. constructor(parent, context) {
  14143. super(parent, context);
  14144. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, EMPTY_PATH, context, 'other'));
  14145. }
  14146. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  14147. if (this.context.module.importDescriptions.has(identifier.name)) {
  14148. context.error(logRedeclarationError(identifier.name), identifier.start);
  14149. }
  14150. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  14151. }
  14152. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  14153. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  14154. this.variables.set('default', variable);
  14155. return variable;
  14156. }
  14157. addNamespaceMemberAccess() { }
  14158. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  14159. // all module level variables are already deconflicted when deconflicting the chunk
  14160. for (const scope of this.children)
  14161. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  14162. }
  14163. findLexicalBoundary() {
  14164. return this;
  14165. }
  14166. findVariable(name) {
  14167. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  14168. if (knownVariable) {
  14169. return knownVariable;
  14170. }
  14171. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  14172. if (variable instanceof GlobalVariable) {
  14173. this.accessedOutsideVariables.set(name, variable);
  14174. }
  14175. return variable;
  14176. }
  14177. }
  14178. class ThisExpression extends NodeBase {
  14179. bind() {
  14180. this.variable = this.scope.findVariable('this');
  14181. }
  14182. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14183. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14184. }
  14185. deoptimizePath(path) {
  14186. this.variable.deoptimizePath(path);
  14187. }
  14188. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14189. if (path.length === 0) {
  14190. return interaction.type !== INTERACTION_ACCESSED;
  14191. }
  14192. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  14193. }
  14194. include(context) {
  14195. if (!this.included)
  14196. this.includeNode(context);
  14197. }
  14198. includeNode(context) {
  14199. this.included = true;
  14200. if (!this.deoptimized)
  14201. this.applyDeoptimizations();
  14202. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  14203. }
  14204. includePath(path, context) {
  14205. if (!this.included) {
  14206. this.included = true;
  14207. this.scope.context.includeVariableInModule(this.variable, path, context);
  14208. }
  14209. else if (path.length > 0) {
  14210. this.variable.includePath(path, context);
  14211. }
  14212. const functionScope = findFunctionScope(this.scope, this.variable);
  14213. if (functionScope &&
  14214. functionScope.functionNode.parent instanceof Property &&
  14215. functionScope.functionNode.parent.parent instanceof ObjectExpression) {
  14216. functionScope.functionNode.parent.parent.includePath(path, context);
  14217. }
  14218. }
  14219. initialise() {
  14220. super.initialise();
  14221. this.alias =
  14222. this.scope.findLexicalBoundary() instanceof ModuleScope
  14223. ? this.scope.context.moduleContext
  14224. : null;
  14225. if (this.alias === 'undefined') {
  14226. this.scope.context.log(LOGLEVEL_WARN, logThisIsUndefined(), this.start);
  14227. }
  14228. }
  14229. render(code) {
  14230. if (this.alias !== null) {
  14231. code.overwrite(this.start, this.end, this.alias, {
  14232. contentOnly: false,
  14233. storeName: true
  14234. });
  14235. }
  14236. }
  14237. }
  14238. function findFunctionScope(scope, thisVariable) {
  14239. while (!(scope instanceof FunctionScope && scope.thisVariable === thisVariable)) {
  14240. if (!(scope instanceof ChildScope)) {
  14241. return null;
  14242. }
  14243. scope = scope.parent;
  14244. }
  14245. return scope;
  14246. }
  14247. class ThrowStatement extends NodeBase {
  14248. hasEffects() {
  14249. return true;
  14250. }
  14251. include(context, includeChildrenRecursively) {
  14252. if (!this.included)
  14253. this.includeNode(context);
  14254. this.argument.include(context, includeChildrenRecursively);
  14255. context.brokenFlow = true;
  14256. }
  14257. includeNode(context) {
  14258. if (!this.included) {
  14259. this.included = true;
  14260. this.argument.includePath(UNKNOWN_PATH, context);
  14261. }
  14262. }
  14263. render(code, options) {
  14264. this.argument.render(code, options, { preventASI: true });
  14265. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  14266. code.prependLeft(this.start + 5, ' ');
  14267. }
  14268. }
  14269. }
  14270. class TryStatement extends NodeBase {
  14271. constructor() {
  14272. super(...arguments);
  14273. this.directlyIncluded = false;
  14274. this.includedLabelsAfterBlock = null;
  14275. }
  14276. hasEffects(context) {
  14277. return ((this.scope.context.options.treeshake.tryCatchDeoptimization
  14278. ? this.block.body.length > 0
  14279. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  14280. }
  14281. include(context, includeChildrenRecursively) {
  14282. const tryCatchDeoptimization = this.scope.context.options.treeshake?.tryCatchDeoptimization;
  14283. const { brokenFlow, includedLabels } = context;
  14284. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  14285. this.included = true;
  14286. this.directlyIncluded = true;
  14287. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  14288. if (includedLabels.size > 0) {
  14289. this.includedLabelsAfterBlock = [...includedLabels];
  14290. }
  14291. context.brokenFlow = brokenFlow;
  14292. }
  14293. else if (this.includedLabelsAfterBlock) {
  14294. for (const label of this.includedLabelsAfterBlock) {
  14295. includedLabels.add(label);
  14296. }
  14297. }
  14298. if (this.handler !== null) {
  14299. this.handler.include(context, includeChildrenRecursively);
  14300. context.brokenFlow = brokenFlow;
  14301. }
  14302. this.finalizer?.include(context, includeChildrenRecursively);
  14303. }
  14304. }
  14305. TryStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14306. TryStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14307. const unaryOperators = {
  14308. '!': value => !value,
  14309. '+': value => +value,
  14310. '-': value => -value,
  14311. delete: () => UnknownValue,
  14312. typeof: value => typeof value,
  14313. void: () => undefined,
  14314. '~': value => ~value
  14315. };
  14316. const UNASSIGNED = Symbol('Unassigned');
  14317. class UnaryExpression extends NodeBase {
  14318. constructor() {
  14319. super(...arguments);
  14320. this.renderedLiteralValue = UNASSIGNED;
  14321. }
  14322. get prefix() {
  14323. return isFlagSet(this.flags, 2097152 /* Flag.prefix */);
  14324. }
  14325. set prefix(value) {
  14326. this.flags = setFlag(this.flags, 2097152 /* Flag.prefix */, value);
  14327. }
  14328. deoptimizeCache() {
  14329. this.renderedLiteralValue = UnknownValue;
  14330. }
  14331. getLiteralValueAtPath(path, recursionTracker, origin) {
  14332. if (path.length > 0)
  14333. return UnknownValue;
  14334. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  14335. if (typeof argumentValue === 'symbol') {
  14336. if (this.operator === 'void')
  14337. return undefined;
  14338. if (this.operator === '!') {
  14339. if (argumentValue === UnknownFalsyValue)
  14340. return true;
  14341. if (argumentValue === UnknownTruthyValue)
  14342. return false;
  14343. }
  14344. return UnknownValue;
  14345. }
  14346. return unaryOperators[this.operator](argumentValue);
  14347. }
  14348. hasEffects(context) {
  14349. if (!this.deoptimized)
  14350. this.applyDeoptimizations();
  14351. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  14352. return false;
  14353. return (this.argument.hasEffects(context) ||
  14354. (this.operator === 'delete' &&
  14355. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  14356. }
  14357. hasEffectsOnInteractionAtPath(path, { type }) {
  14358. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  14359. }
  14360. applyDeoptimizations() {
  14361. this.deoptimized = true;
  14362. if (this.operator === 'delete') {
  14363. this.argument.deoptimizePath(EMPTY_PATH);
  14364. this.scope.context.requestTreeshakingPass();
  14365. }
  14366. }
  14367. getRenderedLiteralValue(includeChildrenRecursively) {
  14368. if (this.renderedLiteralValue !== UNASSIGNED)
  14369. return this.renderedLiteralValue;
  14370. return (this.renderedLiteralValue = includeChildrenRecursively
  14371. ? UnknownValue
  14372. : getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  14373. }
  14374. include(context, includeChildrenRecursively, _options) {
  14375. if (!this.deoptimized)
  14376. this.applyDeoptimizations();
  14377. this.included = true;
  14378. // Check if the argument is an identifier that should be preserved as a reference for readability
  14379. const shouldPreserveArgument = this.argument instanceof Identifier && this.argument.variable?.included;
  14380. if (typeof this.getRenderedLiteralValue(includeChildrenRecursively) === 'symbol' ||
  14381. this.argument.shouldBeIncluded(context) ||
  14382. shouldPreserveArgument) {
  14383. this.argument.include(context, includeChildrenRecursively);
  14384. this.renderedLiteralValue = UnknownValue;
  14385. }
  14386. }
  14387. render(code, options) {
  14388. if (typeof this.renderedLiteralValue === 'symbol') {
  14389. super.render(code, options);
  14390. }
  14391. else {
  14392. let value = this.renderedLiteralValue;
  14393. if (!CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE.test(code.original[this.start - 1])) {
  14394. value = ` ${value}`;
  14395. }
  14396. code.overwrite(this.start, this.end, value);
  14397. }
  14398. }
  14399. }
  14400. const CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE = /[\s([=%&*+-/<>^|,?:;]/;
  14401. UnaryExpression.prototype.includeNode = onlyIncludeSelf;
  14402. class UpdateExpression extends NodeBase {
  14403. hasEffects(context) {
  14404. if (!this.deoptimized)
  14405. this.applyDeoptimizations();
  14406. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  14407. }
  14408. hasEffectsOnInteractionAtPath(path, { type }) {
  14409. return path.length > 1 || type !== INTERACTION_ACCESSED;
  14410. }
  14411. include(context, includeChildrenRecursively) {
  14412. if (!this.included)
  14413. this.includeNode(context);
  14414. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  14415. }
  14416. initialise() {
  14417. super.initialise();
  14418. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  14419. }
  14420. render(code, options) {
  14421. const { exportNamesByVariable, format, snippets: { _ } } = options;
  14422. this.argument.render(code, options);
  14423. if (format === 'system') {
  14424. const variable = this.argument.variable;
  14425. const exportNames = exportNamesByVariable.get(variable);
  14426. if (exportNames) {
  14427. if (this.prefix) {
  14428. if (exportNames.length === 1) {
  14429. renderSystemExportExpression(variable, this.start, this.end, code, options);
  14430. }
  14431. else {
  14432. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  14433. }
  14434. }
  14435. else {
  14436. const operator = this.operator[0];
  14437. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  14438. }
  14439. }
  14440. }
  14441. }
  14442. applyDeoptimizations() {
  14443. this.deoptimized = true;
  14444. this.argument.deoptimizePath(EMPTY_PATH);
  14445. if (this.argument instanceof Identifier) {
  14446. const variable = this.scope.findVariable(this.argument.name);
  14447. variable.markReassigned();
  14448. }
  14449. this.scope.context.requestTreeshakingPass();
  14450. }
  14451. }
  14452. UpdateExpression.prototype.includeNode = onlyIncludeSelf;
  14453. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  14454. for (const declarator of declarations) {
  14455. if (!declarator.id.included)
  14456. return false;
  14457. if (declarator.id.type === Identifier$1) {
  14458. if (exportNamesByVariable.has(declarator.id.variable))
  14459. return false;
  14460. }
  14461. else {
  14462. const exportedVariables = [];
  14463. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  14464. if (exportedVariables.length > 0)
  14465. return false;
  14466. }
  14467. }
  14468. return true;
  14469. }
  14470. class VariableDeclaration extends NodeBase {
  14471. deoptimizePath() {
  14472. for (const declarator of this.declarations) {
  14473. declarator.deoptimizePath(EMPTY_PATH);
  14474. }
  14475. }
  14476. hasEffectsOnInteractionAtPath() {
  14477. return false;
  14478. }
  14479. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  14480. this.included = true;
  14481. for (const declarator of this.declarations) {
  14482. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  14483. declarator.include(context, includeChildrenRecursively);
  14484. }
  14485. const { id, init } = declarator;
  14486. if (asSingleStatement) {
  14487. id.include(context, includeChildrenRecursively);
  14488. }
  14489. if (init &&
  14490. id.included &&
  14491. !init.included &&
  14492. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  14493. init.include(context, includeChildrenRecursively);
  14494. }
  14495. }
  14496. }
  14497. initialise() {
  14498. super.initialise();
  14499. this.isUsingDeclaration = this.kind === 'await using' || this.kind === 'using';
  14500. for (const declarator of this.declarations) {
  14501. declarator.declareDeclarator(this.kind, this.isUsingDeclaration);
  14502. }
  14503. }
  14504. removeAnnotations(code) {
  14505. this.declarations[0].removeAnnotations(code);
  14506. }
  14507. render(code, options, nodeRenderOptions = BLANK) {
  14508. if (this.isUsingDeclaration ||
  14509. areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  14510. for (const declarator of this.declarations) {
  14511. declarator.render(code, options);
  14512. }
  14513. if (!nodeRenderOptions.isNoStatement &&
  14514. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  14515. code.appendLeft(this.end, ';');
  14516. }
  14517. }
  14518. else {
  14519. this.renderReplacedDeclarations(code, options);
  14520. }
  14521. }
  14522. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  14523. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  14524. code.remove(this.end - 1, this.end);
  14525. }
  14526. separatorString += ';';
  14527. if (lastSeparatorPos === null) {
  14528. code.appendLeft(renderedContentEnd, separatorString);
  14529. }
  14530. else {
  14531. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  14532. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  14533. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  14534. actualContentEnd--;
  14535. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  14536. actualContentEnd--;
  14537. }
  14538. }
  14539. if (actualContentEnd === lastSeparatorPos + 1) {
  14540. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  14541. }
  14542. else {
  14543. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  14544. code.remove(actualContentEnd, renderedContentEnd);
  14545. }
  14546. }
  14547. if (systemPatternExports.length > 0) {
  14548. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  14549. }
  14550. }
  14551. renderReplacedDeclarations(code, options) {
  14552. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  14553. let actualContentEnd, renderedContentEnd;
  14554. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  14555. let lastSeparatorPos = renderedContentEnd - 1;
  14556. code.remove(this.start, lastSeparatorPos);
  14557. let isInDeclaration = false;
  14558. let hasRenderedContent = false;
  14559. let separatorString = '', leadingString, nextSeparatorString;
  14560. const aggregatedSystemExports = [];
  14561. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  14562. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  14563. if (!node.included) {
  14564. treeshakeNode(node, code, start, end);
  14565. continue;
  14566. }
  14567. node.render(code, options);
  14568. leadingString = '';
  14569. nextSeparatorString = '';
  14570. if (!node.id.included ||
  14571. (node.id instanceof Identifier &&
  14572. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  14573. if (hasRenderedContent) {
  14574. separatorString += ';';
  14575. }
  14576. isInDeclaration = false;
  14577. }
  14578. else {
  14579. if (singleSystemExport && singleSystemExport === node.id.variable) {
  14580. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  14581. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  14582. }
  14583. if (isInDeclaration) {
  14584. separatorString += ',';
  14585. }
  14586. else {
  14587. if (hasRenderedContent) {
  14588. separatorString += ';';
  14589. }
  14590. leadingString += `${this.kind} `;
  14591. isInDeclaration = true;
  14592. }
  14593. }
  14594. if (renderedContentEnd === lastSeparatorPos + 1) {
  14595. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  14596. }
  14597. else {
  14598. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  14599. code.appendLeft(renderedContentEnd, leadingString);
  14600. }
  14601. actualContentEnd = contentEnd;
  14602. renderedContentEnd = end;
  14603. hasRenderedContent = true;
  14604. lastSeparatorPos = separator;
  14605. separatorString = nextSeparatorString;
  14606. }
  14607. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  14608. }
  14609. }
  14610. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  14611. let singleSystemExport = null;
  14612. if (options.format === 'system') {
  14613. for (const { node } of separatedNodes) {
  14614. if (node.id instanceof Identifier &&
  14615. node.init &&
  14616. aggregatedSystemExports.length === 0 &&
  14617. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  14618. singleSystemExport = node.id.variable;
  14619. aggregatedSystemExports.push(singleSystemExport);
  14620. }
  14621. else {
  14622. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  14623. }
  14624. }
  14625. if (aggregatedSystemExports.length > 1) {
  14626. singleSystemExport = null;
  14627. }
  14628. else if (singleSystemExport) {
  14629. aggregatedSystemExports.length = 0;
  14630. }
  14631. }
  14632. return singleSystemExport;
  14633. }
  14634. VariableDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14635. VariableDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  14636. class WhileStatement extends NodeBase {
  14637. hasEffects(context) {
  14638. if (this.test.hasEffects(context))
  14639. return true;
  14640. return hasLoopBodyEffects(context, this.body);
  14641. }
  14642. include(context, includeChildrenRecursively) {
  14643. this.included = true;
  14644. this.test.include(context, includeChildrenRecursively);
  14645. includeLoopBody(context, this.body, includeChildrenRecursively);
  14646. }
  14647. }
  14648. WhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14649. WhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14650. class YieldExpression extends NodeBase {
  14651. applyDeoptimizations() {
  14652. this.deoptimized = true;
  14653. this.argument?.deoptimizePath(UNKNOWN_PATH);
  14654. }
  14655. hasEffects(context) {
  14656. if (!this.deoptimized)
  14657. this.applyDeoptimizations();
  14658. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  14659. }
  14660. includeNode(context) {
  14661. this.included = true;
  14662. if (!this.deoptimized)
  14663. this.applyDeoptimizations();
  14664. this.argument?.includePath(UNKNOWN_PATH, context);
  14665. }
  14666. render(code, options) {
  14667. if (this.argument) {
  14668. this.argument.render(code, options, { preventASI: true });
  14669. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  14670. code.prependLeft(this.start + 5, ' ');
  14671. }
  14672. }
  14673. }
  14674. }
  14675. // This file is generated by scripts/generate-buffer-parsers.js.
  14676. // Do not edit this file directly.
  14677. function convertProgram(buffer, parent, parentScope) {
  14678. return convertNode(parent, parentScope, 0, getAstBuffer(buffer));
  14679. }
  14680. const nodeTypeStrings = [
  14681. 'PanicError',
  14682. 'ParseError',
  14683. 'ArrayExpression',
  14684. 'ArrayPattern',
  14685. 'ArrowFunctionExpression',
  14686. 'AssignmentExpression',
  14687. 'AssignmentPattern',
  14688. 'AwaitExpression',
  14689. 'BinaryExpression',
  14690. 'BlockStatement',
  14691. 'BreakStatement',
  14692. 'CallExpression',
  14693. 'CatchClause',
  14694. 'ChainExpression',
  14695. 'ClassBody',
  14696. 'ClassDeclaration',
  14697. 'ClassExpression',
  14698. 'ConditionalExpression',
  14699. 'ContinueStatement',
  14700. 'DebuggerStatement',
  14701. 'Decorator',
  14702. 'ExpressionStatement',
  14703. 'DoWhileStatement',
  14704. 'EmptyStatement',
  14705. 'ExportAllDeclaration',
  14706. 'ExportDefaultDeclaration',
  14707. 'ExportNamedDeclaration',
  14708. 'ExportSpecifier',
  14709. 'ExpressionStatement',
  14710. 'ForInStatement',
  14711. 'ForOfStatement',
  14712. 'ForStatement',
  14713. 'FunctionDeclaration',
  14714. 'FunctionExpression',
  14715. 'Identifier',
  14716. 'IfStatement',
  14717. 'ImportAttribute',
  14718. 'ImportDeclaration',
  14719. 'ImportDefaultSpecifier',
  14720. 'ImportExpression',
  14721. 'ImportNamespaceSpecifier',
  14722. 'ImportSpecifier',
  14723. 'JSXAttribute',
  14724. 'JSXClosingElement',
  14725. 'JSXClosingFragment',
  14726. 'JSXElement',
  14727. 'JSXEmptyExpression',
  14728. 'JSXExpressionContainer',
  14729. 'JSXFragment',
  14730. 'JSXIdentifier',
  14731. 'JSXMemberExpression',
  14732. 'JSXNamespacedName',
  14733. 'JSXOpeningElement',
  14734. 'JSXOpeningFragment',
  14735. 'JSXSpreadAttribute',
  14736. 'JSXSpreadChild',
  14737. 'JSXText',
  14738. 'LabeledStatement',
  14739. 'Literal',
  14740. 'Literal',
  14741. 'Literal',
  14742. 'Literal',
  14743. 'Literal',
  14744. 'Literal',
  14745. 'LogicalExpression',
  14746. 'MemberExpression',
  14747. 'MetaProperty',
  14748. 'MethodDefinition',
  14749. 'NewExpression',
  14750. 'ObjectExpression',
  14751. 'ObjectPattern',
  14752. 'PrivateIdentifier',
  14753. 'Program',
  14754. 'Property',
  14755. 'PropertyDefinition',
  14756. 'RestElement',
  14757. 'ReturnStatement',
  14758. 'SequenceExpression',
  14759. 'SpreadElement',
  14760. 'StaticBlock',
  14761. 'Super',
  14762. 'SwitchCase',
  14763. 'SwitchStatement',
  14764. 'TaggedTemplateExpression',
  14765. 'TemplateElement',
  14766. 'TemplateLiteral',
  14767. 'ThisExpression',
  14768. 'ThrowStatement',
  14769. 'TryStatement',
  14770. 'UnaryExpression',
  14771. 'UpdateExpression',
  14772. 'VariableDeclaration',
  14773. 'VariableDeclarator',
  14774. 'WhileStatement',
  14775. 'YieldExpression'
  14776. ];
  14777. const nodeConstructors$1 = [
  14778. PanicError,
  14779. ParseError,
  14780. ArrayExpression,
  14781. ArrayPattern,
  14782. ArrowFunctionExpression,
  14783. AssignmentExpression,
  14784. AssignmentPattern,
  14785. AwaitExpression,
  14786. BinaryExpression,
  14787. BlockStatement,
  14788. BreakStatement,
  14789. CallExpression,
  14790. CatchClause,
  14791. ChainExpression,
  14792. ClassBody,
  14793. ClassDeclaration,
  14794. ClassExpression,
  14795. ConditionalExpression,
  14796. ContinueStatement,
  14797. DebuggerStatement,
  14798. Decorator,
  14799. ExpressionStatement,
  14800. DoWhileStatement,
  14801. EmptyStatement,
  14802. ExportAllDeclaration,
  14803. ExportDefaultDeclaration,
  14804. ExportNamedDeclaration,
  14805. ExportSpecifier,
  14806. ExpressionStatement,
  14807. ForInStatement,
  14808. ForOfStatement,
  14809. ForStatement,
  14810. FunctionDeclaration,
  14811. FunctionExpression,
  14812. Identifier,
  14813. IfStatement,
  14814. ImportAttribute,
  14815. ImportDeclaration,
  14816. ImportDefaultSpecifier,
  14817. ImportExpression,
  14818. ImportNamespaceSpecifier,
  14819. ImportSpecifier,
  14820. JSXAttribute,
  14821. JSXClosingElement,
  14822. JSXClosingFragment,
  14823. JSXElement,
  14824. JSXEmptyExpression,
  14825. JSXExpressionContainer,
  14826. JSXFragment,
  14827. JSXIdentifier,
  14828. JSXMemberExpression,
  14829. JSXNamespacedName,
  14830. JSXOpeningElement,
  14831. JSXOpeningFragment,
  14832. JSXSpreadAttribute,
  14833. JSXSpreadChild,
  14834. JSXText,
  14835. LabeledStatement,
  14836. Literal,
  14837. Literal,
  14838. Literal,
  14839. Literal,
  14840. Literal,
  14841. Literal,
  14842. LogicalExpression,
  14843. MemberExpression,
  14844. MetaProperty,
  14845. MethodDefinition,
  14846. NewExpression,
  14847. ObjectExpression,
  14848. ObjectPattern,
  14849. PrivateIdentifier,
  14850. Program,
  14851. Property,
  14852. PropertyDefinition,
  14853. RestElement,
  14854. ReturnStatement,
  14855. SequenceExpression,
  14856. SpreadElement,
  14857. StaticBlock,
  14858. Super,
  14859. SwitchCase,
  14860. SwitchStatement,
  14861. TaggedTemplateExpression,
  14862. TemplateElement,
  14863. TemplateLiteral,
  14864. ThisExpression,
  14865. ThrowStatement,
  14866. TryStatement,
  14867. UnaryExpression,
  14868. UpdateExpression,
  14869. VariableDeclaration,
  14870. VariableDeclarator,
  14871. WhileStatement,
  14872. YieldExpression
  14873. ];
  14874. const bufferParsers = [
  14875. function panicError(node, position, buffer) {
  14876. node.message = buffer.convertString(buffer[position]);
  14877. },
  14878. function parseError(node, position, buffer) {
  14879. node.message = buffer.convertString(buffer[position]);
  14880. },
  14881. function arrayExpression(node, position, buffer) {
  14882. const { scope } = node;
  14883. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  14884. },
  14885. function arrayPattern(node, position, buffer) {
  14886. const { scope } = node;
  14887. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  14888. },
  14889. function arrowFunctionExpression(node, position, buffer) {
  14890. const { scope } = node;
  14891. const flags = buffer[position];
  14892. node.async = (flags & 1) === 1;
  14893. node.expression = (flags & 2) === 2;
  14894. node.generator = (flags & 4) === 4;
  14895. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  14896. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  14897. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 2], buffer));
  14898. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  14899. node.body = convertNode(node, scope.bodyScope, buffer[position + 3], buffer);
  14900. },
  14901. function assignmentExpression(node, position, buffer) {
  14902. const { scope } = node;
  14903. node.operator = FIXED_STRINGS[buffer[position]];
  14904. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  14905. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  14906. },
  14907. function assignmentPattern(node, position, buffer) {
  14908. const { scope } = node;
  14909. node.left = convertNode(node, scope, buffer[position], buffer);
  14910. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  14911. },
  14912. function awaitExpression(node, position, buffer) {
  14913. const { scope } = node;
  14914. node.argument = convertNode(node, scope, buffer[position], buffer);
  14915. },
  14916. function binaryExpression(node, position, buffer) {
  14917. const { scope } = node;
  14918. node.operator = FIXED_STRINGS[buffer[position]];
  14919. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  14920. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  14921. },
  14922. function blockStatement(node, position, buffer) {
  14923. const { scope } = node;
  14924. node.body = convertNodeList(node, scope, buffer[position], buffer);
  14925. },
  14926. function breakStatement(node, position, buffer) {
  14927. const { scope } = node;
  14928. const labelPosition = buffer[position];
  14929. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  14930. },
  14931. function callExpression(node, position, buffer) {
  14932. const { scope } = node;
  14933. const flags = buffer[position];
  14934. node.optional = (flags & 1) === 1;
  14935. node.annotations = convertAnnotations(buffer[position + 1], buffer);
  14936. node.callee = convertNode(node, scope, buffer[position + 2], buffer);
  14937. node.arguments = convertNodeList(node, scope, buffer[position + 3], buffer);
  14938. },
  14939. function catchClause(node, position, buffer) {
  14940. const { scope } = node;
  14941. const parameterPosition = buffer[position];
  14942. const parameter = (node.param =
  14943. parameterPosition === 0 ? null : convertNode(node, scope, parameterPosition, buffer));
  14944. parameter?.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  14945. node.body = convertNode(node, scope.bodyScope, buffer[position + 1], buffer);
  14946. },
  14947. function chainExpression(node, position, buffer) {
  14948. const { scope } = node;
  14949. node.expression = convertNode(node, scope, buffer[position], buffer);
  14950. },
  14951. function classBody(node, position, buffer) {
  14952. const { scope } = node;
  14953. const bodyPosition = buffer[position];
  14954. if (bodyPosition) {
  14955. const length = buffer[bodyPosition];
  14956. const body = (node.body = new Array(length));
  14957. for (let index = 0; index < length; index++) {
  14958. const nodePosition = buffer[bodyPosition + 1 + index];
  14959. body[index] = convertNode(node, buffer[nodePosition] !== 79 &&
  14960. (buffer[nodePosition + 3] & /* the static flag is always first */ 1) === 0
  14961. ? scope.instanceScope
  14962. : scope, nodePosition, buffer);
  14963. }
  14964. }
  14965. else {
  14966. node.body = [];
  14967. }
  14968. },
  14969. function classDeclaration(node, position, buffer) {
  14970. const { scope } = node;
  14971. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  14972. const idPosition = buffer[position + 1];
  14973. node.id =
  14974. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  14975. const superClassPosition = buffer[position + 2];
  14976. node.superClass =
  14977. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  14978. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  14979. },
  14980. function classExpression(node, position, buffer) {
  14981. const { scope } = node;
  14982. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  14983. const idPosition = buffer[position + 1];
  14984. node.id = idPosition === 0 ? null : convertNode(node, scope, idPosition, buffer);
  14985. const superClassPosition = buffer[position + 2];
  14986. node.superClass =
  14987. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  14988. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  14989. },
  14990. function conditionalExpression(node, position, buffer) {
  14991. const { scope } = node;
  14992. node.test = convertNode(node, scope, buffer[position], buffer);
  14993. node.consequent = convertNode(node, scope, buffer[position + 1], buffer);
  14994. node.alternate = convertNode(node, scope, buffer[position + 2], buffer);
  14995. },
  14996. function continueStatement(node, position, buffer) {
  14997. const { scope } = node;
  14998. const labelPosition = buffer[position];
  14999. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  15000. },
  15001. function debuggerStatement() { },
  15002. function decorator(node, position, buffer) {
  15003. const { scope } = node;
  15004. node.expression = convertNode(node, scope, buffer[position], buffer);
  15005. },
  15006. function directive(node, position, buffer) {
  15007. const { scope } = node;
  15008. node.directive = buffer.convertString(buffer[position]);
  15009. node.expression = convertNode(node, scope, buffer[position + 1], buffer);
  15010. },
  15011. function doWhileStatement(node, position, buffer) {
  15012. const { scope } = node;
  15013. node.body = convertNode(node, scope, buffer[position], buffer);
  15014. node.test = convertNode(node, scope, buffer[position + 1], buffer);
  15015. },
  15016. function emptyStatement() { },
  15017. function exportAllDeclaration(node, position, buffer) {
  15018. const { scope } = node;
  15019. const exportedPosition = buffer[position];
  15020. node.exported =
  15021. exportedPosition === 0 ? null : convertNode(node, scope, exportedPosition, buffer);
  15022. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  15023. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15024. },
  15025. function exportDefaultDeclaration(node, position, buffer) {
  15026. const { scope } = node;
  15027. node.declaration = convertNode(node, scope, buffer[position], buffer);
  15028. },
  15029. function exportNamedDeclaration(node, position, buffer) {
  15030. const { scope } = node;
  15031. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  15032. const sourcePosition = buffer[position + 1];
  15033. node.source = sourcePosition === 0 ? null : convertNode(node, scope, sourcePosition, buffer);
  15034. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15035. const declarationPosition = buffer[position + 3];
  15036. node.declaration =
  15037. declarationPosition === 0 ? null : convertNode(node, scope, declarationPosition, buffer);
  15038. },
  15039. function exportSpecifier(node, position, buffer) {
  15040. const { scope } = node;
  15041. node.local = convertNode(node, scope, buffer[position], buffer);
  15042. const exportedPosition = buffer[position + 1];
  15043. node.exported =
  15044. exportedPosition === 0 ? node.local : convertNode(node, scope, exportedPosition, buffer);
  15045. },
  15046. function expressionStatement(node, position, buffer) {
  15047. const { scope } = node;
  15048. node.expression = convertNode(node, scope, buffer[position], buffer);
  15049. },
  15050. function forInStatement(node, position, buffer) {
  15051. const { scope } = node;
  15052. node.left = convertNode(node, scope, buffer[position], buffer);
  15053. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  15054. node.body = convertNode(node, scope, buffer[position + 2], buffer);
  15055. },
  15056. function forOfStatement(node, position, buffer) {
  15057. const { scope } = node;
  15058. const flags = buffer[position];
  15059. node.await = (flags & 1) === 1;
  15060. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15061. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15062. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  15063. },
  15064. function forStatement(node, position, buffer) {
  15065. const { scope } = node;
  15066. const initPosition = buffer[position];
  15067. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  15068. const testPosition = buffer[position + 1];
  15069. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  15070. const updatePosition = buffer[position + 2];
  15071. node.update = updatePosition === 0 ? null : convertNode(node, scope, updatePosition, buffer);
  15072. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  15073. },
  15074. function functionDeclaration(node, position, buffer) {
  15075. const { scope } = node;
  15076. const flags = buffer[position];
  15077. node.async = (flags & 1) === 1;
  15078. node.generator = (flags & 2) === 2;
  15079. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  15080. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  15081. const idPosition = buffer[position + 2];
  15082. node.id =
  15083. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  15084. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  15085. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  15086. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  15087. },
  15088. function functionExpression(node, position, buffer) {
  15089. const { scope } = node;
  15090. const flags = buffer[position];
  15091. node.async = (flags & 1) === 1;
  15092. node.generator = (flags & 2) === 2;
  15093. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  15094. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  15095. const idPosition = buffer[position + 2];
  15096. node.id = idPosition === 0 ? null : convertNode(node, node.idScope, idPosition, buffer);
  15097. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  15098. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  15099. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  15100. },
  15101. function identifier(node, position, buffer) {
  15102. node.name = buffer.convertString(buffer[position]);
  15103. },
  15104. function ifStatement(node, position, buffer) {
  15105. const { scope } = node;
  15106. node.test = convertNode(node, scope, buffer[position], buffer);
  15107. node.consequent = convertNode(node, (node.consequentScope = new TrackingScope(scope)), buffer[position + 1], buffer);
  15108. const alternatePosition = buffer[position + 2];
  15109. node.alternate =
  15110. alternatePosition === 0
  15111. ? null
  15112. : convertNode(node, (node.alternateScope = new TrackingScope(scope)), alternatePosition, buffer);
  15113. },
  15114. function importAttribute(node, position, buffer) {
  15115. const { scope } = node;
  15116. node.key = convertNode(node, scope, buffer[position], buffer);
  15117. node.value = convertNode(node, scope, buffer[position + 1], buffer);
  15118. },
  15119. function importDeclaration(node, position, buffer) {
  15120. const { scope } = node;
  15121. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  15122. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  15123. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15124. },
  15125. function importDefaultSpecifier(node, position, buffer) {
  15126. const { scope } = node;
  15127. node.local = convertNode(node, scope, buffer[position], buffer);
  15128. },
  15129. function importExpression(node, position, buffer) {
  15130. const { scope } = node;
  15131. node.source = convertNode(node, scope, buffer[position], buffer);
  15132. node.sourceAstNode = convertNode$1(buffer[position], buffer);
  15133. const optionsPosition = buffer[position + 1];
  15134. node.options = optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer);
  15135. },
  15136. function importNamespaceSpecifier(node, position, buffer) {
  15137. const { scope } = node;
  15138. node.local = convertNode(node, scope, buffer[position], buffer);
  15139. },
  15140. function importSpecifier(node, position, buffer) {
  15141. const { scope } = node;
  15142. const importedPosition = buffer[position];
  15143. node.local = convertNode(node, scope, buffer[position + 1], buffer);
  15144. node.imported =
  15145. importedPosition === 0 ? node.local : convertNode(node, scope, importedPosition, buffer);
  15146. },
  15147. function jsxAttribute(node, position, buffer) {
  15148. const { scope } = node;
  15149. node.name = convertNode(node, scope, buffer[position], buffer);
  15150. const valuePosition = buffer[position + 1];
  15151. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  15152. },
  15153. function jsxClosingElement(node, position, buffer) {
  15154. const { scope } = node;
  15155. node.name = convertNode(node, scope, buffer[position], buffer);
  15156. },
  15157. function jsxClosingFragment() { },
  15158. function jsxElement(node, position, buffer) {
  15159. const { scope } = node;
  15160. node.openingElement = convertNode(node, scope, buffer[position], buffer);
  15161. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  15162. const closingElementPosition = buffer[position + 2];
  15163. node.closingElement =
  15164. closingElementPosition === 0
  15165. ? null
  15166. : convertNode(node, scope, closingElementPosition, buffer);
  15167. },
  15168. function jsxEmptyExpression() { },
  15169. function jsxExpressionContainer(node, position, buffer) {
  15170. const { scope } = node;
  15171. node.expression = convertNode(node, scope, buffer[position], buffer);
  15172. },
  15173. function jsxFragment(node, position, buffer) {
  15174. const { scope } = node;
  15175. node.openingFragment = convertNode(node, scope, buffer[position], buffer);
  15176. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  15177. node.closingFragment = convertNode(node, scope, buffer[position + 2], buffer);
  15178. },
  15179. function jsxIdentifier(node, position, buffer) {
  15180. node.name = buffer.convertString(buffer[position]);
  15181. },
  15182. function jsxMemberExpression(node, position, buffer) {
  15183. const { scope } = node;
  15184. node.object = convertNode(node, scope, buffer[position], buffer);
  15185. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  15186. },
  15187. function jsxNamespacedName(node, position, buffer) {
  15188. const { scope } = node;
  15189. node.namespace = convertNode(node, scope, buffer[position], buffer);
  15190. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  15191. },
  15192. function jsxOpeningElement(node, position, buffer) {
  15193. const { scope } = node;
  15194. const flags = buffer[position];
  15195. node.selfClosing = (flags & 1) === 1;
  15196. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  15197. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15198. },
  15199. function jsxOpeningFragment(node) {
  15200. node.attributes = [];
  15201. node.selfClosing = false;
  15202. },
  15203. function jsxSpreadAttribute(node, position, buffer) {
  15204. const { scope } = node;
  15205. node.argument = convertNode(node, scope, buffer[position], buffer);
  15206. },
  15207. function jsxSpreadChild(node, position, buffer) {
  15208. const { scope } = node;
  15209. node.expression = convertNode(node, scope, buffer[position], buffer);
  15210. },
  15211. function jsxText(node, position, buffer) {
  15212. node.value = buffer.convertString(buffer[position]);
  15213. node.raw = buffer.convertString(buffer[position + 1]);
  15214. },
  15215. function labeledStatement(node, position, buffer) {
  15216. const { scope } = node;
  15217. node.label = convertNode(node, scope, buffer[position], buffer);
  15218. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  15219. },
  15220. function literalBigInt(node, position, buffer) {
  15221. const bigint = (node.bigint = buffer.convertString(buffer[position]));
  15222. node.raw = buffer.convertString(buffer[position + 1]);
  15223. node.value = BigInt(bigint);
  15224. },
  15225. function literalBoolean(node, position, buffer) {
  15226. const flags = buffer[position];
  15227. const value = (node.value = (flags & 1) === 1);
  15228. node.raw = value ? 'true' : 'false';
  15229. },
  15230. function literalNull(node) {
  15231. node.value = null;
  15232. },
  15233. function literalNumber(node, position, buffer) {
  15234. const rawPosition = buffer[position];
  15235. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  15236. node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
  15237. },
  15238. function literalRegExp(node, position, buffer) {
  15239. const flags = buffer.convertString(buffer[position]);
  15240. const pattern = buffer.convertString(buffer[position + 1]);
  15241. node.raw = `/${pattern}/${flags}`;
  15242. node.regex = { flags, pattern };
  15243. node.value = new RegExp(pattern, flags);
  15244. },
  15245. function literalString(node, position, buffer) {
  15246. node.value = buffer.convertString(buffer[position]);
  15247. const rawPosition = buffer[position + 1];
  15248. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  15249. },
  15250. function logicalExpression(node, position, buffer) {
  15251. const { scope } = node;
  15252. node.operator = FIXED_STRINGS[buffer[position]];
  15253. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15254. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15255. },
  15256. function memberExpression(node, position, buffer) {
  15257. const { scope } = node;
  15258. const flags = buffer[position];
  15259. node.computed = (flags & 1) === 1;
  15260. node.optional = (flags & 2) === 2;
  15261. node.object = convertNode(node, scope, buffer[position + 1], buffer);
  15262. node.property = convertNode(node, scope, buffer[position + 2], buffer);
  15263. },
  15264. function metaProperty(node, position, buffer) {
  15265. const { scope } = node;
  15266. node.meta = convertNode(node, scope, buffer[position], buffer);
  15267. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  15268. },
  15269. function methodDefinition(node, position, buffer) {
  15270. const { scope } = node;
  15271. const flags = buffer[position];
  15272. node.static = (flags & 1) === 1;
  15273. node.computed = (flags & 2) === 2;
  15274. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  15275. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  15276. node.value = convertNode(node, scope, buffer[position + 3], buffer);
  15277. node.kind = FIXED_STRINGS[buffer[position + 4]];
  15278. },
  15279. function newExpression(node, position, buffer) {
  15280. const { scope } = node;
  15281. node.annotations = convertAnnotations(buffer[position], buffer);
  15282. node.callee = convertNode(node, scope, buffer[position + 1], buffer);
  15283. node.arguments = convertNodeList(node, scope, buffer[position + 2], buffer);
  15284. },
  15285. function objectExpression(node, position, buffer) {
  15286. const { scope } = node;
  15287. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  15288. },
  15289. function objectPattern(node, position, buffer) {
  15290. const { scope } = node;
  15291. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  15292. },
  15293. function privateIdentifier(node, position, buffer) {
  15294. node.name = buffer.convertString(buffer[position]);
  15295. },
  15296. function program(node, position, buffer) {
  15297. const { scope } = node;
  15298. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15299. node.invalidAnnotations = convertAnnotations(buffer[position + 1], buffer);
  15300. },
  15301. function property(node, position, buffer) {
  15302. const { scope } = node;
  15303. const flags = buffer[position];
  15304. node.method = (flags & 1) === 1;
  15305. node.shorthand = (flags & 2) === 2;
  15306. node.computed = (flags & 4) === 4;
  15307. const keyPosition = buffer[position + 1];
  15308. node.value = convertNode(node, scope, buffer[position + 2], buffer);
  15309. node.kind = FIXED_STRINGS[buffer[position + 3]];
  15310. node.key = keyPosition === 0 ? node.value : convertNode(node, scope, keyPosition, buffer);
  15311. },
  15312. function propertyDefinition(node, position, buffer) {
  15313. const { scope } = node;
  15314. const flags = buffer[position];
  15315. node.static = (flags & 1) === 1;
  15316. node.computed = (flags & 2) === 2;
  15317. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  15318. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  15319. const valuePosition = buffer[position + 3];
  15320. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  15321. },
  15322. function restElement(node, position, buffer) {
  15323. const { scope } = node;
  15324. node.argument = convertNode(node, scope, buffer[position], buffer);
  15325. },
  15326. function returnStatement(node, position, buffer) {
  15327. const { scope } = node;
  15328. const argumentPosition = buffer[position];
  15329. node.argument =
  15330. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  15331. },
  15332. function sequenceExpression(node, position, buffer) {
  15333. const { scope } = node;
  15334. node.expressions = convertNodeList(node, scope, buffer[position], buffer);
  15335. },
  15336. function spreadElement(node, position, buffer) {
  15337. const { scope } = node;
  15338. node.argument = convertNode(node, scope, buffer[position], buffer);
  15339. },
  15340. function staticBlock(node, position, buffer) {
  15341. const { scope } = node;
  15342. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15343. },
  15344. function superElement() { },
  15345. function switchCase(node, position, buffer) {
  15346. const { scope } = node;
  15347. const testPosition = buffer[position];
  15348. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  15349. node.consequent = convertNodeList(node, scope, buffer[position + 1], buffer);
  15350. },
  15351. function switchStatement(node, position, buffer) {
  15352. const { scope } = node;
  15353. node.discriminant = convertNode(node, node.parentScope, buffer[position], buffer);
  15354. node.cases = convertNodeList(node, scope, buffer[position + 1], buffer);
  15355. },
  15356. function taggedTemplateExpression(node, position, buffer) {
  15357. const { scope } = node;
  15358. node.tag = convertNode(node, scope, buffer[position], buffer);
  15359. node.quasi = convertNode(node, scope, buffer[position + 1], buffer);
  15360. },
  15361. function templateElement(node, position, buffer) {
  15362. const flags = buffer[position];
  15363. node.tail = (flags & 1) === 1;
  15364. const cookedPosition = buffer[position + 1];
  15365. const cooked = cookedPosition === 0 ? undefined : buffer.convertString(cookedPosition);
  15366. const raw = buffer.convertString(buffer[position + 2]);
  15367. node.value = { cooked, raw };
  15368. },
  15369. function templateLiteral(node, position, buffer) {
  15370. const { scope } = node;
  15371. node.quasis = convertNodeList(node, scope, buffer[position], buffer);
  15372. node.expressions = convertNodeList(node, scope, buffer[position + 1], buffer);
  15373. },
  15374. function thisExpression() { },
  15375. function throwStatement(node, position, buffer) {
  15376. const { scope } = node;
  15377. node.argument = convertNode(node, scope, buffer[position], buffer);
  15378. },
  15379. function tryStatement(node, position, buffer) {
  15380. const { scope } = node;
  15381. node.block = convertNode(node, scope, buffer[position], buffer);
  15382. const handlerPosition = buffer[position + 1];
  15383. node.handler = handlerPosition === 0 ? null : convertNode(node, scope, handlerPosition, buffer);
  15384. const finalizerPosition = buffer[position + 2];
  15385. node.finalizer =
  15386. finalizerPosition === 0 ? null : convertNode(node, scope, finalizerPosition, buffer);
  15387. },
  15388. function unaryExpression(node, position, buffer) {
  15389. const { scope } = node;
  15390. node.operator = FIXED_STRINGS[buffer[position]];
  15391. node.argument = convertNode(node, scope, buffer[position + 1], buffer);
  15392. },
  15393. function updateExpression(node, position, buffer) {
  15394. const { scope } = node;
  15395. const flags = buffer[position];
  15396. node.prefix = (flags & 1) === 1;
  15397. node.operator = FIXED_STRINGS[buffer[position + 1]];
  15398. node.argument = convertNode(node, scope, buffer[position + 2], buffer);
  15399. },
  15400. function variableDeclaration(node, position, buffer) {
  15401. const { scope } = node;
  15402. node.kind = FIXED_STRINGS[buffer[position]];
  15403. node.declarations = convertNodeList(node, scope, buffer[position + 1], buffer);
  15404. },
  15405. function variableDeclarator(node, position, buffer) {
  15406. const { scope } = node;
  15407. node.id = convertNode(node, scope, buffer[position], buffer);
  15408. const initPosition = buffer[position + 1];
  15409. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  15410. },
  15411. function whileStatement(node, position, buffer) {
  15412. const { scope } = node;
  15413. node.test = convertNode(node, scope, buffer[position], buffer);
  15414. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  15415. },
  15416. function yieldExpression(node, position, buffer) {
  15417. const { scope } = node;
  15418. const flags = buffer[position];
  15419. node.delegate = (flags & 1) === 1;
  15420. const argumentPosition = buffer[position + 1];
  15421. node.argument =
  15422. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  15423. }
  15424. ];
  15425. function convertNode(parent, parentScope, position, buffer) {
  15426. const nodeType = buffer[position];
  15427. const NodeConstructor = nodeConstructors$1[nodeType];
  15428. /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
  15429. if (!NodeConstructor) {
  15430. console.trace();
  15431. throw new Error(`Unknown node type: ${nodeType}`);
  15432. }
  15433. const node = new NodeConstructor(parent, parentScope);
  15434. node.type = nodeTypeStrings[nodeType];
  15435. node.start = buffer[position + 1];
  15436. node.end = buffer[position + 2];
  15437. bufferParsers[nodeType](node, position + 3, buffer);
  15438. node.initialise();
  15439. return node;
  15440. }
  15441. function convertNodeList(parent, parentScope, position, buffer) {
  15442. if (position === 0)
  15443. return EMPTY_ARRAY;
  15444. const length = buffer[position++];
  15445. const list = new Array(length);
  15446. for (let index = 0; index < length; index++) {
  15447. const nodePosition = buffer[position++];
  15448. list[index] = nodePosition ? convertNode(parent, parentScope, nodePosition, buffer) : null;
  15449. }
  15450. return list;
  15451. }
  15452. class UnknownNode extends NodeBase {
  15453. hasEffects() {
  15454. return true;
  15455. }
  15456. include(context) {
  15457. super.include(context, true);
  15458. }
  15459. }
  15460. // This file is generated by scripts/generate-node-index.js.
  15461. // Do not edit this file directly.
  15462. const nodeConstructors = {
  15463. ArrayExpression,
  15464. ArrayPattern,
  15465. ArrowFunctionExpression,
  15466. AssignmentExpression,
  15467. AssignmentPattern,
  15468. AwaitExpression,
  15469. BinaryExpression,
  15470. BlockStatement,
  15471. BreakStatement,
  15472. CallExpression,
  15473. CatchClause,
  15474. ChainExpression,
  15475. ClassBody,
  15476. ClassDeclaration,
  15477. ClassExpression,
  15478. ConditionalExpression,
  15479. ContinueStatement,
  15480. DebuggerStatement,
  15481. Decorator,
  15482. DoWhileStatement,
  15483. EmptyStatement,
  15484. ExportAllDeclaration,
  15485. ExportDefaultDeclaration,
  15486. ExportNamedDeclaration,
  15487. ExportSpecifier,
  15488. ExpressionStatement,
  15489. ForInStatement,
  15490. ForOfStatement,
  15491. ForStatement,
  15492. FunctionDeclaration,
  15493. FunctionExpression,
  15494. Identifier,
  15495. IfStatement,
  15496. ImportAttribute,
  15497. ImportDeclaration,
  15498. ImportDefaultSpecifier,
  15499. ImportExpression,
  15500. ImportNamespaceSpecifier,
  15501. ImportSpecifier,
  15502. JSXAttribute,
  15503. JSXClosingElement,
  15504. JSXClosingFragment,
  15505. JSXElement,
  15506. JSXEmptyExpression,
  15507. JSXExpressionContainer,
  15508. JSXFragment,
  15509. JSXIdentifier,
  15510. JSXMemberExpression,
  15511. JSXNamespacedName,
  15512. JSXOpeningElement,
  15513. JSXOpeningFragment,
  15514. JSXSpreadAttribute,
  15515. JSXSpreadChild,
  15516. JSXText,
  15517. LabeledStatement,
  15518. Literal,
  15519. LogicalExpression,
  15520. MemberExpression,
  15521. MetaProperty,
  15522. MethodDefinition,
  15523. NewExpression,
  15524. ObjectExpression,
  15525. ObjectPattern,
  15526. PanicError,
  15527. ParseError,
  15528. PrivateIdentifier,
  15529. Program,
  15530. Property,
  15531. PropertyDefinition,
  15532. RestElement,
  15533. ReturnStatement,
  15534. SequenceExpression,
  15535. SpreadElement,
  15536. StaticBlock,
  15537. Super,
  15538. SwitchCase,
  15539. SwitchStatement,
  15540. TaggedTemplateExpression,
  15541. TemplateElement,
  15542. TemplateLiteral,
  15543. ThisExpression,
  15544. ThrowStatement,
  15545. TryStatement,
  15546. UnaryExpression,
  15547. UnknownNode,
  15548. UpdateExpression,
  15549. VariableDeclaration,
  15550. VariableDeclarator,
  15551. WhileStatement,
  15552. YieldExpression
  15553. };
  15554. class ExportShimVariable extends Variable {
  15555. constructor(module) {
  15556. super(MISSING_EXPORT_SHIM_VARIABLE);
  15557. this.module = module;
  15558. }
  15559. includePath(path, context) {
  15560. super.includePath(path, context);
  15561. this.module.needsExportShim = true;
  15562. }
  15563. }
  15564. var BuildPhase;
  15565. (function (BuildPhase) {
  15566. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  15567. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  15568. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  15569. })(BuildPhase || (BuildPhase = {}));
  15570. const sourceMapCache = new WeakMap();
  15571. /**
  15572. * This clears the decoded array and falls back to the encoded string form.
  15573. * Sourcemap mappings arrays can be very large and holding on to them for longer
  15574. * than is necessary leads to poor heap utilization.
  15575. */
  15576. function resetCacheToEncoded(cache) {
  15577. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  15578. cache.encodedMappings = encode(cache.decodedMappings);
  15579. }
  15580. cache.decodedMappings = undefined;
  15581. }
  15582. function resetSourcemapCache(map, sourcemapChain) {
  15583. if (map) {
  15584. const cache = sourceMapCache.get(map);
  15585. if (cache) {
  15586. resetCacheToEncoded(cache);
  15587. }
  15588. }
  15589. if (!sourcemapChain) {
  15590. return;
  15591. }
  15592. for (const map of sourcemapChain) {
  15593. if (map.missing)
  15594. continue;
  15595. resetSourcemapCache(map);
  15596. }
  15597. }
  15598. function decodedSourcemap(map) {
  15599. if (!map)
  15600. return null;
  15601. if (typeof map === 'string') {
  15602. map = JSON.parse(map);
  15603. }
  15604. if (!map.mappings) {
  15605. return {
  15606. mappings: [],
  15607. names: [],
  15608. sources: [],
  15609. version: 3
  15610. };
  15611. }
  15612. const originalMappings = map.mappings;
  15613. const isAlreadyDecoded = Array.isArray(originalMappings);
  15614. const cache = {
  15615. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  15616. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  15617. };
  15618. const decodedMap = {
  15619. ...map,
  15620. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  15621. // where the mappings field is never actually accessed. This appears to greatly reduce
  15622. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  15623. get mappings() {
  15624. if (cache.decodedMappings) {
  15625. return cache.decodedMappings;
  15626. }
  15627. // If decodedMappings doesn't exist then encodedMappings should.
  15628. // The only scenario where cache.encodedMappings should be undefined is if the map
  15629. // this was constructed from was already decoded, or if mappings was set to a new
  15630. // decoded string. In either case, this line shouldn't get hit.
  15631. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  15632. cache.encodedMappings = undefined;
  15633. return cache.decodedMappings;
  15634. }
  15635. };
  15636. sourceMapCache.set(decodedMap, cache);
  15637. return decodedMap;
  15638. }
  15639. function getId(m) {
  15640. return m.id;
  15641. }
  15642. function getOriginalLocation(sourcemapChain, location) {
  15643. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  15644. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  15645. const sourcemap = filteredSourcemapChain.pop();
  15646. const line = sourcemap.mappings[location.line - 1];
  15647. if (line) {
  15648. const filteredLine = line.filter((segment) => segment.length > 1);
  15649. const lastSegment = filteredLine[filteredLine.length - 1];
  15650. let previousSegment = filteredLine[0];
  15651. for (let segment of filteredLine) {
  15652. if (segment[0] >= location.column || segment === lastSegment) {
  15653. const notMatched = segment[0] !== location.column;
  15654. segment = notMatched ? previousSegment : segment;
  15655. location = {
  15656. column: segment[3],
  15657. line: segment[2] + 1
  15658. };
  15659. continue traceSourcemap;
  15660. }
  15661. previousSegment = segment;
  15662. }
  15663. }
  15664. throw new Error("Can't resolve original location of error.");
  15665. }
  15666. return location;
  15667. }
  15668. const ATTRIBUTE_KEYWORDS = new Set(['assert', 'with']);
  15669. function getAttributesFromImportExpression(node) {
  15670. const { scope: { context }, options, start } = node;
  15671. if (!(options instanceof ObjectExpression)) {
  15672. if (options) {
  15673. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), start);
  15674. }
  15675. return EMPTY_OBJECT;
  15676. }
  15677. const assertProperty = options.properties.find((property) => ATTRIBUTE_KEYWORDS.has(getPropertyKey(property)))?.value;
  15678. if (!assertProperty) {
  15679. return EMPTY_OBJECT;
  15680. }
  15681. if (!(assertProperty instanceof ObjectExpression)) {
  15682. context.module.log(LOGLEVEL_WARN, logImportOptionsAreInvalid(context.module.id), start);
  15683. return EMPTY_OBJECT;
  15684. }
  15685. const assertFields = assertProperty.properties
  15686. .map(property => {
  15687. const key = getPropertyKey(property);
  15688. if (typeof key === 'string' &&
  15689. typeof property.value.value === 'string') {
  15690. return [key, property.value.value];
  15691. }
  15692. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), property.start);
  15693. return null;
  15694. })
  15695. .filter((property) => !!property);
  15696. if (assertFields.length > 0) {
  15697. return Object.fromEntries(assertFields);
  15698. }
  15699. return EMPTY_OBJECT;
  15700. }
  15701. const getPropertyKey = (property) => {
  15702. const key = property.key;
  15703. return (key &&
  15704. !property.computed &&
  15705. (key.name || key.value));
  15706. };
  15707. function getAttributesFromImportExportDeclaration(attributes) {
  15708. return attributes?.length
  15709. ? Object.fromEntries(attributes.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  15710. : EMPTY_OBJECT;
  15711. }
  15712. function doAttributesDiffer(assertionA, assertionB) {
  15713. const keysA = Object.keys(assertionA);
  15714. return (keysA.length !== Object.keys(assertionB).length ||
  15715. keysA.some(key => assertionA[key] !== assertionB[key]));
  15716. }
  15717. let timers = new Map();
  15718. function getPersistedLabel(label, level) {
  15719. switch (level) {
  15720. case 1: {
  15721. return `# ${label}`;
  15722. }
  15723. case 2: {
  15724. return `## ${label}`;
  15725. }
  15726. case 3: {
  15727. return label;
  15728. }
  15729. default: {
  15730. return `- ${label}`;
  15731. }
  15732. }
  15733. }
  15734. function timeStartImpl(label, level = 3) {
  15735. label = getPersistedLabel(label, level);
  15736. const startMemory = process$1.memoryUsage().heapUsed;
  15737. const startTime = performance.now();
  15738. const timer = timers.get(label);
  15739. if (timer === undefined) {
  15740. timers.set(label, {
  15741. memory: 0,
  15742. startMemory,
  15743. startTime,
  15744. time: 0,
  15745. totalMemory: 0
  15746. });
  15747. }
  15748. else {
  15749. timer.startMemory = startMemory;
  15750. timer.startTime = startTime;
  15751. }
  15752. }
  15753. function timeEndImpl(label, level = 3) {
  15754. label = getPersistedLabel(label, level);
  15755. const timer = timers.get(label);
  15756. if (timer !== undefined) {
  15757. const currentMemory = process$1.memoryUsage().heapUsed;
  15758. timer.memory += currentMemory - timer.startMemory;
  15759. timer.time += performance.now() - timer.startTime;
  15760. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  15761. }
  15762. }
  15763. function getTimings() {
  15764. const newTimings = {};
  15765. for (const [label, { memory, time, totalMemory }] of timers) {
  15766. newTimings[label] = [time, memory, totalMemory];
  15767. }
  15768. return newTimings;
  15769. }
  15770. let timeStart = doNothing;
  15771. let timeEnd = doNothing;
  15772. const TIMED_PLUGIN_HOOKS = [
  15773. 'augmentChunkHash',
  15774. 'buildEnd',
  15775. 'buildStart',
  15776. 'generateBundle',
  15777. 'load',
  15778. 'moduleParsed',
  15779. 'options',
  15780. 'outputOptions',
  15781. 'renderChunk',
  15782. 'renderDynamicImport',
  15783. 'renderStart',
  15784. 'resolveDynamicImport',
  15785. 'resolveFileUrl',
  15786. 'resolveId',
  15787. 'resolveImportMeta',
  15788. 'shouldTransformCachedModule',
  15789. 'transform',
  15790. 'writeBundle'
  15791. ];
  15792. function getPluginWithTimers(plugin, index) {
  15793. if (plugin._hasTimer)
  15794. return plugin;
  15795. plugin._hasTimer = true;
  15796. for (const hook of TIMED_PLUGIN_HOOKS) {
  15797. if (hook in plugin) {
  15798. let timerLabel = `plugin ${index}`;
  15799. if (plugin.name) {
  15800. timerLabel += ` (${plugin.name})`;
  15801. }
  15802. timerLabel += ` - ${hook}`;
  15803. const handler = function (...parameters) {
  15804. timeStart(timerLabel, 4);
  15805. const result = hookFunction.apply(this, parameters);
  15806. timeEnd(timerLabel, 4);
  15807. return result;
  15808. };
  15809. let hookFunction;
  15810. if (typeof plugin[hook].handler === 'function') {
  15811. hookFunction = plugin[hook].handler;
  15812. plugin[hook].handler = handler;
  15813. }
  15814. else {
  15815. hookFunction = plugin[hook];
  15816. plugin[hook] = handler;
  15817. }
  15818. }
  15819. }
  15820. return plugin;
  15821. }
  15822. function initialiseTimers(inputOptions) {
  15823. if (inputOptions.perf) {
  15824. timers = new Map();
  15825. timeStart = timeStartImpl;
  15826. timeEnd = timeEndImpl;
  15827. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  15828. }
  15829. else {
  15830. timeStart = doNothing;
  15831. timeEnd = doNothing;
  15832. }
  15833. }
  15834. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  15835. identifier: null,
  15836. localName: MISSING_EXPORT_SHIM_VARIABLE
  15837. };
  15838. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  15839. const searchedModules = searchedNamesAndModules.get(name);
  15840. if (searchedModules) {
  15841. if (searchedModules.has(target)) {
  15842. return isExportAllSearch ? [null] : error(logCircularReexport(name, target.id));
  15843. }
  15844. searchedModules.add(target);
  15845. }
  15846. else {
  15847. searchedNamesAndModules.set(name, new Set([target]));
  15848. }
  15849. return target.getVariableForExportName(name, {
  15850. importerForSideEffects,
  15851. isExportAllSearch,
  15852. searchedNamesAndModules
  15853. });
  15854. }
  15855. function getAndExtendSideEffectModules(variable, module) {
  15856. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  15857. let currentVariable = variable;
  15858. const referencedVariables = new Set([currentVariable]);
  15859. while (true) {
  15860. const importingModule = currentVariable.module;
  15861. currentVariable =
  15862. currentVariable instanceof ExportDefaultVariable
  15863. ? currentVariable.getDirectOriginalVariable()
  15864. : currentVariable instanceof SyntheticNamedExportVariable
  15865. ? currentVariable.syntheticNamespace
  15866. : null;
  15867. if (!currentVariable || referencedVariables.has(currentVariable)) {
  15868. break;
  15869. }
  15870. referencedVariables.add(currentVariable);
  15871. sideEffectModules.add(importingModule);
  15872. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  15873. if (originalSideEffects) {
  15874. for (const module of originalSideEffects) {
  15875. sideEffectModules.add(module);
  15876. }
  15877. }
  15878. }
  15879. return sideEffectModules;
  15880. }
  15881. class Module {
  15882. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
  15883. this.graph = graph;
  15884. this.id = id;
  15885. this.options = options;
  15886. this.alternativeReexportModules = new Map();
  15887. this.chunkFileNames = new Set();
  15888. this.chunkNames = [];
  15889. this.cycles = new Set();
  15890. this.dependencies = new Set();
  15891. this.dynamicDependencies = new Set();
  15892. this.dynamicImporters = [];
  15893. this.dynamicImports = [];
  15894. this.execIndex = Infinity;
  15895. this.hasTreeShakingPassStarted = false;
  15896. this.implicitlyLoadedAfter = new Set();
  15897. this.implicitlyLoadedBefore = new Set();
  15898. this.importDescriptions = new Map();
  15899. this.importMetas = [];
  15900. this.importedFromNotTreeshaken = false;
  15901. this.importers = [];
  15902. this.includedDynamicImporters = [];
  15903. this.includedTopLevelAwaitingDynamicImporters = new Set();
  15904. this.includedImports = new Set();
  15905. this.isExecuted = false;
  15906. this.isUserDefinedEntryPoint = false;
  15907. this.needsExportShim = false;
  15908. this.sideEffectDependenciesByVariable = new Map();
  15909. this.sourcesWithAttributes = new Map();
  15910. this.allExportNames = null;
  15911. this.allExportsIncluded = false;
  15912. this.ast = null;
  15913. this.exportAllModules = [];
  15914. this.exportAllSources = new Set();
  15915. this.exportNamesByVariable = null;
  15916. this.exportShimVariable = new ExportShimVariable(this);
  15917. this.exports = new Map();
  15918. this.namespaceReexportsByName = new Map();
  15919. this.reexportDescriptions = new Map();
  15920. this.relevantDependencies = null;
  15921. this.syntheticExports = new Map();
  15922. this.syntheticNamespace = null;
  15923. this.transformDependencies = [];
  15924. this.transitiveReexports = null;
  15925. this.excludeFromSourcemap = /\0/.test(id);
  15926. this.context = options.moduleContext(id);
  15927. this.preserveSignature = this.options.preserveEntrySignatures;
  15928. // eslint-disable-next-line @typescript-eslint/no-this-alias
  15929. const module = this;
  15930. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
  15931. this.info = {
  15932. ast: null,
  15933. attributes,
  15934. code: null,
  15935. get dynamicallyImportedIdResolutions() {
  15936. return dynamicImports
  15937. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  15938. .filter(Boolean);
  15939. },
  15940. get dynamicallyImportedIds() {
  15941. // We cannot use this.dynamicDependencies because this is needed before
  15942. // dynamicDependencies are populated
  15943. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  15944. },
  15945. get dynamicImporters() {
  15946. return dynamicImporters.sort();
  15947. },
  15948. get exportedBindings() {
  15949. const exportBindings = { '.': [...exports.keys()] };
  15950. for (const [name, { source }] of reexportDescriptions) {
  15951. (exportBindings[source] ??= []).push(name);
  15952. }
  15953. for (const source of exportAllSources) {
  15954. (exportBindings[source] ??= []).push('*');
  15955. }
  15956. return exportBindings;
  15957. },
  15958. get exports() {
  15959. return [
  15960. ...exports.keys(),
  15961. ...reexportDescriptions.keys(),
  15962. ...[...exportAllSources].map(() => '*')
  15963. ];
  15964. },
  15965. get hasDefaultExport() {
  15966. // This information is only valid after parsing
  15967. if (!module.ast) {
  15968. return null;
  15969. }
  15970. return module.exports.has('default') || reexportDescriptions.has('default');
  15971. },
  15972. id,
  15973. get implicitlyLoadedAfterOneOf() {
  15974. return Array.from(implicitlyLoadedAfter, getId).sort();
  15975. },
  15976. get implicitlyLoadedBefore() {
  15977. return Array.from(implicitlyLoadedBefore, getId).sort();
  15978. },
  15979. get importedIdResolutions() {
  15980. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
  15981. },
  15982. get importedIds() {
  15983. // We cannot use this.dependencies because this is needed before
  15984. // dependencies are populated
  15985. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  15986. },
  15987. get importers() {
  15988. return importers.sort();
  15989. },
  15990. isEntry,
  15991. isExternal: false,
  15992. get isIncluded() {
  15993. if (graph.phase !== BuildPhase.GENERATE) {
  15994. return null;
  15995. }
  15996. return module.isIncluded();
  15997. },
  15998. meta: { ...meta },
  15999. moduleSideEffects,
  16000. syntheticNamedExports
  16001. };
  16002. }
  16003. basename() {
  16004. const base = basename(this.id);
  16005. const extension = extname(this.id);
  16006. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  16007. }
  16008. bindReferences() {
  16009. this.ast.bind();
  16010. }
  16011. cacheInfoGetters() {
  16012. cacheObjectGetters(this.info, [
  16013. 'dynamicallyImportedIdResolutions',
  16014. 'dynamicallyImportedIds',
  16015. 'dynamicImporters',
  16016. 'exportedBindings',
  16017. 'exports',
  16018. 'hasDefaultExport',
  16019. 'implicitlyLoadedAfterOneOf',
  16020. 'implicitlyLoadedBefore',
  16021. 'importedIdResolutions',
  16022. 'importedIds',
  16023. 'importers'
  16024. ]);
  16025. }
  16026. error(properties, pos) {
  16027. if (pos !== undefined) {
  16028. this.addLocationToLogProps(properties, pos);
  16029. }
  16030. return error(properties);
  16031. }
  16032. // sum up the length of all ast nodes that are included
  16033. estimateSize() {
  16034. let size = 0;
  16035. for (const node of this.ast.body) {
  16036. if (node.included) {
  16037. size += node.end - node.start;
  16038. }
  16039. }
  16040. return size;
  16041. }
  16042. getAllExportNames() {
  16043. if (this.allExportNames) {
  16044. return this.allExportNames;
  16045. }
  16046. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  16047. for (const module of this.exportAllModules) {
  16048. if (module instanceof ExternalModule) {
  16049. this.allExportNames.add(`*${module.id}`);
  16050. continue;
  16051. }
  16052. for (const name of module.getAllExportNames()) {
  16053. if (name !== 'default')
  16054. this.allExportNames.add(name);
  16055. }
  16056. }
  16057. // We do not count the synthetic namespace as a regular export to hide it
  16058. // from entry signatures and namespace objects
  16059. if (typeof this.info.syntheticNamedExports === 'string') {
  16060. this.allExportNames.delete(this.info.syntheticNamedExports);
  16061. }
  16062. return this.allExportNames;
  16063. }
  16064. getDependenciesToBeIncluded() {
  16065. if (this.relevantDependencies)
  16066. return this.relevantDependencies;
  16067. this.relevantDependencies = new Set();
  16068. const necessaryDependencies = new Set();
  16069. const alwaysCheckedDependencies = new Set();
  16070. const dependencyVariables = new Set(this.includedImports);
  16071. if (this.info.isEntry ||
  16072. this.includedDynamicImporters.length > 0 ||
  16073. this.namespace.included ||
  16074. this.implicitlyLoadedAfter.size > 0) {
  16075. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  16076. const [exportedVariable] = this.getVariableForExportName(exportName);
  16077. if (exportedVariable?.included) {
  16078. dependencyVariables.add(exportedVariable);
  16079. }
  16080. }
  16081. }
  16082. for (let variable of dependencyVariables) {
  16083. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  16084. if (sideEffectDependencies) {
  16085. for (const module of sideEffectDependencies) {
  16086. alwaysCheckedDependencies.add(module);
  16087. }
  16088. }
  16089. if (variable instanceof SyntheticNamedExportVariable) {
  16090. variable = variable.getBaseVariable();
  16091. }
  16092. else if (variable instanceof ExportDefaultVariable) {
  16093. variable = variable.getOriginalVariable();
  16094. }
  16095. necessaryDependencies.add(variable.module);
  16096. }
  16097. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  16098. for (const dependency of this.dependencies) {
  16099. this.relevantDependencies.add(dependency);
  16100. }
  16101. }
  16102. else {
  16103. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  16104. }
  16105. for (const dependency of necessaryDependencies) {
  16106. this.relevantDependencies.add(dependency);
  16107. }
  16108. return this.relevantDependencies;
  16109. }
  16110. getExportNamesByVariable() {
  16111. if (this.exportNamesByVariable) {
  16112. return this.exportNamesByVariable;
  16113. }
  16114. const exportNamesByVariable = new Map();
  16115. for (const exportName of this.getAllExportNames()) {
  16116. let [tracedVariable] = this.getVariableForExportName(exportName);
  16117. if (tracedVariable instanceof ExportDefaultVariable) {
  16118. tracedVariable = tracedVariable.getOriginalVariable();
  16119. }
  16120. if (!tracedVariable ||
  16121. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  16122. continue;
  16123. }
  16124. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  16125. if (existingExportNames) {
  16126. existingExportNames.push(exportName);
  16127. }
  16128. else {
  16129. exportNamesByVariable.set(tracedVariable, [exportName]);
  16130. }
  16131. }
  16132. return (this.exportNamesByVariable = exportNamesByVariable);
  16133. }
  16134. getExports() {
  16135. return [...this.exports.keys()];
  16136. }
  16137. getReexports() {
  16138. if (this.transitiveReexports) {
  16139. return this.transitiveReexports;
  16140. }
  16141. // to avoid infinite recursion when using circular `export * from X`
  16142. this.transitiveReexports = [];
  16143. const reexports = new Set(this.reexportDescriptions.keys());
  16144. for (const module of this.exportAllModules) {
  16145. if (module instanceof ExternalModule) {
  16146. reexports.add(`*${module.id}`);
  16147. }
  16148. else {
  16149. for (const name of [...module.getReexports(), ...module.getExports()]) {
  16150. if (name !== 'default')
  16151. reexports.add(name);
  16152. }
  16153. }
  16154. }
  16155. return (this.transitiveReexports = [...reexports]);
  16156. }
  16157. getRenderedExports() {
  16158. // only direct exports are counted here, not reexports at all
  16159. const renderedExports = [];
  16160. const removedExports = [];
  16161. for (const exportName of this.exports.keys()) {
  16162. const [variable] = this.getVariableForExportName(exportName);
  16163. (variable?.included ? renderedExports : removedExports).push(exportName);
  16164. }
  16165. return { removedExports, renderedExports };
  16166. }
  16167. getSyntheticNamespace() {
  16168. if (this.syntheticNamespace === null) {
  16169. this.syntheticNamespace = undefined;
  16170. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  16171. ? this.info.syntheticNamedExports
  16172. : 'default', { onlyExplicit: true });
  16173. }
  16174. if (!this.syntheticNamespace) {
  16175. return error(logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  16176. }
  16177. return this.syntheticNamespace;
  16178. }
  16179. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  16180. if (name[0] === '*') {
  16181. if (name.length === 1) {
  16182. // export * from './other'
  16183. return [this.namespace];
  16184. }
  16185. // export * from 'external'
  16186. const module = this.graph.modulesById.get(name.slice(1));
  16187. return module.getVariableForExportName('*');
  16188. }
  16189. // export { foo } from './other'
  16190. const reexportDeclaration = this.reexportDescriptions.get(name);
  16191. if (reexportDeclaration) {
  16192. const [variable, options] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  16193. if (!variable) {
  16194. return this.error(logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id, !!options?.missingButExportExists), reexportDeclaration.start);
  16195. }
  16196. if (importerForSideEffects) {
  16197. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  16198. if (this.info.moduleSideEffects) {
  16199. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  16200. }
  16201. }
  16202. return [variable];
  16203. }
  16204. const exportDeclaration = this.exports.get(name);
  16205. if (exportDeclaration) {
  16206. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  16207. return [this.exportShimVariable];
  16208. }
  16209. const name = exportDeclaration.localName;
  16210. const variable = this.traceVariable(name, {
  16211. importerForSideEffects,
  16212. searchedNamesAndModules
  16213. });
  16214. if (!variable) {
  16215. return [null, { missingButExportExists: true }];
  16216. }
  16217. if (importerForSideEffects) {
  16218. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  16219. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  16220. }
  16221. return [variable];
  16222. }
  16223. if (onlyExplicit) {
  16224. return [null];
  16225. }
  16226. if (name !== 'default') {
  16227. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  16228. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  16229. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  16230. if (foundNamespaceReexport[0]) {
  16231. return foundNamespaceReexport;
  16232. }
  16233. }
  16234. if (this.info.syntheticNamedExports) {
  16235. return [
  16236. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  16237. ];
  16238. }
  16239. // we don't want to create shims when we are just
  16240. // probing export * modules for exports
  16241. if (!isExportAllSearch && this.options.shimMissingExports) {
  16242. this.shimMissingExport(name);
  16243. return [this.exportShimVariable];
  16244. }
  16245. return [null];
  16246. }
  16247. hasEffects() {
  16248. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  16249. }
  16250. include() {
  16251. const context = createInclusionContext();
  16252. if (this.ast.shouldBeIncluded(context))
  16253. this.ast.include(context, false);
  16254. }
  16255. includeAllExports(includeNamespaceMembers) {
  16256. if (includeNamespaceMembers) {
  16257. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  16258. }
  16259. if (this.allExportsIncluded)
  16260. return;
  16261. this.allExportsIncluded = true;
  16262. if (!this.isExecuted) {
  16263. markModuleAndImpureDependenciesAsExecuted(this);
  16264. this.graph.needsTreeshakingPass = true;
  16265. }
  16266. const inclusionContext = createInclusionContext();
  16267. for (const exportName of this.exports.keys()) {
  16268. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  16269. const variable = this.getVariableForExportName(exportName)[0];
  16270. if (!variable) {
  16271. return error(logMissingEntryExport(exportName, this.id));
  16272. }
  16273. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  16274. variable.deoptimizePath(UNKNOWN_PATH);
  16275. }
  16276. }
  16277. for (const name of this.getReexports()) {
  16278. const [variable] = this.getVariableForExportName(name);
  16279. if (variable) {
  16280. variable.deoptimizePath(UNKNOWN_PATH);
  16281. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  16282. if (variable instanceof ExternalVariable) {
  16283. variable.module.reexported = true;
  16284. }
  16285. }
  16286. }
  16287. }
  16288. includeAllInBundle() {
  16289. this.ast.include(createInclusionContext(), true);
  16290. this.includeAllExports(false);
  16291. }
  16292. includeExportsByNames(names) {
  16293. if (!this.isExecuted) {
  16294. markModuleAndImpureDependenciesAsExecuted(this);
  16295. this.graph.needsTreeshakingPass = true;
  16296. }
  16297. let includeNamespaceMembers = false;
  16298. const inclusionContext = createInclusionContext();
  16299. for (const name of names) {
  16300. const variable = this.getVariableForExportName(name)[0];
  16301. if (variable) {
  16302. variable.deoptimizePath(UNKNOWN_PATH);
  16303. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  16304. }
  16305. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  16306. includeNamespaceMembers = true;
  16307. }
  16308. }
  16309. if (includeNamespaceMembers) {
  16310. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  16311. }
  16312. }
  16313. isIncluded() {
  16314. // Modules where this.ast is missing have been loaded via this.load and are
  16315. // not yet fully processed, hence they cannot be included.
  16316. return (this.ast &&
  16317. (this.ast.included ||
  16318. this.namespace.included ||
  16319. this.importedFromNotTreeshaken ||
  16320. this.exportShimVariable.included));
  16321. }
  16322. linkImports() {
  16323. this.addModulesToImportDescriptions(this.importDescriptions);
  16324. this.addModulesToImportDescriptions(this.reexportDescriptions);
  16325. const externalExportAllModules = [];
  16326. for (const source of this.exportAllSources) {
  16327. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  16328. if (module instanceof ExternalModule) {
  16329. externalExportAllModules.push(module);
  16330. continue;
  16331. }
  16332. this.exportAllModules.push(module);
  16333. }
  16334. this.exportAllModules.push(...externalExportAllModules);
  16335. }
  16336. log(level, properties, pos) {
  16337. this.addLocationToLogProps(properties, pos);
  16338. this.options.onLog(level, properties);
  16339. }
  16340. render(options) {
  16341. const source = this.magicString.clone();
  16342. this.ast.render(source, options);
  16343. source.trim();
  16344. const { usesTopLevelAwait } = this.astContext;
  16345. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  16346. return error(logInvalidFormatForTopLevelAwait(this.id, options.format));
  16347. }
  16348. return { source, usesTopLevelAwait };
  16349. }
  16350. async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  16351. timeStart('generate ast', 3);
  16352. if (code.startsWith('#!')) {
  16353. const shebangEndPosition = code.indexOf('\n');
  16354. this.shebang = code.slice(2, shebangEndPosition);
  16355. }
  16356. this.info.code = code;
  16357. this.originalCode = originalCode;
  16358. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  16359. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  16360. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  16361. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  16362. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  16363. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  16364. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  16365. if (transformFiles) {
  16366. this.transformFiles = transformFiles;
  16367. }
  16368. this.transformDependencies = transformDependencies;
  16369. this.customTransformCache = customTransformCache;
  16370. this.updateOptions(moduleOptions);
  16371. this.resolvedIds = resolvedIds ?? Object.create(null);
  16372. // By default, `id` is the file name. Custom resolvers and loaders
  16373. // can change that, but it makes sense to use it for the source file name
  16374. const fileName = this.id;
  16375. this.magicString = new MagicString(code, {
  16376. filename: (this.excludeFromSourcemap ? null : fileName), // don't include plugin helpers in sourcemap
  16377. indentExclusionRanges: []
  16378. });
  16379. this.astContext = {
  16380. addDynamicImport: this.addDynamicImport.bind(this),
  16381. addExport: this.addExport.bind(this),
  16382. addImport: this.addImport.bind(this),
  16383. addImportMeta: this.addImportMeta.bind(this),
  16384. addImportSource: this.addImportSource.bind(this),
  16385. code, // Only needed for debugging
  16386. deoptimizationTracker: this.graph.deoptimizationTracker,
  16387. error: this.error.bind(this),
  16388. fileName, // Needed for warnings
  16389. getExports: this.getExports.bind(this),
  16390. getImportedJsxFactoryVariable: this.getImportedJsxFactoryVariable.bind(this),
  16391. getModuleExecIndex: () => this.execIndex,
  16392. getModuleName: this.basename.bind(this),
  16393. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  16394. getReexports: this.getReexports.bind(this),
  16395. importDescriptions: this.importDescriptions,
  16396. includeAllExports: () => this.includeAllExports(true),
  16397. includeDynamicImport: this.includeDynamicImport.bind(this),
  16398. includeVariableInModule: this.includeVariableInModule.bind(this),
  16399. log: this.log.bind(this),
  16400. magicString: this.magicString,
  16401. manualPureFunctions: this.graph.pureFunctions,
  16402. module: this,
  16403. moduleContext: this.context,
  16404. newlyIncludedVariableInits: this.graph.newlyIncludedVariableInits,
  16405. options: this.options,
  16406. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  16407. traceExport: (name) => this.getVariableForExportName(name),
  16408. traceVariable: this.traceVariable.bind(this),
  16409. usesTopLevelAwait: false
  16410. };
  16411. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  16412. this.namespace = new NamespaceVariable(this.astContext);
  16413. const programParent = { context: this.astContext, type: 'Module' };
  16414. if (ast) {
  16415. this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
  16416. this.info.ast = ast;
  16417. }
  16418. else {
  16419. // Measuring asynchronous code does not provide reasonable results
  16420. timeEnd('generate ast', 3);
  16421. const astBuffer = await parseAsync(code, false, this.options.jsx !== false);
  16422. timeStart('generate ast', 3);
  16423. this.ast = convertProgram(astBuffer, programParent, this.scope);
  16424. // Make lazy and apply LRU cache to not hog the memory
  16425. Object.defineProperty(this.info, 'ast', {
  16426. get: () => {
  16427. if (this.graph.astLru.has(fileName)) {
  16428. return this.graph.astLru.get(fileName);
  16429. }
  16430. else {
  16431. const parsedAst = this.tryParse();
  16432. // If the cache is not disabled, we need to keep the AST in memory
  16433. // until the end when the cache is generated
  16434. if (this.options.cache !== false) {
  16435. Object.defineProperty(this.info, 'ast', {
  16436. value: parsedAst
  16437. });
  16438. return parsedAst;
  16439. }
  16440. // Otherwise, we keep it in a small LRU cache to not hog too much
  16441. // memory but allow the same AST to be requested several times.
  16442. this.graph.astLru.set(fileName, parsedAst);
  16443. return parsedAst;
  16444. }
  16445. }
  16446. });
  16447. }
  16448. timeEnd('generate ast', 3);
  16449. }
  16450. toJSON() {
  16451. return {
  16452. ast: this.info.ast,
  16453. attributes: this.info.attributes,
  16454. code: this.info.code,
  16455. customTransformCache: this.customTransformCache,
  16456. dependencies: Array.from(this.dependencies, getId),
  16457. id: this.id,
  16458. meta: this.info.meta,
  16459. moduleSideEffects: this.info.moduleSideEffects,
  16460. originalCode: this.originalCode,
  16461. originalSourcemap: this.originalSourcemap,
  16462. resolvedIds: this.resolvedIds,
  16463. sourcemapChain: this.sourcemapChain,
  16464. syntheticNamedExports: this.info.syntheticNamedExports,
  16465. transformDependencies: this.transformDependencies,
  16466. transformFiles: this.transformFiles
  16467. };
  16468. }
  16469. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  16470. const localVariable = this.scope.variables.get(name);
  16471. if (localVariable) {
  16472. return localVariable;
  16473. }
  16474. const importDescription = this.importDescriptions.get(name);
  16475. if (importDescription) {
  16476. const otherModule = importDescription.module;
  16477. if (otherModule instanceof Module && importDescription.name === '*') {
  16478. return otherModule.namespace;
  16479. }
  16480. const [declaration, options] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  16481. if (!declaration) {
  16482. return this.error(logMissingExport(importDescription.name, this.id, otherModule.id, !!options?.missingButExportExists), importDescription.start);
  16483. }
  16484. return declaration;
  16485. }
  16486. return null;
  16487. }
  16488. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  16489. if (moduleSideEffects != null) {
  16490. this.info.moduleSideEffects = moduleSideEffects;
  16491. }
  16492. if (syntheticNamedExports != null) {
  16493. this.info.syntheticNamedExports = syntheticNamedExports;
  16494. }
  16495. if (meta != null) {
  16496. Object.assign(this.info.meta, meta);
  16497. }
  16498. }
  16499. addDynamicImport(node) {
  16500. let argument = node.sourceAstNode;
  16501. if (argument.type === TemplateLiteral$1) {
  16502. if (argument.quasis.length === 1 &&
  16503. typeof argument.quasis[0].value.cooked === 'string') {
  16504. argument = argument.quasis[0].value.cooked;
  16505. }
  16506. }
  16507. else if (argument.type === Literal$1 &&
  16508. typeof argument.value === 'string') {
  16509. argument = argument.value;
  16510. }
  16511. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  16512. }
  16513. assertUniqueExportName(name, nodeStart) {
  16514. if (this.exports.has(name) || this.reexportDescriptions.has(name)) {
  16515. this.error(logDuplicateExportError(name), nodeStart);
  16516. }
  16517. }
  16518. addExport(node) {
  16519. if (node instanceof ExportDefaultDeclaration) {
  16520. // export default foo;
  16521. this.assertUniqueExportName('default', node.start);
  16522. this.exports.set('default', {
  16523. identifier: node.variable.getAssignedVariableName(),
  16524. localName: 'default'
  16525. });
  16526. }
  16527. else if (node instanceof ExportAllDeclaration) {
  16528. const source = node.source.value;
  16529. this.addSource(source, node);
  16530. if (node.exported) {
  16531. // export * as name from './other'
  16532. const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
  16533. this.assertUniqueExportName(name, node.exported.start);
  16534. this.reexportDescriptions.set(name, {
  16535. localName: '*',
  16536. module: null, // filled in later,
  16537. source,
  16538. start: node.start
  16539. });
  16540. }
  16541. else {
  16542. // export * from './other'
  16543. this.exportAllSources.add(source);
  16544. }
  16545. }
  16546. else if (node.source instanceof Literal) {
  16547. // export { name } from './other'
  16548. const source = node.source.value;
  16549. this.addSource(source, node);
  16550. for (const { exported, local, start } of node.specifiers) {
  16551. const name = exported instanceof Literal ? exported.value : exported.name;
  16552. this.assertUniqueExportName(name, start);
  16553. this.reexportDescriptions.set(name, {
  16554. localName: local instanceof Literal ? local.value : local.name,
  16555. module: null, // filled in later,
  16556. source,
  16557. start
  16558. });
  16559. }
  16560. }
  16561. else if (node.declaration) {
  16562. const declaration = node.declaration;
  16563. if (declaration instanceof VariableDeclaration) {
  16564. // export var { foo, bar } = ...
  16565. // export var foo = 1, bar = 2;
  16566. for (const declarator of declaration.declarations) {
  16567. for (const localName of extractAssignedNames(declarator.id)) {
  16568. this.assertUniqueExportName(localName, declarator.id.start);
  16569. this.exports.set(localName, { identifier: null, localName });
  16570. }
  16571. }
  16572. }
  16573. else {
  16574. // export function foo () {}
  16575. const localName = declaration.id.name;
  16576. this.assertUniqueExportName(localName, declaration.id.start);
  16577. this.exports.set(localName, { identifier: null, localName });
  16578. }
  16579. }
  16580. else {
  16581. // export { foo, bar, baz }
  16582. for (const { local, exported } of node.specifiers) {
  16583. // except for reexports, local must be an Identifier
  16584. const localName = local.name;
  16585. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  16586. this.assertUniqueExportName(exportedName, exported.start);
  16587. this.exports.set(exportedName, { identifier: null, localName });
  16588. }
  16589. }
  16590. }
  16591. addImport(node) {
  16592. const source = node.source.value;
  16593. this.addSource(source, node);
  16594. for (const specifier of node.specifiers) {
  16595. const localName = specifier.local.name;
  16596. if (this.scope.variables.has(localName) || this.importDescriptions.has(localName)) {
  16597. this.error(logRedeclarationError(localName), specifier.local.start);
  16598. }
  16599. const name = specifier instanceof ImportDefaultSpecifier
  16600. ? 'default'
  16601. : specifier instanceof ImportNamespaceSpecifier
  16602. ? '*'
  16603. : specifier.imported instanceof Identifier
  16604. ? specifier.imported.name
  16605. : specifier.imported.value;
  16606. this.importDescriptions.set(localName, {
  16607. module: null, // filled in later
  16608. name,
  16609. source,
  16610. start: specifier.start
  16611. });
  16612. }
  16613. }
  16614. addImportSource(importSource) {
  16615. if (importSource && !this.sourcesWithAttributes.has(importSource)) {
  16616. this.sourcesWithAttributes.set(importSource, EMPTY_OBJECT);
  16617. }
  16618. }
  16619. addImportMeta(node) {
  16620. this.importMetas.push(node);
  16621. }
  16622. addLocationToLogProps(properties, pos) {
  16623. properties.id = this.id;
  16624. properties.pos = pos;
  16625. let code = this.info.code;
  16626. const location = locate(code, pos, { offsetLine: 1 });
  16627. if (location) {
  16628. let { column, line } = location;
  16629. try {
  16630. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  16631. code = this.originalCode;
  16632. }
  16633. catch (error_) {
  16634. this.options.onLog(LOGLEVEL_WARN, logInvalidSourcemapForError(error_, this.id, column, line, pos));
  16635. }
  16636. augmentCodeLocation(properties, { column, line }, code, this.id);
  16637. }
  16638. }
  16639. addModulesToImportDescriptions(importDescription) {
  16640. for (const specifier of importDescription.values()) {
  16641. const { id } = this.resolvedIds[specifier.source];
  16642. specifier.module = this.graph.modulesById.get(id);
  16643. }
  16644. }
  16645. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  16646. const handledDependencies = new Set();
  16647. const addSideEffectDependencies = (possibleDependencies) => {
  16648. for (const dependency of possibleDependencies) {
  16649. if (handledDependencies.has(dependency)) {
  16650. continue;
  16651. }
  16652. handledDependencies.add(dependency);
  16653. if (necessaryDependencies.has(dependency)) {
  16654. relevantDependencies.add(dependency);
  16655. continue;
  16656. }
  16657. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  16658. continue;
  16659. }
  16660. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  16661. relevantDependencies.add(dependency);
  16662. continue;
  16663. }
  16664. addSideEffectDependencies(dependency.dependencies);
  16665. }
  16666. };
  16667. addSideEffectDependencies(this.dependencies);
  16668. addSideEffectDependencies(alwaysCheckedDependencies);
  16669. }
  16670. addSource(source, declaration) {
  16671. const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
  16672. const existingAttributes = this.sourcesWithAttributes.get(source);
  16673. if (existingAttributes) {
  16674. if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
  16675. this.log(LOGLEVEL_WARN, logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
  16676. }
  16677. }
  16678. else {
  16679. this.sourcesWithAttributes.set(source, parsedAttributes);
  16680. }
  16681. }
  16682. getImportedJsxFactoryVariable(baseName, nodeStart, importSource) {
  16683. const { id } = this.resolvedIds[importSource];
  16684. const module = this.graph.modulesById.get(id);
  16685. const [variable] = module.getVariableForExportName(baseName);
  16686. if (!variable) {
  16687. return this.error(logMissingJsxExport(baseName, id, this.id), nodeStart);
  16688. }
  16689. return variable;
  16690. }
  16691. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  16692. let foundSyntheticDeclaration = null;
  16693. const foundInternalDeclarations = new Map();
  16694. const foundExternalDeclarations = new Set();
  16695. for (const module of this.exportAllModules) {
  16696. // Synthetic namespaces should not hide "regular" exports of the same name
  16697. if (module.info.syntheticNamedExports === name) {
  16698. continue;
  16699. }
  16700. const [variable, options] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  16701. // We are creating a copy to handle the case where the same binding is
  16702. // imported through different namespace reexports gracefully
  16703. copyNameToModulesMap(searchedNamesAndModules));
  16704. if (module instanceof ExternalModule || options?.indirectExternal) {
  16705. foundExternalDeclarations.add(variable);
  16706. }
  16707. else if (variable instanceof SyntheticNamedExportVariable) {
  16708. if (!foundSyntheticDeclaration) {
  16709. foundSyntheticDeclaration = variable;
  16710. }
  16711. }
  16712. else if (variable) {
  16713. foundInternalDeclarations.set(variable, module);
  16714. }
  16715. }
  16716. if (foundInternalDeclarations.size > 0) {
  16717. const foundDeclarationList = [...foundInternalDeclarations];
  16718. const usedDeclaration = foundDeclarationList[0][0];
  16719. if (foundDeclarationList.length === 1) {
  16720. return [usedDeclaration];
  16721. }
  16722. this.options.onLog(LOGLEVEL_WARN, logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  16723. // TODO we are pretending it was not found while it should behave like "undefined"
  16724. return [null];
  16725. }
  16726. if (foundExternalDeclarations.size > 0) {
  16727. const foundDeclarationList = [...foundExternalDeclarations];
  16728. const usedDeclaration = foundDeclarationList[0];
  16729. if (foundDeclarationList.length > 1) {
  16730. this.options.onLog(LOGLEVEL_WARN, logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  16731. }
  16732. return [usedDeclaration, { indirectExternal: true }];
  16733. }
  16734. if (foundSyntheticDeclaration) {
  16735. return [foundSyntheticDeclaration];
  16736. }
  16737. return [null];
  16738. }
  16739. includeAndGetAdditionalMergedNamespaces() {
  16740. const externalNamespaces = new Set();
  16741. const syntheticNamespaces = new Set();
  16742. for (const module of [this, ...this.exportAllModules]) {
  16743. if (module instanceof ExternalModule) {
  16744. const [externalVariable] = module.getVariableForExportName('*');
  16745. externalVariable.includePath(UNKNOWN_PATH, createInclusionContext());
  16746. this.includedImports.add(externalVariable);
  16747. externalNamespaces.add(externalVariable);
  16748. }
  16749. else if (module.info.syntheticNamedExports) {
  16750. const syntheticNamespace = module.getSyntheticNamespace();
  16751. syntheticNamespace.includePath(UNKNOWN_PATH, createInclusionContext());
  16752. this.includedImports.add(syntheticNamespace);
  16753. syntheticNamespaces.add(syntheticNamespace);
  16754. }
  16755. }
  16756. return [...syntheticNamespaces, ...externalNamespaces];
  16757. }
  16758. includeDynamicImport(node) {
  16759. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  16760. if (resolution instanceof Module) {
  16761. if (!resolution.includedDynamicImporters.includes(this)) {
  16762. resolution.includedDynamicImporters.push(this);
  16763. // If a module has a top-level await, removing this entry can create
  16764. // deadlocks.
  16765. if (this.astContext.usesTopLevelAwait) {
  16766. resolution.includedTopLevelAwaitingDynamicImporters.add(this);
  16767. }
  16768. }
  16769. const importedNames = this.options.treeshake
  16770. ? node.getDeterministicImportedNames()
  16771. : undefined;
  16772. if (importedNames) {
  16773. resolution.includeExportsByNames(importedNames);
  16774. }
  16775. else {
  16776. resolution.includeAllExports(true);
  16777. }
  16778. }
  16779. }
  16780. includeVariable(variable, path, context) {
  16781. const { included, module: variableModule } = variable;
  16782. variable.includePath(path, context);
  16783. if (included) {
  16784. if (variableModule instanceof Module && variableModule !== this) {
  16785. getAndExtendSideEffectModules(variable, this);
  16786. }
  16787. }
  16788. else {
  16789. this.graph.needsTreeshakingPass = true;
  16790. if (variableModule instanceof Module) {
  16791. if (!variableModule.isExecuted) {
  16792. markModuleAndImpureDependenciesAsExecuted(variableModule);
  16793. }
  16794. if (variableModule !== this) {
  16795. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  16796. for (const module of sideEffectModules) {
  16797. if (!module.isExecuted) {
  16798. markModuleAndImpureDependenciesAsExecuted(module);
  16799. }
  16800. }
  16801. }
  16802. }
  16803. }
  16804. }
  16805. includeVariableInModule(variable, path, context) {
  16806. this.includeVariable(variable, path, context);
  16807. const variableModule = variable.module;
  16808. if (variableModule && variableModule !== this) {
  16809. this.includedImports.add(variable);
  16810. }
  16811. }
  16812. shimMissingExport(name) {
  16813. this.options.onLog(LOGLEVEL_WARN, logShimmedExport(this.id, name));
  16814. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  16815. }
  16816. tryParse() {
  16817. try {
  16818. return parseAst(this.info.code, { jsx: this.options.jsx !== false });
  16819. }
  16820. catch (error_) {
  16821. return this.error(logModuleParseError(error_, this.id), error_.pos);
  16822. }
  16823. }
  16824. }
  16825. // if there is a cyclic import in the reexport chain, we should not
  16826. // import from the original module but from the cyclic module to not
  16827. // mess up execution order.
  16828. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  16829. if (variable.module instanceof Module && variable.module !== reexporter) {
  16830. const exporterCycles = variable.module.cycles;
  16831. if (exporterCycles.size > 0) {
  16832. const importerCycles = reexporter.cycles;
  16833. for (const cycleSymbol of importerCycles) {
  16834. if (exporterCycles.has(cycleSymbol)) {
  16835. importer.alternativeReexportModules.set(variable, reexporter);
  16836. break;
  16837. }
  16838. }
  16839. }
  16840. }
  16841. }
  16842. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  16843. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  16844. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  16845. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  16846. async function createAddons(options, outputPluginDriver, chunk) {
  16847. try {
  16848. let [banner, footer, intro, outro] = await Promise.all([
  16849. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  16850. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  16851. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  16852. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  16853. ]);
  16854. if (intro)
  16855. intro += '\n\n';
  16856. if (outro)
  16857. outro = `\n\n${outro}`;
  16858. if (banner)
  16859. banner += '\n';
  16860. if (footer)
  16861. footer = '\n' + footer;
  16862. return { banner, footer, intro, outro };
  16863. }
  16864. catch (error_) {
  16865. return error(logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  16866. }
  16867. }
  16868. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  16869. amd: deconflictImportsOther,
  16870. cjs: deconflictImportsOther,
  16871. es: deconflictImportsEsmOrSystem,
  16872. iife: deconflictImportsOther,
  16873. system: deconflictImportsEsmOrSystem,
  16874. umd: deconflictImportsOther
  16875. };
  16876. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  16877. const reversedModules = [...modules].reverse();
  16878. for (const module of reversedModules) {
  16879. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  16880. }
  16881. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  16882. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  16883. for (const module of reversedModules) {
  16884. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  16885. }
  16886. }
  16887. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  16888. // This is needed for namespace reexports
  16889. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  16890. if (preserveModules || dependency instanceof ExternalChunk) {
  16891. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  16892. }
  16893. }
  16894. for (const variable of imports) {
  16895. const module = variable.module;
  16896. const name = variable.name;
  16897. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  16898. variable.setRenderNames(null, (module instanceof ExternalModule
  16899. ? externalChunkByModule.get(module)
  16900. : chunkByModule.get(module)).variableName);
  16901. }
  16902. else if (module instanceof ExternalModule && name === 'default') {
  16903. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  16904. ? module.suggestedVariableName + '__default'
  16905. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  16906. }
  16907. else {
  16908. variable.setRenderNames(null, getSafeName(makeLegal(name), usedNames, variable.forbiddenNames));
  16909. }
  16910. }
  16911. for (const variable of syntheticExports) {
  16912. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  16913. }
  16914. }
  16915. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  16916. for (const chunk of dependencies) {
  16917. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  16918. }
  16919. for (const chunk of deconflictedNamespace) {
  16920. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  16921. }
  16922. for (const externalModule of deconflictedDefault) {
  16923. externalModule.defaultVariableName =
  16924. deconflictedNamespace.has(externalModule) &&
  16925. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  16926. ? externalModule.namespaceVariableName
  16927. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  16928. }
  16929. for (const variable of imports) {
  16930. const module = variable.module;
  16931. if (module instanceof ExternalModule) {
  16932. const chunk = externalChunkByModule.get(module);
  16933. const name = variable.name;
  16934. if (name === 'default') {
  16935. const moduleInterop = interop(module.id);
  16936. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  16937. ? chunk.defaultVariableName
  16938. : chunk.variableName;
  16939. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  16940. variable.setRenderNames(variableName, 'default');
  16941. }
  16942. else {
  16943. variable.setRenderNames(null, variableName);
  16944. }
  16945. }
  16946. else if (name === '*') {
  16947. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  16948. ? chunk.namespaceVariableName
  16949. : chunk.variableName);
  16950. }
  16951. else {
  16952. // if the second parameter is `null`, it uses its "name" for the property name
  16953. variable.setRenderNames(chunk.variableName, null);
  16954. }
  16955. }
  16956. else {
  16957. const chunk = chunkByModule.get(module);
  16958. if (preserveModules && variable.isNamespace) {
  16959. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  16960. }
  16961. else if (chunk.exportMode === 'default') {
  16962. variable.setRenderNames(null, chunk.variableName);
  16963. }
  16964. else {
  16965. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  16966. }
  16967. }
  16968. }
  16969. }
  16970. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  16971. for (const module of modules) {
  16972. for (const variable of module.scope.variables.values()) {
  16973. if (variable.included &&
  16974. // this will only happen for exports in some formats
  16975. !(variable.renderBaseName ||
  16976. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  16977. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  16978. }
  16979. }
  16980. if (includedNamespaces.has(module)) {
  16981. const namespace = module.namespace;
  16982. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  16983. }
  16984. }
  16985. }
  16986. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  16987. let nameIndex = 0;
  16988. for (const variable of exports) {
  16989. let [exportName] = variable.name;
  16990. if (exportsByName.has(exportName)) {
  16991. do {
  16992. exportName = toBase64(++nameIndex);
  16993. // skip past leading number identifiers
  16994. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  16995. nameIndex += 9 * 64 ** (exportName.length - 1);
  16996. exportName = toBase64(nameIndex);
  16997. }
  16998. } while (RESERVED_NAMES.has(exportName) || exportsByName.has(exportName));
  16999. }
  17000. exportsByName.set(exportName, variable);
  17001. exportNamesByVariable.set(variable, [exportName]);
  17002. }
  17003. }
  17004. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  17005. for (const variable of exports) {
  17006. let nameIndex = 0;
  17007. let exportName = variable.name;
  17008. while (exportsByName.has(exportName)) {
  17009. exportName = variable.name + '$' + ++nameIndex;
  17010. }
  17011. exportsByName.set(exportName, variable);
  17012. exportNamesByVariable.set(variable, [exportName]);
  17013. }
  17014. }
  17015. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  17016. const exportKeys = chunk.getExportNames();
  17017. if (exportMode === 'default') {
  17018. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  17019. return error(logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  17020. }
  17021. }
  17022. else if (exportMode === 'none' && exportKeys.length > 0) {
  17023. return error(logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  17024. }
  17025. if (exportMode === 'auto') {
  17026. if (exportKeys.length === 0) {
  17027. exportMode = 'none';
  17028. }
  17029. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  17030. exportMode = 'default';
  17031. }
  17032. else {
  17033. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  17034. log(LOGLEVEL_WARN, logMixedExport(facadeModuleId, name));
  17035. }
  17036. exportMode = 'named';
  17037. }
  17038. }
  17039. return exportMode;
  17040. }
  17041. function guessIndentString(code) {
  17042. const lines = code.split('\n');
  17043. const tabbed = lines.filter(line => /^\t+/.test(line));
  17044. const spaced = lines.filter(line => /^ {2,}/.test(line));
  17045. if (tabbed.length === 0 && spaced.length === 0) {
  17046. return null;
  17047. }
  17048. // More lines tabbed than spaced? Assume tabs, and
  17049. // default to tabs in the case of a tie (or nothing
  17050. // to go on)
  17051. if (tabbed.length >= spaced.length) {
  17052. return '\t';
  17053. }
  17054. // Otherwise, we need to guess the multiple
  17055. const min = spaced.reduce((previous, current) => {
  17056. const numberSpaces = /^ +/.exec(current)[0].length;
  17057. return Math.min(numberSpaces, previous);
  17058. }, Infinity);
  17059. return ' '.repeat(min);
  17060. }
  17061. function getIndentString(modules, options) {
  17062. if (options.indent !== true)
  17063. return options.indent;
  17064. for (const module of modules) {
  17065. const indent = guessIndentString(module.originalCode);
  17066. if (indent !== null)
  17067. return indent;
  17068. }
  17069. return '\t';
  17070. }
  17071. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  17072. const staticDependencyBlocks = [];
  17073. const handledDependencies = new Set();
  17074. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  17075. const module = orderedModules[modulePos];
  17076. if (!handledDependencies.has(module)) {
  17077. const staticDependencies = [];
  17078. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  17079. staticDependencyBlocks.unshift(staticDependencies);
  17080. }
  17081. }
  17082. const dependencies = new Set();
  17083. for (const block of staticDependencyBlocks) {
  17084. for (const dependency of block) {
  17085. dependencies.add(dependency);
  17086. }
  17087. }
  17088. return dependencies;
  17089. }
  17090. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  17091. const dependencies = module.getDependenciesToBeIncluded();
  17092. for (const dependency of dependencies) {
  17093. if (dependency instanceof ExternalModule) {
  17094. staticDependencies.push(externalChunkByModule.get(dependency));
  17095. continue;
  17096. }
  17097. const dependencyChunk = chunkByModule.get(dependency);
  17098. if (dependencyChunk !== chunk) {
  17099. staticDependencies.push(dependencyChunk);
  17100. continue;
  17101. }
  17102. if (!handledModules.has(dependency)) {
  17103. handledModules.add(dependency);
  17104. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  17105. }
  17106. }
  17107. }
  17108. // Four random characters from the private use area to minimize risk of
  17109. // conflicts
  17110. const hashPlaceholderLeft = '!~{';
  17111. const hashPlaceholderRight = '}~';
  17112. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  17113. // This is the size of a 128-bits xxhash with base64url encoding
  17114. const MAX_HASH_SIZE = 21;
  17115. const DEFAULT_HASH_SIZE = 8;
  17116. const getHashPlaceholderGenerator = () => {
  17117. let nextIndex = 0;
  17118. return (optionName, hashSize) => {
  17119. if (hashSize > MAX_HASH_SIZE) {
  17120. return error(logFailedValidation(`Hashes cannot be longer than ${MAX_HASH_SIZE} characters, received ${hashSize}. Check the "${optionName}" option.`));
  17121. }
  17122. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  17123. if (placeholder.length > hashSize) {
  17124. 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.`));
  17125. }
  17126. return placeholder;
  17127. };
  17128. };
  17129. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${MAX_HASH_SIZE - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  17130. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  17131. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  17132. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  17133. const containedPlaceholders = new Set();
  17134. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  17135. if (placeholders.has(placeholder)) {
  17136. containedPlaceholders.add(placeholder);
  17137. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  17138. }
  17139. return placeholder;
  17140. });
  17141. return { containedPlaceholders, transformedCode };
  17142. };
  17143. const lowercaseBundleKeys = Symbol('bundleKeys');
  17144. const FILE_PLACEHOLDER = {
  17145. type: 'placeholder'
  17146. };
  17147. const getOutputBundle = (outputBundleBase) => {
  17148. const reservedLowercaseBundleKeys = new Set();
  17149. return new Proxy(outputBundleBase, {
  17150. deleteProperty(target, key) {
  17151. if (typeof key === 'string') {
  17152. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  17153. }
  17154. return Reflect.deleteProperty(target, key);
  17155. },
  17156. get(target, key) {
  17157. if (key === lowercaseBundleKeys) {
  17158. return reservedLowercaseBundleKeys;
  17159. }
  17160. return Reflect.get(target, key);
  17161. },
  17162. set(target, key, value) {
  17163. if (typeof key === 'string') {
  17164. reservedLowercaseBundleKeys.add(key.toLowerCase());
  17165. }
  17166. return Reflect.set(target, key, value);
  17167. }
  17168. });
  17169. };
  17170. const removeUnreferencedAssets = (outputBundle) => {
  17171. const unreferencedAssets = new Set();
  17172. const bundleEntries = Object.values(outputBundle);
  17173. for (const asset of bundleEntries) {
  17174. if (asset.type === 'asset' && asset.needsCodeReference) {
  17175. unreferencedAssets.add(asset.fileName);
  17176. }
  17177. }
  17178. for (const chunk of bundleEntries) {
  17179. if (chunk.type === 'chunk') {
  17180. for (const referencedFile of chunk.referencedFiles) {
  17181. if (unreferencedAssets.has(referencedFile)) {
  17182. unreferencedAssets.delete(referencedFile);
  17183. }
  17184. }
  17185. }
  17186. }
  17187. for (const file of unreferencedAssets) {
  17188. delete outputBundle[file];
  17189. }
  17190. };
  17191. function renderNamePattern(pattern, patternName, replacements) {
  17192. if (isPathFragment(pattern))
  17193. 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.`));
  17194. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  17195. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  17196. return error(logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  17197. }
  17198. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  17199. if (isPathFragment(replacement))
  17200. return error(logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  17201. return replacement;
  17202. });
  17203. }
  17204. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  17205. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  17206. return name;
  17207. const extension = extname(name);
  17208. name = name.slice(0, Math.max(0, name.length - extension.length));
  17209. let uniqueName, uniqueIndex = 1;
  17210. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  17211. ;
  17212. return uniqueName;
  17213. }
  17214. const NON_ASSET_EXTENSIONS = new Set([
  17215. '.js',
  17216. '.jsx',
  17217. '.ts',
  17218. '.tsx',
  17219. '.mjs',
  17220. '.mts',
  17221. '.cjs',
  17222. '.cts'
  17223. ]);
  17224. function getGlobalName(chunk, globals, hasExports, log) {
  17225. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  17226. if (globalName) {
  17227. return globalName;
  17228. }
  17229. if (hasExports) {
  17230. log(LOGLEVEL_WARN, logMissingGlobalName(chunk.id, chunk.variableName));
  17231. return chunk.variableName;
  17232. }
  17233. }
  17234. class Chunk {
  17235. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  17236. this.orderedModules = orderedModules;
  17237. this.inputOptions = inputOptions;
  17238. this.outputOptions = outputOptions;
  17239. this.unsetOptions = unsetOptions;
  17240. this.pluginDriver = pluginDriver;
  17241. this.modulesById = modulesById;
  17242. this.chunkByModule = chunkByModule;
  17243. this.externalChunkByModule = externalChunkByModule;
  17244. this.facadeChunkByModule = facadeChunkByModule;
  17245. this.includedNamespaces = includedNamespaces;
  17246. this.manualChunkAlias = manualChunkAlias;
  17247. this.getPlaceholder = getPlaceholder;
  17248. this.bundle = bundle;
  17249. this.inputBase = inputBase;
  17250. this.snippets = snippets;
  17251. this.dependencies = new Set();
  17252. this.entryModules = [];
  17253. this.exportMode = 'named';
  17254. this.facadeModule = null;
  17255. this.namespaceVariableName = '';
  17256. this.variableName = '';
  17257. this.accessedGlobalsByScope = new Map();
  17258. this.dynamicEntryModules = [];
  17259. this.dynamicName = null;
  17260. this.exportNamesByVariable = new Map();
  17261. this.exports = new Set();
  17262. this.exportsByName = new Map();
  17263. this.fileName = null;
  17264. this.implicitEntryModules = [];
  17265. this.implicitlyLoadedBefore = new Set();
  17266. this.imports = new Set();
  17267. this.includedDynamicImports = null;
  17268. this.includedReexportsByModule = new Map();
  17269. // This may be updated in the constructor
  17270. this.isEmpty = true;
  17271. this.name = null;
  17272. this.needsExportsShim = false;
  17273. this.preRenderedChunkInfo = null;
  17274. this.preliminaryFileName = null;
  17275. this.preliminarySourcemapFileName = null;
  17276. this.renderedChunkInfo = null;
  17277. this.renderedDependencies = null;
  17278. this.renderedModules = Object.create(null);
  17279. this.sortedExportNames = null;
  17280. this.strictFacade = false;
  17281. /** Modules with 'allow-extension' that should have preserved exports within the chunk */
  17282. this.allowExtensionModules = new Set();
  17283. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  17284. const chunkModules = new Set(orderedModules);
  17285. for (const module of orderedModules) {
  17286. chunkByModule.set(module, this);
  17287. if (module.namespace.included && !outputOptions.preserveModules) {
  17288. includedNamespaces.add(module);
  17289. }
  17290. if (this.isEmpty && module.isIncluded()) {
  17291. this.isEmpty = false;
  17292. }
  17293. if (module.info.isEntry || outputOptions.preserveModules) {
  17294. this.entryModules.push(module);
  17295. }
  17296. for (const importer of module.includedDynamicImporters) {
  17297. if (!chunkModules.has(importer)) {
  17298. this.dynamicEntryModules.push(module);
  17299. // Modules with synthetic exports need an artificial namespace for dynamic imports
  17300. if (module.info.syntheticNamedExports) {
  17301. includedNamespaces.add(module);
  17302. this.exports.add(module.namespace);
  17303. }
  17304. }
  17305. }
  17306. if (module.implicitlyLoadedAfter.size > 0) {
  17307. this.implicitEntryModules.push(module);
  17308. }
  17309. }
  17310. this.suggestedVariableName = makeLegal(this.generateVariableName());
  17311. }
  17312. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  17313. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  17314. chunk.assignFacadeName(facadeName, facadedModule);
  17315. if (!facadeChunkByModule.has(facadedModule)) {
  17316. facadeChunkByModule.set(facadedModule, chunk);
  17317. }
  17318. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  17319. chunk.dependencies.add(dependency instanceof Module
  17320. ? chunkByModule.get(dependency)
  17321. : externalChunkByModule.get(dependency));
  17322. }
  17323. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  17324. facadedModule.info.moduleSideEffects &&
  17325. facadedModule.hasEffects()) {
  17326. chunk.dependencies.add(chunkByModule.get(facadedModule));
  17327. }
  17328. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  17329. chunk.facadeModule = facadedModule;
  17330. chunk.strictFacade = true;
  17331. return chunk;
  17332. }
  17333. canModuleBeFacade(module, exposedVariables) {
  17334. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  17335. // All exports of this chunk need to be exposed by the candidate module
  17336. for (const exposedVariable of this.exports) {
  17337. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  17338. return false;
  17339. }
  17340. }
  17341. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  17342. for (const exposedVariable of exposedVariables) {
  17343. if (!(exposedVariable.module === module ||
  17344. moduleExportNamesByVariable.has(exposedVariable) ||
  17345. (exposedVariable instanceof SyntheticNamedExportVariable &&
  17346. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  17347. return false;
  17348. }
  17349. }
  17350. return true;
  17351. }
  17352. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  17353. const renderedChunkInfo = this.getRenderedChunkInfo();
  17354. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  17355. const preliminaryFileName = renderedChunkInfo.fileName;
  17356. const fileName = (this.fileName = finalize(preliminaryFileName));
  17357. return {
  17358. ...renderedChunkInfo,
  17359. code,
  17360. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  17361. fileName,
  17362. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  17363. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  17364. finalize(fileName),
  17365. bindings
  17366. ])),
  17367. imports: renderedChunkInfo.imports.map(finalize),
  17368. map,
  17369. preliminaryFileName,
  17370. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  17371. sourcemapFileName
  17372. };
  17373. }
  17374. generateExports() {
  17375. this.sortedExportNames = null;
  17376. const remainingExports = new Set(this.exports);
  17377. if (this.facadeModule !== null &&
  17378. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  17379. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  17380. for (const [variable, exportNames] of exportNamesByVariable) {
  17381. this.exportNamesByVariable.set(variable, [...exportNames]);
  17382. for (const exportName of exportNames) {
  17383. this.exportsByName.set(exportName, variable);
  17384. }
  17385. remainingExports.delete(variable);
  17386. }
  17387. }
  17388. for (const module of this.allowExtensionModules) {
  17389. const exportNamesByVariable = module.getExportNamesByVariable();
  17390. for (const [variable, exportNames] of exportNamesByVariable) {
  17391. this.exportNamesByVariable.set(variable, [...exportNames]);
  17392. for (const exportName of exportNames) {
  17393. this.exportsByName.set(exportName, variable);
  17394. }
  17395. remainingExports.delete(variable);
  17396. }
  17397. }
  17398. if (this.outputOptions.minifyInternalExports) {
  17399. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  17400. }
  17401. else {
  17402. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  17403. }
  17404. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  17405. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  17406. }
  17407. generateFacades() {
  17408. const facades = [];
  17409. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  17410. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  17411. for (const module of entryModules) {
  17412. if (module.preserveSignature === 'allow-extension') {
  17413. const canPreserveExports = this.canPreserveModuleExports(module);
  17414. if (canPreserveExports &&
  17415. !module.chunkFileNames.size &&
  17416. module.chunkNames.every(({ isUserDefined }) => !isUserDefined)) {
  17417. this.allowExtensionModules.add(module);
  17418. if (!this.facadeModule) {
  17419. this.facadeModule = module;
  17420. this.strictFacade = false;
  17421. this.assignFacadeName({}, module, this.outputOptions.preserveModules);
  17422. }
  17423. this.facadeChunkByModule.set(module, this);
  17424. continue;
  17425. }
  17426. }
  17427. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  17428. // mapping must run after Set 'name' dedupe
  17429. name => ({
  17430. name
  17431. }));
  17432. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  17433. requiredFacades.push({});
  17434. }
  17435. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  17436. if (requiredFacades.length === 0) {
  17437. requiredFacades.push({});
  17438. }
  17439. if (!this.facadeModule) {
  17440. const needsStrictFacade = !this.outputOptions.preserveModules &&
  17441. (module.preserveSignature === 'strict' ||
  17442. (module.preserveSignature === 'exports-only' &&
  17443. module.getExportNamesByVariable().size > 0));
  17444. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  17445. this.facadeModule = module;
  17446. this.facadeChunkByModule.set(module, this);
  17447. if (module.preserveSignature) {
  17448. this.strictFacade = needsStrictFacade;
  17449. }
  17450. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  17451. }
  17452. }
  17453. for (const facadeName of requiredFacades) {
  17454. 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));
  17455. }
  17456. }
  17457. for (const module of this.dynamicEntryModules) {
  17458. if (module.info.syntheticNamedExports)
  17459. continue;
  17460. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  17461. this.facadeModule = module;
  17462. this.facadeChunkByModule.set(module, this);
  17463. this.strictFacade = true;
  17464. this.dynamicName = getChunkNameFromModule(module);
  17465. }
  17466. else if (this.facadeModule === module &&
  17467. !this.strictFacade &&
  17468. this.canModuleBeFacade(module, exposedVariables)) {
  17469. this.strictFacade = true;
  17470. }
  17471. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  17472. this.includedNamespaces.add(module);
  17473. this.exports.add(module.namespace);
  17474. }
  17475. }
  17476. if (!this.outputOptions.preserveModules) {
  17477. this.addNecessaryImportsForFacades();
  17478. }
  17479. return facades;
  17480. }
  17481. canPreserveModuleExports(module) {
  17482. const exportNamesByVariable = module.getExportNamesByVariable();
  17483. // Check for conflicts - an export name is a conflict if it points to a different module or definition
  17484. for (const [variable, exportNames] of exportNamesByVariable) {
  17485. for (const exportName of exportNames) {
  17486. const existingVariable = this.exportsByName.get(exportName);
  17487. // It's ok if the same export name in two modules references the exact same variable
  17488. if (existingVariable && existingVariable !== variable) {
  17489. return false;
  17490. }
  17491. }
  17492. }
  17493. // No actual conflicts found, add export names for future conflict checks
  17494. for (const [variable, exportNames] of exportNamesByVariable) {
  17495. for (const exportName of exportNames) {
  17496. this.exportsByName.set(exportName, variable);
  17497. }
  17498. }
  17499. return true;
  17500. }
  17501. getChunkName() {
  17502. return (this.name ??= this.outputOptions.sanitizeFileName(this.getFallbackChunkName()));
  17503. }
  17504. getExportNames() {
  17505. return (this.sortedExportNames ??= [...this.exportsByName.keys()].sort());
  17506. }
  17507. getFileName() {
  17508. return this.fileName || this.getPreliminaryFileName().fileName;
  17509. }
  17510. getImportPath(importer) {
  17511. return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  17512. }
  17513. getPreliminaryFileName() {
  17514. if (this.preliminaryFileName) {
  17515. return this.preliminaryFileName;
  17516. }
  17517. let fileName;
  17518. let hashPlaceholder = null;
  17519. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  17520. if (file) {
  17521. fileName = basename(file);
  17522. }
  17523. else if (this.fileName === null) {
  17524. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  17525. ? [entryFileNames, 'output.entryFileNames']
  17526. : [chunkFileNames, 'output.chunkFileNames'];
  17527. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  17528. format: () => format,
  17529. hash: size => hashPlaceholder ||
  17530. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  17531. name: () => this.getChunkName()
  17532. });
  17533. if (!hashPlaceholder) {
  17534. fileName = makeUnique(fileName, this.bundle);
  17535. }
  17536. }
  17537. else {
  17538. fileName = this.fileName;
  17539. }
  17540. if (!hashPlaceholder) {
  17541. this.bundle[fileName] = FILE_PLACEHOLDER;
  17542. }
  17543. // Caching is essential to not conflict with the file name reservation above
  17544. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  17545. }
  17546. getPreliminarySourcemapFileName() {
  17547. if (this.preliminarySourcemapFileName) {
  17548. return this.preliminarySourcemapFileName;
  17549. }
  17550. let sourcemapFileName = null;
  17551. let hashPlaceholder = null;
  17552. const { sourcemapFileNames, format } = this.outputOptions;
  17553. if (sourcemapFileNames) {
  17554. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  17555. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  17556. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  17557. format: () => format,
  17558. hash: size => hashPlaceholder ||
  17559. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  17560. name: () => this.getChunkName()
  17561. });
  17562. if (!hashPlaceholder) {
  17563. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  17564. }
  17565. }
  17566. else {
  17567. return null;
  17568. }
  17569. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  17570. }
  17571. getRenderedChunkInfo() {
  17572. if (this.renderedChunkInfo) {
  17573. return this.renderedChunkInfo;
  17574. }
  17575. return (this.renderedChunkInfo = {
  17576. ...this.getPreRenderedChunkInfo(),
  17577. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  17578. fileName: this.getFileName(),
  17579. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  17580. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  17581. imports: Array.from(this.dependencies, resolveFileName),
  17582. modules: this.renderedModules,
  17583. referencedFiles: this.getReferencedFiles()
  17584. });
  17585. }
  17586. getVariableExportName(variable) {
  17587. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  17588. return '*';
  17589. }
  17590. return this.exportNamesByVariable.get(variable)[0];
  17591. }
  17592. link() {
  17593. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  17594. for (const module of this.orderedModules) {
  17595. this.addImplicitlyLoadedBeforeFromModule(module);
  17596. this.setUpChunkImportsAndExportsForModule(module);
  17597. }
  17598. }
  17599. inlineTransitiveImports() {
  17600. const { facadeModule, dependencies, outputOptions } = this;
  17601. const { hoistTransitiveImports, preserveModules } = outputOptions;
  17602. // for static and dynamic entry points, add transitive dependencies to this
  17603. // chunk's dependencies to avoid loading latency
  17604. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  17605. for (const dep of dependencies) {
  17606. if (dep instanceof Chunk)
  17607. this.inlineChunkDependencies(dep);
  17608. }
  17609. }
  17610. }
  17611. async render() {
  17612. const { exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  17613. const { format, preserveModules } = outputOptions;
  17614. const preliminaryFileName = this.getPreliminaryFileName();
  17615. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  17616. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  17617. const renderedDependencies = [...this.getRenderedDependencies().values()];
  17618. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  17619. let hasExports = renderedExports.length > 0;
  17620. let hasDefaultExport = false;
  17621. for (const renderedDependency of renderedDependencies) {
  17622. const { reexports } = renderedDependency;
  17623. if (reexports?.length) {
  17624. hasExports = true;
  17625. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  17626. hasDefaultExport = true;
  17627. }
  17628. if (format === 'es') {
  17629. renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  17630. }
  17631. }
  17632. }
  17633. if (!hasDefaultExport) {
  17634. for (const { exported } of renderedExports) {
  17635. if (exported === 'default') {
  17636. hasDefaultExport = true;
  17637. break;
  17638. }
  17639. }
  17640. }
  17641. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  17642. finalisers[format](renderedSource, {
  17643. accessedGlobals,
  17644. dependencies: renderedDependencies,
  17645. exports: renderedExports,
  17646. hasDefaultExport,
  17647. hasExports,
  17648. id: preliminaryFileName.fileName,
  17649. indent,
  17650. intro,
  17651. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  17652. isModuleFacade: facadeModule !== null,
  17653. log: onLog,
  17654. namedExportsMode: exportMode !== 'default',
  17655. outro,
  17656. snippets,
  17657. usesTopLevelAwait
  17658. }, outputOptions);
  17659. if (banner)
  17660. magicString.prepend(banner);
  17661. if (format === 'es' || format === 'cjs') {
  17662. const shebang = facadeModule !== null && facadeModule.info.isEntry && facadeModule.shebang;
  17663. if (shebang) {
  17664. magicString.prepend(`#!${shebang}\n`);
  17665. }
  17666. }
  17667. if (footer)
  17668. magicString.append(footer);
  17669. return {
  17670. chunk: this,
  17671. magicString,
  17672. preliminaryFileName,
  17673. preliminarySourcemapFileName,
  17674. usedModules
  17675. };
  17676. }
  17677. addImplicitlyLoadedBeforeFromModule(baseModule) {
  17678. const { chunkByModule, implicitlyLoadedBefore } = this;
  17679. for (const module of baseModule.implicitlyLoadedBefore) {
  17680. const chunk = chunkByModule.get(module);
  17681. if (chunk && chunk !== this) {
  17682. implicitlyLoadedBefore.add(chunk);
  17683. }
  17684. }
  17685. }
  17686. addNecessaryImportsForFacades() {
  17687. for (const [module, variables] of this.includedReexportsByModule) {
  17688. if (this.includedNamespaces.has(module)) {
  17689. for (const variable of variables) {
  17690. this.imports.add(variable);
  17691. }
  17692. }
  17693. }
  17694. }
  17695. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  17696. if (fileName) {
  17697. this.fileName = fileName;
  17698. }
  17699. else {
  17700. this.name = this.outputOptions.sanitizeFileName(name ||
  17701. (preservePath
  17702. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  17703. : getChunkNameFromModule(facadedModule)));
  17704. }
  17705. }
  17706. checkCircularDependencyImport(variable, importingModule) {
  17707. const variableModule = variable.module;
  17708. if (variableModule instanceof Module) {
  17709. const exportChunk = this.chunkByModule.get(variableModule);
  17710. let alternativeReexportModule;
  17711. do {
  17712. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  17713. if (alternativeReexportModule) {
  17714. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  17715. if (exportingChunk !== exportChunk) {
  17716. this.inputOptions.onLog(LOGLEVEL_WARN, logCyclicCrossChunkReexport(
  17717. // Namespaces do not have an export name
  17718. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  17719. }
  17720. importingModule = alternativeReexportModule;
  17721. }
  17722. } while (alternativeReexportModule);
  17723. }
  17724. }
  17725. ensureReexportsAreAvailableForModule(module) {
  17726. const includedReexports = [];
  17727. const map = module.getExportNamesByVariable();
  17728. for (const exportedVariable of map.keys()) {
  17729. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  17730. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  17731. this.checkCircularDependencyImport(importedVariable, module);
  17732. // When preserving modules, we do not create namespace objects but directly
  17733. // use the actual namespaces, which would be broken by this logic.
  17734. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  17735. const exportingModule = importedVariable.module;
  17736. if (exportingModule instanceof Module) {
  17737. const chunk = this.chunkByModule.get(exportingModule);
  17738. if (chunk && chunk !== this) {
  17739. chunk.exports.add(importedVariable);
  17740. includedReexports.push(importedVariable);
  17741. if (isSynthetic) {
  17742. this.imports.add(importedVariable);
  17743. }
  17744. }
  17745. }
  17746. }
  17747. }
  17748. if (includedReexports.length > 0) {
  17749. this.includedReexportsByModule.set(module, includedReexports);
  17750. }
  17751. }
  17752. generateVariableName() {
  17753. if (this.manualChunkAlias) {
  17754. return this.manualChunkAlias;
  17755. }
  17756. const moduleForNaming = this.entryModules[0] ||
  17757. this.implicitEntryModules[0] ||
  17758. this.dynamicEntryModules[0] ||
  17759. this.orderedModules[this.orderedModules.length - 1];
  17760. if (moduleForNaming) {
  17761. return getChunkNameFromModule(moduleForNaming);
  17762. }
  17763. return 'chunk';
  17764. }
  17765. getChunkExportDeclarations(format) {
  17766. const exports = [];
  17767. for (const exportName of this.getExportNames()) {
  17768. if (exportName[0] === '*')
  17769. continue;
  17770. const variable = this.exportsByName.get(exportName);
  17771. if (!(variable instanceof SyntheticNamedExportVariable)) {
  17772. const module = variable.module;
  17773. if (module) {
  17774. const chunk = this.chunkByModule.get(module);
  17775. if (chunk !== this) {
  17776. if (!chunk || format !== 'es') {
  17777. continue;
  17778. }
  17779. const chunkDep = this.renderedDependencies.get(chunk);
  17780. if (!chunkDep) {
  17781. continue;
  17782. }
  17783. const { imports, reexports } = chunkDep;
  17784. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  17785. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  17786. if (!isImported) {
  17787. continue;
  17788. }
  17789. }
  17790. }
  17791. }
  17792. let expression = null;
  17793. let hoisted = false;
  17794. let local = variable.getName(this.snippets.getPropertyAccess);
  17795. if (variable instanceof LocalVariable) {
  17796. for (const declaration of variable.declarations) {
  17797. if (declaration.parent instanceof FunctionDeclaration ||
  17798. (declaration instanceof ExportDefaultDeclaration &&
  17799. declaration.declaration instanceof FunctionDeclaration)) {
  17800. hoisted = true;
  17801. break;
  17802. }
  17803. }
  17804. }
  17805. else if (variable instanceof SyntheticNamedExportVariable) {
  17806. expression = local;
  17807. if (format === 'es') {
  17808. local = variable.renderName;
  17809. }
  17810. }
  17811. exports.push({
  17812. exported: exportName,
  17813. expression,
  17814. hoisted,
  17815. local
  17816. });
  17817. }
  17818. return exports;
  17819. }
  17820. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  17821. const dependencies = new Set();
  17822. const deconflictedDefault = new Set();
  17823. const deconflictedNamespace = new Set();
  17824. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  17825. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  17826. const module = variable.module;
  17827. if (module instanceof ExternalModule) {
  17828. const chunk = this.externalChunkByModule.get(module);
  17829. dependencies.add(chunk);
  17830. if (addNonNamespacesAndInteropHelpers) {
  17831. if (variable.name === 'default') {
  17832. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  17833. deconflictedDefault.add(chunk);
  17834. }
  17835. }
  17836. else if (variable.isNamespace &&
  17837. namespaceInteropHelpersByInteropType[interop(module.id)] &&
  17838. (this.imports.has(variable) ||
  17839. !this.exportNamesByVariable.get(variable)?.every(name => name[0] === '*'))) {
  17840. // We only need to deconflict it if the namespace is actually
  17841. // created as a variable, i.e. because it is used internally or
  17842. // because it is reexported as an object
  17843. deconflictedNamespace.add(chunk);
  17844. }
  17845. }
  17846. }
  17847. else {
  17848. const chunk = this.chunkByModule.get(module);
  17849. if (chunk !== this) {
  17850. dependencies.add(chunk);
  17851. if (addNonNamespacesAndInteropHelpers &&
  17852. chunk.exportMode === 'default' &&
  17853. variable.isNamespace) {
  17854. deconflictedNamespace.add(chunk);
  17855. }
  17856. }
  17857. }
  17858. }
  17859. }
  17860. if (addDependenciesWithoutBindings) {
  17861. for (const dependency of this.dependencies) {
  17862. dependencies.add(dependency);
  17863. }
  17864. }
  17865. return { deconflictedDefault, deconflictedNamespace, dependencies };
  17866. }
  17867. getDynamicDependencies() {
  17868. return this.getIncludedDynamicImports()
  17869. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  17870. resolvedDynamicImport.chunk ||
  17871. resolvedDynamicImport.externalChunk ||
  17872. resolvedDynamicImport.resolution)
  17873. .filter((resolution) => resolution !== this &&
  17874. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  17875. }
  17876. getDynamicImportStringAndAttributes(resolution, fileName, node) {
  17877. const { externalImportAttributes } = this.outputOptions;
  17878. const keepExternalImportAttributes = ['es', 'cjs'].includes(this.outputOptions.format) && externalImportAttributes;
  17879. if (resolution instanceof ExternalModule) {
  17880. const chunk = this.externalChunkByModule.get(resolution);
  17881. const dynamicAttributes = chunk.getImportAttributes(this.snippets);
  17882. return [
  17883. `'${chunk.getImportPath(fileName)}'`,
  17884. dynamicAttributes || (keepExternalImportAttributes ? true : null)
  17885. ];
  17886. }
  17887. let attributes = null;
  17888. if (keepExternalImportAttributes) {
  17889. const attributesFromImportAttributes = getAttributesFromImportExpression(node);
  17890. attributes =
  17891. attributesFromImportAttributes === EMPTY_OBJECT
  17892. ? true
  17893. : formatAttributes(attributesFromImportAttributes, this.snippets);
  17894. }
  17895. return [resolution || '', attributes];
  17896. }
  17897. getFallbackChunkName() {
  17898. if (this.manualChunkAlias) {
  17899. return this.manualChunkAlias;
  17900. }
  17901. if (this.dynamicName) {
  17902. return this.dynamicName;
  17903. }
  17904. if (this.fileName) {
  17905. return getAliasName(this.fileName);
  17906. }
  17907. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  17908. }
  17909. getImportSpecifiers() {
  17910. const { interop } = this.outputOptions;
  17911. const importsByDependency = new Map();
  17912. for (const variable of this.imports) {
  17913. const module = variable.module;
  17914. let dependency;
  17915. let imported;
  17916. if (module instanceof ExternalModule) {
  17917. dependency = this.externalChunkByModule.get(module);
  17918. imported = variable.name;
  17919. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  17920. return error(logUnexpectedNamedImport(module.id, imported, false));
  17921. }
  17922. }
  17923. else {
  17924. dependency = this.chunkByModule.get(module);
  17925. imported = dependency.getVariableExportName(variable);
  17926. }
  17927. getOrCreate(importsByDependency, dependency, getNewArray).push({
  17928. imported,
  17929. local: variable.getName(this.snippets.getPropertyAccess)
  17930. });
  17931. }
  17932. return importsByDependency;
  17933. }
  17934. getIncludedDynamicImports() {
  17935. if (this.includedDynamicImports) {
  17936. return this.includedDynamicImports;
  17937. }
  17938. const includedDynamicImports = [];
  17939. for (const module of this.orderedModules) {
  17940. for (const { node, resolution } of module.dynamicImports) {
  17941. if (!node.included) {
  17942. continue;
  17943. }
  17944. includedDynamicImports.push(resolution instanceof Module
  17945. ? {
  17946. chunk: this.chunkByModule.get(resolution),
  17947. externalChunk: null,
  17948. facadeChunk: this.facadeChunkByModule.get(resolution),
  17949. node,
  17950. resolution
  17951. }
  17952. : resolution instanceof ExternalModule
  17953. ? {
  17954. chunk: null,
  17955. externalChunk: this.externalChunkByModule.get(resolution),
  17956. facadeChunk: null,
  17957. node,
  17958. resolution
  17959. }
  17960. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  17961. }
  17962. }
  17963. return (this.includedDynamicImports = includedDynamicImports);
  17964. }
  17965. getPreRenderedChunkInfo() {
  17966. if (this.preRenderedChunkInfo) {
  17967. return this.preRenderedChunkInfo;
  17968. }
  17969. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  17970. return (this.preRenderedChunkInfo = {
  17971. exports: this.getExportNames(),
  17972. facadeModuleId: facadeModule && facadeModule.id,
  17973. isDynamicEntry: dynamicEntryModules.length > 0,
  17974. isEntry: !!facadeModule?.info.isEntry,
  17975. isImplicitEntry: implicitEntryModules.length > 0,
  17976. moduleIds: orderedModules.map(({ id }) => id),
  17977. name: this.getChunkName(),
  17978. type: 'chunk'
  17979. });
  17980. }
  17981. getPreserveModulesChunkNameFromModule(module) {
  17982. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  17983. if (predefinedChunkName)
  17984. return predefinedChunkName;
  17985. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  17986. const sanitizedId = sanitizeFileName(normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  17987. const extensionName = extname(sanitizedId);
  17988. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  17989. ? sanitizedId.slice(0, -extensionName.length)
  17990. : sanitizedId;
  17991. if (isAbsolute$1(idWithoutExtension)) {
  17992. if (preserveModulesRoot && resolve$1(idWithoutExtension).startsWith(preserveModulesRoot)) {
  17993. return idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '');
  17994. }
  17995. else {
  17996. // handle edge case in Windows
  17997. if (this.inputBase === '/' && idWithoutExtension[0] !== '/') {
  17998. return relative$1(this.inputBase, idWithoutExtension.replace(/^[a-zA-Z]:[/\\]/, '/'));
  17999. }
  18000. return relative$1(this.inputBase, idWithoutExtension);
  18001. }
  18002. }
  18003. else {
  18004. return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + basename(idWithoutExtension));
  18005. }
  18006. }
  18007. getReexportSpecifiers() {
  18008. const { externalLiveBindings, interop } = this.outputOptions;
  18009. const reexportSpecifiers = new Map();
  18010. for (let exportName of this.getExportNames()) {
  18011. let dependency;
  18012. let imported;
  18013. let needsLiveBinding = false;
  18014. if (exportName[0] === '*') {
  18015. const id = exportName.slice(1);
  18016. if (interop(id) === 'defaultOnly') {
  18017. this.inputOptions.onLog(LOGLEVEL_WARN, logUnexpectedNamespaceReexport(id));
  18018. }
  18019. needsLiveBinding = externalLiveBindings;
  18020. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  18021. imported = exportName = '*';
  18022. }
  18023. else {
  18024. const variable = this.exportsByName.get(exportName);
  18025. if (variable instanceof SyntheticNamedExportVariable)
  18026. continue;
  18027. const module = variable.module;
  18028. if (module instanceof Module) {
  18029. dependency = this.chunkByModule.get(module);
  18030. if (dependency === this)
  18031. continue;
  18032. imported = dependency.getVariableExportName(variable);
  18033. needsLiveBinding = variable.isReassigned;
  18034. }
  18035. else {
  18036. dependency = this.externalChunkByModule.get(module);
  18037. imported = variable.name;
  18038. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  18039. return error(logUnexpectedNamedImport(module.id, imported, true));
  18040. }
  18041. needsLiveBinding =
  18042. externalLiveBindings &&
  18043. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  18044. }
  18045. }
  18046. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  18047. imported,
  18048. needsLiveBinding,
  18049. reexported: exportName
  18050. });
  18051. }
  18052. return reexportSpecifiers;
  18053. }
  18054. getReferencedFiles() {
  18055. const referencedFiles = new Set();
  18056. for (const module of this.orderedModules) {
  18057. for (const meta of module.importMetas) {
  18058. const fileName = meta.getReferencedFileName(this.pluginDriver);
  18059. if (fileName) {
  18060. referencedFiles.add(fileName);
  18061. }
  18062. }
  18063. }
  18064. return [...referencedFiles];
  18065. }
  18066. getRenderedDependencies() {
  18067. if (this.renderedDependencies) {
  18068. return this.renderedDependencies;
  18069. }
  18070. const importSpecifiers = this.getImportSpecifiers();
  18071. const reexportSpecifiers = this.getReexportSpecifiers();
  18072. const renderedDependencies = new Map();
  18073. const fileName = this.getFileName();
  18074. for (const dependency of this.dependencies) {
  18075. const imports = importSpecifiers.get(dependency) || null;
  18076. const reexports = reexportSpecifiers.get(dependency) || null;
  18077. const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
  18078. const importPath = dependency.getImportPath(fileName);
  18079. renderedDependencies.set(dependency, {
  18080. attributes: dependency instanceof ExternalChunk
  18081. ? dependency.getImportAttributes(this.snippets)
  18082. : null,
  18083. defaultVariableName: dependency.defaultVariableName,
  18084. globalName: dependency instanceof ExternalChunk &&
  18085. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  18086. getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  18087. importPath,
  18088. imports,
  18089. isChunk: dependency instanceof Chunk,
  18090. name: dependency.variableName,
  18091. namedExportsMode,
  18092. namespaceVariableName: dependency.namespaceVariableName,
  18093. reexports
  18094. });
  18095. }
  18096. return (this.renderedDependencies = renderedDependencies);
  18097. }
  18098. inlineChunkDependencies(chunk) {
  18099. for (const dep of chunk.dependencies) {
  18100. if (this.dependencies.has(dep))
  18101. continue;
  18102. this.dependencies.add(dep);
  18103. if (dep instanceof Chunk) {
  18104. this.inlineChunkDependencies(dep);
  18105. }
  18106. }
  18107. }
  18108. // This method changes properties on the AST before rendering and must not be async
  18109. renderModules(fileName) {
  18110. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  18111. const { compact, format, freeze, generatedCode: { symbols }, importAttributesKey } = outputOptions;
  18112. const { _, cnst, n } = snippets;
  18113. this.setDynamicImportResolutions(fileName);
  18114. this.setImportMetaResolutions(fileName);
  18115. this.setIdentifierRenderResolutions();
  18116. const magicString = new Bundle$1({ separator: `${n}${n}` });
  18117. const indent = getIndentString(orderedModules, outputOptions);
  18118. const usedModules = [];
  18119. let hoistedSource = '';
  18120. const accessedGlobals = new Set();
  18121. const renderedModuleSources = new Map();
  18122. const renderOptions = {
  18123. accessedDocumentCurrentScript: false,
  18124. exportNamesByVariable,
  18125. format,
  18126. freeze,
  18127. importAttributesKey,
  18128. indent,
  18129. pluginDriver,
  18130. snippets,
  18131. symbols,
  18132. useOriginalName: null
  18133. };
  18134. let usesTopLevelAwait = false;
  18135. for (const module of orderedModules) {
  18136. let renderedLength = 0;
  18137. let source;
  18138. if (module.isIncluded() || includedNamespaces.has(module)) {
  18139. const rendered = module.render(renderOptions);
  18140. if (!renderOptions.accessedDocumentCurrentScript &&
  18141. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  18142. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  18143. }
  18144. renderOptions.accessedDocumentCurrentScript = false;
  18145. ({ source } = rendered);
  18146. usesTopLevelAwait ||= rendered.usesTopLevelAwait;
  18147. renderedLength = source.length();
  18148. if (renderedLength) {
  18149. if (compact && source.lastLine().includes('//'))
  18150. source.append('\n');
  18151. renderedModuleSources.set(module, source);
  18152. magicString.addSource(source);
  18153. usedModules.push(module);
  18154. }
  18155. const namespace = module.namespace;
  18156. if (includedNamespaces.has(module)) {
  18157. const rendered = namespace.renderBlock(renderOptions);
  18158. if (namespace.renderFirst())
  18159. hoistedSource += n + rendered;
  18160. else
  18161. magicString.addSource(new MagicString(rendered));
  18162. }
  18163. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  18164. if (accessedGlobalVariables) {
  18165. for (const name of accessedGlobalVariables) {
  18166. accessedGlobals.add(name);
  18167. }
  18168. }
  18169. }
  18170. const { renderedExports, removedExports } = module.getRenderedExports();
  18171. renderedModules[module.id] = {
  18172. get code() {
  18173. return source?.toString() ?? null;
  18174. },
  18175. originalLength: module.originalCode.length,
  18176. removedExports,
  18177. renderedExports,
  18178. renderedLength
  18179. };
  18180. }
  18181. if (hoistedSource)
  18182. magicString.prepend(hoistedSource + n + n);
  18183. if (this.needsExportsShim) {
  18184. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  18185. }
  18186. const renderedSource = compact ? magicString : magicString.trim();
  18187. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  18188. onLog(LOGLEVEL_WARN, logEmptyChunk(this.getChunkName()));
  18189. }
  18190. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  18191. }
  18192. setDynamicImportResolutions(fileName) {
  18193. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  18194. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  18195. if (resolvedDynamicImport.chunk) {
  18196. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  18197. if (chunk === this) {
  18198. node.setInternalResolution(resolution.namespace);
  18199. }
  18200. else {
  18201. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null, this, facadeChunk || chunk);
  18202. }
  18203. }
  18204. else {
  18205. const { node, resolution } = resolvedDynamicImport;
  18206. const [resolutionString, attributes] = this.getDynamicImportStringAndAttributes(resolution, fileName, node);
  18207. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, attributes, this, null);
  18208. }
  18209. }
  18210. }
  18211. setIdentifierRenderResolutions() {
  18212. const { format, generatedCode: { symbols }, interop, preserveModules, externalLiveBindings } = this.outputOptions;
  18213. const syntheticExports = new Set();
  18214. for (const exportName of this.getExportNames()) {
  18215. const exportVariable = this.exportsByName.get(exportName);
  18216. if (format !== 'es' &&
  18217. format !== 'system' &&
  18218. exportVariable.isReassigned &&
  18219. !exportVariable.isId) {
  18220. exportVariable.setRenderNames('exports', exportName);
  18221. }
  18222. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  18223. syntheticExports.add(exportVariable);
  18224. }
  18225. else {
  18226. exportVariable.setRenderNames(null, null);
  18227. }
  18228. }
  18229. for (const module of this.orderedModules) {
  18230. if (module.needsExportShim) {
  18231. this.needsExportsShim = true;
  18232. break;
  18233. }
  18234. }
  18235. const usedNames = new Set(['Object', 'Promise']);
  18236. if (this.needsExportsShim) {
  18237. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  18238. }
  18239. if (symbols) {
  18240. usedNames.add('Symbol');
  18241. }
  18242. switch (format) {
  18243. case 'system': {
  18244. usedNames.add('module').add('exports');
  18245. break;
  18246. }
  18247. case 'es': {
  18248. break;
  18249. }
  18250. case 'cjs': {
  18251. usedNames.add('module').add('require').add('__filename').add('__dirname');
  18252. }
  18253. // fallthrough
  18254. default: {
  18255. usedNames.add('exports');
  18256. for (const helper of HELPER_NAMES) {
  18257. usedNames.add(helper);
  18258. }
  18259. }
  18260. }
  18261. 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);
  18262. }
  18263. setImportMetaResolutions(fileName) {
  18264. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  18265. for (const module of orderedModules) {
  18266. for (const importMeta of module.importMetas) {
  18267. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  18268. }
  18269. if (includedNamespaces.has(module)) {
  18270. module.namespace.prepare(accessedGlobalsByScope);
  18271. }
  18272. }
  18273. }
  18274. setUpChunkImportsAndExportsForModule(module) {
  18275. const moduleImports = new Set(module.includedImports);
  18276. // when we are not preserving modules, we need to make all namespace variables available for
  18277. // rendering the namespace object
  18278. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  18279. const memberVariables = module.namespace.getMemberVariables();
  18280. for (const variable of Object.values(memberVariables)) {
  18281. if (variable.included) {
  18282. moduleImports.add(variable);
  18283. }
  18284. }
  18285. }
  18286. for (let variable of moduleImports) {
  18287. if (variable instanceof ExportDefaultVariable) {
  18288. variable = variable.getOriginalVariable();
  18289. }
  18290. if (variable instanceof SyntheticNamedExportVariable) {
  18291. variable = variable.getBaseVariable();
  18292. }
  18293. const chunk = this.chunkByModule.get(variable.module);
  18294. if (chunk !== this) {
  18295. this.imports.add(variable);
  18296. if (variable.module instanceof Module) {
  18297. this.checkCircularDependencyImport(variable, module);
  18298. // When preserving modules, we do not create namespace objects but directly
  18299. // use the actual namespaces, which would be broken by this logic.
  18300. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  18301. chunk.exports.add(variable);
  18302. }
  18303. }
  18304. }
  18305. }
  18306. if (this.includedNamespaces.has(module) ||
  18307. (module.info.isEntry && module.preserveSignature !== false) ||
  18308. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  18309. this.ensureReexportsAreAvailableForModule(module);
  18310. }
  18311. for (const { node, resolution } of module.dynamicImports) {
  18312. if (node.included &&
  18313. resolution instanceof Module &&
  18314. this.chunkByModule.get(resolution) === this &&
  18315. !this.includedNamespaces.has(resolution)) {
  18316. this.includedNamespaces.add(resolution);
  18317. this.ensureReexportsAreAvailableForModule(resolution);
  18318. }
  18319. }
  18320. }
  18321. }
  18322. function getChunkNameFromModule(module) {
  18323. return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id);
  18324. }
  18325. function getPredefinedChunkNameFromModule(module) {
  18326. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  18327. }
  18328. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  18329. const importedBindingsPerDependency = {};
  18330. for (const [dependency, declaration] of renderedDependencies) {
  18331. const specifiers = new Set();
  18332. if (declaration.imports) {
  18333. for (const { imported } of declaration.imports) {
  18334. specifiers.add(imported);
  18335. }
  18336. }
  18337. if (declaration.reexports) {
  18338. for (const { imported } of declaration.reexports) {
  18339. specifiers.add(imported);
  18340. }
  18341. }
  18342. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  18343. }
  18344. return importedBindingsPerDependency;
  18345. }
  18346. const QUERY_HASH_REGEX = /[#?]/;
  18347. const resolveFileName = (dependency) => dependency.getFileName();
  18348. /**
  18349. * Concatenate a number of iterables to a new iterable without fully evaluating
  18350. * their iterators. Useful when e.g. working with large sets or lists and when
  18351. * there is a chance that the iterators will not be fully exhausted.
  18352. */
  18353. function* concatLazy(iterables) {
  18354. for (const iterable of iterables) {
  18355. yield* iterable;
  18356. }
  18357. }
  18358. /**
  18359. * At its core, the algorithm first starts from each static or dynamic entry
  18360. * point and then assigns that entry point to all modules than can be reached
  18361. * via static imports. We call this the *dependent entry points* of that
  18362. * module.
  18363. *
  18364. * Then we group all modules with the same dependent entry points into chunks
  18365. * as those modules will always be loaded together.
  18366. *
  18367. * One non-trivial optimization we can apply is that dynamic entries are
  18368. * different from static entries in so far as when a dynamic import occurs,
  18369. * some modules are already in memory. If some of these modules are also
  18370. * dependencies of the dynamic entry, then it does not make sense to create a
  18371. * separate chunk for them. Instead, the dynamic import target can load them
  18372. * from the importing chunk.
  18373. *
  18374. * With regard to chunking, if B is implicitly loaded after A, then this can be
  18375. * handled the same way as if there was a dynamic import A => B.
  18376. *
  18377. * Example:
  18378. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  18379. * Then the initial algorithm would assign A into the A chunk, C into the C
  18380. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  18381. * points A and C.
  18382. * However we know that C can only be loaded from A, so A and its dependency B
  18383. * must already be in memory when C is loaded. So it is enough to create only
  18384. * two chunks A containing [AB] and C containing [C].
  18385. *
  18386. * So we do not assign the dynamic entry C as dependent entry point to modules
  18387. * that are already loaded.
  18388. *
  18389. * In a more complex example, let us assume that we have entry points X and Y.
  18390. * Further, let us assume
  18391. * X -> A, X -> B, X -> C,
  18392. * Y -> A, Y -> B,
  18393. * A => D,
  18394. * D -> B, D -> C
  18395. * So without dynamic import optimization, the dependent entry points are
  18396. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, so we would for now create six
  18397. * chunks.
  18398. *
  18399. * Now D is loaded only after A is loaded. But A is loaded if either X is
  18400. * loaded or Y is loaded. So the modules that are already in memory when D is
  18401. * loaded are the intersection of all modules that X depends on with all
  18402. * modules that Y depends on, which in this case are the modules A and B.
  18403. * We could also say they are all modules that have both X and Y as dependent
  18404. * entry points.
  18405. *
  18406. * So we can remove D as dependent entry point from A and B, which means they
  18407. * both now have only XY as dependent entry points and can be merged into the
  18408. * same chunk.
  18409. *
  18410. * Now let us extend this to the most general case where we have several
  18411. * dynamic importers for one dynamic entry point.
  18412. *
  18413. * In the most general form, it works like this:
  18414. * For each dynamic entry point, we have a number of dynamic importers, which
  18415. * are the modules importing it. Using the previous ideas, we can determine
  18416. * the modules already in memory for each dynamic importer by looking for all
  18417. * modules that have all the dependent entry points of the dynamic importer as
  18418. * dependent entry points.
  18419. * So the modules that are guaranteed to be in memory when the dynamic entry
  18420. * point is loaded are the intersection of the modules already in memory for
  18421. * each dynamic importer.
  18422. *
  18423. * Assuming that A => D and B => D and A has dependent entry points XY and B
  18424. * has dependent entry points YZ, then the modules guaranteed to be in memory
  18425. * are all modules that have at least XYZ as dependent entry points.
  18426. * We call XYZ the *dynamically dependent entry points* of D.
  18427. *
  18428. * Now there is one last case to consider: If one of the dynamically dependent
  18429. * entries is itself a dynamic entry, then any module is in memory that either
  18430. * is a dependency of that dynamic entry or again has the dynamic dependent
  18431. * entries of that dynamic entry as dependent entry points.
  18432. *
  18433. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  18434. * complexity with regard to dynamic entries that blew up for very large
  18435. * projects.
  18436. *
  18437. * If we have an efficient way to do Set operations, an alternative approach
  18438. * would be to instead collect already loaded modules per dynamic entry. And as
  18439. * all chunks from the initial grouping would behave the same, we can instead
  18440. * collect already loaded chunks for a performance improvement.
  18441. *
  18442. * To do that efficiently, need
  18443. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  18444. * imports that can be triggered by a dynamic entry
  18445. * - a Map of static dependencies per entry
  18446. * - a Map of already loaded chunks per entry that we initially populate with
  18447. * empty Sets for static entries and Sets containing all entries for dynamic
  18448. * entries
  18449. *
  18450. * For efficient operations, we assign each entry a numerical index and
  18451. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  18452. * bit index. Then the last two maps can be represented as arrays of BigInt
  18453. * values.
  18454. *
  18455. * Then we iterate through each dynamic entry. We set the already loaded modules
  18456. * to the intersection of the previously already loaded modules with the union
  18457. * of the already loaded modules of that chunk with its static dependencies.
  18458. *
  18459. * If the already loaded modules changed, then we use the Map of dynamic imports
  18460. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  18461. * them back into the iteration. As an additional optimization, we note for
  18462. * each dynamic entry which dynamic dependent entries have changed and only
  18463. * intersect those entries again on subsequent interations.
  18464. *
  18465. * Then we remove the dynamic entries from the list of dependent entries for
  18466. * those chunks that are already loaded for that dynamic entry and create
  18467. * another round of chunks.
  18468. */
  18469. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log, isManualChunksFunctionForm, onlyExplicitManualChunks) {
  18470. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry, isManualChunksFunctionForm, onlyExplicitManualChunks);
  18471. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry } = analyzeModuleGraph(entries);
  18472. // Each chunk is identified by its position in this array
  18473. const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  18474. const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(allEntries, chunkAtoms);
  18475. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  18476. // If we no longer want this, we should make a copy here.
  18477. const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  18478. const awaitedAlreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, allEntries);
  18479. // This mutates the dependentEntries in chunkAtoms
  18480. removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry);
  18481. const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
  18482. chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
  18483. alias: null,
  18484. modules
  18485. })));
  18486. return chunkDefinitions;
  18487. }
  18488. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry, isManualChunksFunctionForm, onlyExplicitManualChunks) {
  18489. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  18490. const manualChunkModulesByAlias = Object.create(null);
  18491. for (const [entry, alias] of manualChunkAliasByEntry) {
  18492. if (isManualChunksFunctionForm && onlyExplicitManualChunks) {
  18493. (manualChunkModulesByAlias[alias] ||= []).push(entry);
  18494. }
  18495. else {
  18496. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] ||= []), modulesInManualChunks);
  18497. }
  18498. }
  18499. const manualChunks = Object.entries(manualChunkModulesByAlias);
  18500. const chunkDefinitions = new Array(manualChunks.length);
  18501. let index = 0;
  18502. for (const [alias, modules] of manualChunks) {
  18503. chunkDefinitions[index++] = { alias, modules };
  18504. }
  18505. return { chunkDefinitions, modulesInManualChunks };
  18506. }
  18507. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  18508. const modulesToHandle = new Set([entry]);
  18509. for (const module of modulesToHandle) {
  18510. modulesInManualChunks.add(module);
  18511. manualChunkModules.push(module);
  18512. for (const dependency of module.dependencies) {
  18513. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  18514. modulesToHandle.add(dependency);
  18515. }
  18516. }
  18517. }
  18518. }
  18519. function analyzeModuleGraph(entries) {
  18520. const dynamicEntryModules = new Set();
  18521. const awaitedDynamicEntryModules = new Set();
  18522. const dependentEntriesByModule = new Map();
  18523. const allEntriesSet = new Set(entries);
  18524. const dynamicImportModulesByEntry = new Array(allEntriesSet.size);
  18525. const awaitedDynamicImportModulesByEntry = new Array(allEntriesSet.size);
  18526. let entryIndex = 0;
  18527. for (const currentEntry of allEntriesSet) {
  18528. const dynamicImportsForCurrentEntry = new Set();
  18529. const awaitedDynamicImportsForCurrentEntry = new Set();
  18530. dynamicImportModulesByEntry[entryIndex] = dynamicImportsForCurrentEntry;
  18531. awaitedDynamicImportModulesByEntry[entryIndex] = awaitedDynamicImportsForCurrentEntry;
  18532. const staticDependencies = new Set([currentEntry]);
  18533. for (const module of staticDependencies) {
  18534. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  18535. for (const dependency of module.getDependenciesToBeIncluded()) {
  18536. if (!(dependency instanceof ExternalModule)) {
  18537. staticDependencies.add(dependency);
  18538. }
  18539. }
  18540. for (const { resolution } of module.dynamicImports) {
  18541. if (resolution instanceof Module &&
  18542. resolution.includedDynamicImporters.length > 0 &&
  18543. !allEntriesSet.has(resolution)) {
  18544. dynamicEntryModules.add(resolution);
  18545. allEntriesSet.add(resolution);
  18546. dynamicImportsForCurrentEntry.add(resolution);
  18547. for (const includedTopLevelAwaitingDynamicImporter of resolution.includedTopLevelAwaitingDynamicImporters) {
  18548. if (staticDependencies.has(includedTopLevelAwaitingDynamicImporter)) {
  18549. awaitedDynamicEntryModules.add(resolution);
  18550. awaitedDynamicImportsForCurrentEntry.add(resolution);
  18551. break;
  18552. }
  18553. }
  18554. }
  18555. }
  18556. for (const dependency of module.implicitlyLoadedBefore) {
  18557. if (!allEntriesSet.has(dependency)) {
  18558. dynamicEntryModules.add(dependency);
  18559. allEntriesSet.add(dependency);
  18560. }
  18561. }
  18562. }
  18563. entryIndex++;
  18564. }
  18565. const allEntries = [...allEntriesSet];
  18566. const { awaitedDynamicEntries, awaitedDynamicImportsByEntry, dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry);
  18567. return {
  18568. allEntries,
  18569. awaitedDynamicImportsByEntry,
  18570. dependentEntriesByModule,
  18571. dynamicallyDependentEntriesByAwaitedDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, awaitedDynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedTopLevelAwaitingDynamicImporters),
  18572. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedDynamicImporters),
  18573. dynamicImportsByEntry
  18574. };
  18575. }
  18576. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry) {
  18577. const entryIndexByModule = new Map();
  18578. const dynamicEntries = new Set();
  18579. const awaitedDynamicEntries = new Set();
  18580. for (const [entryIndex, entry] of allEntries.entries()) {
  18581. entryIndexByModule.set(entry, entryIndex);
  18582. if (dynamicEntryModules.has(entry)) {
  18583. dynamicEntries.add(entryIndex);
  18584. }
  18585. if (awaitedDynamicEntryModules.has(entry)) {
  18586. awaitedDynamicEntries.add(entryIndex);
  18587. }
  18588. }
  18589. const dynamicImportsByEntry = getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule);
  18590. const awaitedDynamicImportsByEntry = getDynamicImportsByEntry(awaitedDynamicImportModulesByEntry, entryIndexByModule);
  18591. return {
  18592. awaitedDynamicEntries,
  18593. awaitedDynamicImportsByEntry,
  18594. dynamicEntries,
  18595. dynamicImportsByEntry
  18596. };
  18597. }
  18598. function getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule) {
  18599. const dynamicImportsByEntry = new Array(dynamicImportModulesByEntry.length);
  18600. let index = 0;
  18601. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  18602. const dynamicImports = new Set();
  18603. for (const dynamicEntry of dynamicImportModules) {
  18604. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  18605. }
  18606. dynamicImportsByEntry[index++] = dynamicImports;
  18607. }
  18608. return dynamicImportsByEntry;
  18609. }
  18610. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, getDynamicImporters) {
  18611. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  18612. for (const dynamicEntryIndex of dynamicEntries) {
  18613. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  18614. const dynamicEntry = allEntries[dynamicEntryIndex];
  18615. for (const importer of concatLazy([
  18616. getDynamicImporters(dynamicEntry),
  18617. dynamicEntry.implicitlyLoadedAfter
  18618. ])) {
  18619. for (const entry of dependentEntriesByModule.get(importer)) {
  18620. dynamicallyDependentEntries.add(entry);
  18621. }
  18622. }
  18623. }
  18624. return dynamicallyDependentEntriesByDynamicEntry;
  18625. }
  18626. function getChunksWithSameDependentEntries(modulesWithDependentEntries) {
  18627. const chunkModules = Object.create(null);
  18628. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  18629. let chunkSignature = 0n;
  18630. for (const entryIndex of dependentEntries) {
  18631. chunkSignature |= 1n << BigInt(entryIndex);
  18632. }
  18633. (chunkModules[String(chunkSignature)] ||= {
  18634. dependentEntries: new Set(dependentEntries),
  18635. modules: []
  18636. }).modules.push(...modules);
  18637. }
  18638. return Object.values(chunkModules);
  18639. }
  18640. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  18641. for (const [module, dependentEntries] of dependentEntriesByModule) {
  18642. if (!modulesInManualChunks.has(module)) {
  18643. yield { dependentEntries, modules: [module] };
  18644. }
  18645. }
  18646. }
  18647. function getStaticDependencyAtomsByEntry(allEntries, chunkAtoms) {
  18648. // The indices correspond to the indices in allEntries. The atoms correspond
  18649. // to bits in the bigint values where chunk 0 is the lowest bit.
  18650. const staticDependencyAtomsByEntry = allEntries.map(() => 0n);
  18651. // This toggles the bits for each atom that is a dependency of an entry
  18652. let atomMask = 1n;
  18653. for (const { dependentEntries } of chunkAtoms) {
  18654. for (const entryIndex of dependentEntries) {
  18655. staticDependencyAtomsByEntry[entryIndex] |= atomMask;
  18656. }
  18657. atomMask <<= 1n;
  18658. }
  18659. return staticDependencyAtomsByEntry;
  18660. }
  18661. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  18662. function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  18663. // Dynamic entries have all atoms as already loaded initially because we then
  18664. // intersect with the static dependency atoms of all dynamic importers.
  18665. // Static entries cannot have already loaded atoms.
  18666. const alreadyLoadedAtomsByEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  18667. for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByDynamicEntry) {
  18668. // We delete here so that they can be added again if necessary to be handled
  18669. // again by the loop
  18670. dynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  18671. const knownLoadedAtoms = alreadyLoadedAtomsByEntry[dynamicEntryIndex];
  18672. let updatedLoadedAtoms = knownLoadedAtoms;
  18673. for (const entryIndex of dynamicallyDependentEntries) {
  18674. updatedLoadedAtoms &=
  18675. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  18676. }
  18677. // If the knownLoadedAtoms changed, all dependent dynamic entries need to be
  18678. // updated again
  18679. if (updatedLoadedAtoms !== knownLoadedAtoms) {
  18680. alreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
  18681. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  18682. // If this adds an entry that was deleted before, it will be handled
  18683. // again. This is the reason why we delete every entry from this map
  18684. // that we processed.
  18685. getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  18686. }
  18687. }
  18688. }
  18689. return alreadyLoadedAtomsByEntry;
  18690. }
  18691. /**
  18692. * This removes all unnecessary dynamic entries from the dependentEntries in its
  18693. * first argument if a chunk is already loaded without that entry.
  18694. */
  18695. function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry) {
  18696. // Remove entries from dependent entries if a chunk is already loaded without
  18697. // that entry. Do not remove already loaded atoms where some dynamic imports
  18698. // are awaited to avoid cycles in the output.
  18699. let chunkMask = 1n;
  18700. for (const { dependentEntries } of chunkAtoms) {
  18701. for (const entryIndex of dependentEntries) {
  18702. if ((alreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === chunkMask &&
  18703. (awaitedAlreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === 0n) {
  18704. dependentEntries.delete(entryIndex);
  18705. }
  18706. }
  18707. chunkMask <<= 1n;
  18708. }
  18709. }
  18710. function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
  18711. const chunksBySignature = Object.create(null);
  18712. const chunkByModule = new Map();
  18713. const sizeByAtom = new Array(chunkAtoms.length);
  18714. let sideEffectAtoms = 0n;
  18715. let atomMask = 1n;
  18716. let index = 0;
  18717. for (const { dependentEntries, modules } of chunkAtoms) {
  18718. let chunkSignature = 0n;
  18719. let correlatedAtoms = -1n;
  18720. for (const entryIndex of dependentEntries) {
  18721. chunkSignature |= 1n << BigInt(entryIndex);
  18722. // Correlated atoms are the atoms that are guaranteed to be loaded as
  18723. // well when a given atom is loaded. It is the intersection of the already
  18724. // loaded modules of each chunk merged with its static dependencies.
  18725. correlatedAtoms &=
  18726. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  18727. }
  18728. const chunk = (chunksBySignature[String(chunkSignature)] ||= {
  18729. containedAtoms: 0n,
  18730. correlatedAtoms,
  18731. dependencies: new Set(),
  18732. dependentChunks: new Set(),
  18733. dependentEntries: new Set(dependentEntries),
  18734. modules: [],
  18735. pure: true,
  18736. size: 0
  18737. });
  18738. let atomSize = 0;
  18739. let pure = true;
  18740. for (const module of modules) {
  18741. chunkByModule.set(module, chunk);
  18742. // Unfortunately, we cannot take tree-shaking into account here because
  18743. // rendering did not happen yet, but we can detect empty modules
  18744. if (module.isIncluded()) {
  18745. pure &&= !module.hasEffects();
  18746. // we use a trivial size for the default minChunkSize to improve
  18747. // performance
  18748. atomSize += minChunkSize > 1 ? module.estimateSize() : 1;
  18749. }
  18750. }
  18751. if (!pure) {
  18752. sideEffectAtoms |= atomMask;
  18753. }
  18754. sizeByAtom[index++] = atomSize;
  18755. chunk.containedAtoms |= atomMask;
  18756. chunk.modules.push(...modules);
  18757. chunk.pure &&= pure;
  18758. chunk.size += atomSize;
  18759. atomMask <<= 1n;
  18760. }
  18761. const chunks = Object.values(chunksBySignature);
  18762. sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
  18763. return { chunks, sideEffectAtoms, sizeByAtom };
  18764. }
  18765. function addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, nextAvailableAtomMask) {
  18766. const signatureByExternalModule = new Map();
  18767. let externalSideEffectAtoms = 0n;
  18768. for (const chunk of chunks) {
  18769. const { dependencies, modules } = chunk;
  18770. for (const module of modules) {
  18771. for (const dependency of module.getDependenciesToBeIncluded()) {
  18772. if (dependency instanceof ExternalModule) {
  18773. if (dependency.info.moduleSideEffects) {
  18774. const signature = getOrCreate(signatureByExternalModule, dependency, () => {
  18775. const signature = nextAvailableAtomMask;
  18776. nextAvailableAtomMask <<= 1n;
  18777. externalSideEffectAtoms |= signature;
  18778. return signature;
  18779. });
  18780. chunk.containedAtoms |= signature;
  18781. chunk.correlatedAtoms |= signature;
  18782. }
  18783. }
  18784. else {
  18785. const dependencyChunk = chunkByModule.get(dependency);
  18786. if (dependencyChunk && dependencyChunk !== chunk) {
  18787. dependencies.add(dependencyChunk);
  18788. dependencyChunk.dependentChunks.add(chunk);
  18789. }
  18790. }
  18791. }
  18792. }
  18793. }
  18794. return externalSideEffectAtoms;
  18795. }
  18796. /**
  18797. * This function tries to get rid of small chunks by merging them with other
  18798. * chunks.
  18799. *
  18800. * We can only merge chunks safely if after the merge, loading any entry point
  18801. * in any allowed order will not trigger side effects that should not have been
  18802. * triggered. While side effects are usually things like global function calls,
  18803. * global variable mutations or potentially thrown errors, details do not
  18804. * matter here, and we just discern chunks without side effects (pure chunks)
  18805. * from other chunks.
  18806. *
  18807. * As a first step, we assign each pre-generated chunk with side effects a
  18808. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  18809. *
  18810. * Now to determine the side effects of loading a chunk, one also has to take
  18811. * the side effects of its dependencies into account. So if A depends on B
  18812. * (A -> B) and both have side effects, loading A triggers effects AB.
  18813. *
  18814. * Now from the previous step we know that each chunk is uniquely determine by
  18815. * the entry points that depend on it and cause it to load, which we will call
  18816. * its dependent entry points.
  18817. *
  18818. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  18819. * Starting from that idea, we can determine a set of chunks—and thus a set
  18820. * of side effects—that must have been triggered if a certain chunk has been
  18821. * loaded. Basically, it is the intersection of all chunks loaded by the
  18822. * dependent entry points of a given chunk. We call the corresponding side
  18823. * effects the correlated side effects of that chunk.
  18824. *
  18825. * Example:
  18826. * X -> ABC, Y -> ADE, A-> F, B -> D
  18827. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  18828. * The intersection is ADF. So we know that when A is loaded, D and F must also
  18829. * be in memory even though neither D nor A is a dependency of the other.
  18830. * If all have side effects, we call ADF the correlated side effects of A. The
  18831. * correlated side effects need to remain constant when merging chunks.
  18832. *
  18833. * In contrast, we have the dependency side effects of A, which represents
  18834. * the side effects we trigger if we directly load A. In this example, the
  18835. * dependency side effects are AF.
  18836. * For entry chunks, dependency and correlated side effects are the same.
  18837. *
  18838. * With these concepts, merging chunks is allowed if the correlated side
  18839. * effects of each entry do not change. Thus, we are allowed to merge two
  18840. * chunks if
  18841. *
  18842. * a) the dependency side effects of each chunk are a subset of the correlated
  18843. * side effects of the other chunk, so no additional side effects are
  18844. * triggered for any entry, or
  18845. * b) The dependent entry points of chunk A are a subset of the dependent entry
  18846. * points of chunk B while the dependency side effects of A are a subset of
  18847. * the correlated side effects of B. Because in that scenario, whenever A is
  18848. * loaded, B is loaded as well. But there are cases when B is loaded where A
  18849. * is not loaded. So if we merge the chunks, all dependency side effects of
  18850. * A will be added to the correlated side effects of B, and as the latter is
  18851. * not allowed to change, the former need to be a subset of the latter.
  18852. *
  18853. * Another consideration when merging small chunks into other chunks is to
  18854. * avoid
  18855. * that too much additional code is loaded. This is achieved when the dependent
  18856. * entries of the small chunk are a subset of the dependent entries of the
  18857. * other
  18858. * chunk. Because then when the small chunk is loaded, the other chunk was
  18859. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  18860. * additional size of the small chunk is loaded unnecessarily.
  18861. *
  18862. * So the algorithm performs merges in two passes:
  18863. *
  18864. * 1. First we try to merge small chunks A only into other chunks B if the
  18865. * dependent entries of A are a subset of the dependent entries of B and the
  18866. * dependency side effects of A are a subset of the correlated side effects
  18867. * of B.
  18868. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  18869. * following the rule (a), starting with the smallest chunks to look for
  18870. * possible merge targets.
  18871. */
  18872. function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log) {
  18873. timeStart('optimize chunks', 3);
  18874. const chunkPartition = getPartitionedChunks(chunks, minChunkSize);
  18875. if (!chunkPartition) {
  18876. timeEnd('optimize chunks', 3);
  18877. return chunks; // the actual modules
  18878. }
  18879. if (minChunkSize > 1) {
  18880. log('info', logOptimizeChunkStatus(chunks.length, chunkPartition.small.size, 'Initially'));
  18881. }
  18882. mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
  18883. if (minChunkSize > 1) {
  18884. log('info', logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  18885. }
  18886. timeEnd('optimize chunks', 3);
  18887. return [...chunkPartition.small, ...chunkPartition.big];
  18888. }
  18889. function getPartitionedChunks(chunks, minChunkSize) {
  18890. const smallChunks = [];
  18891. const bigChunks = [];
  18892. for (const chunk of chunks) {
  18893. (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
  18894. }
  18895. if (smallChunks.length === 0) {
  18896. return null;
  18897. }
  18898. smallChunks.sort(compareChunkSize);
  18899. bigChunks.sort(compareChunkSize);
  18900. return {
  18901. big: new Set(bigChunks),
  18902. small: new Set(smallChunks)
  18903. };
  18904. }
  18905. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  18906. return sizeA - sizeB;
  18907. }
  18908. function mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom) {
  18909. const { small } = chunkPartition;
  18910. for (const mergedChunk of small) {
  18911. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, sideEffectAtoms, sizeByAtom,
  18912. // In the default case, we do not accept size increases
  18913. minChunkSize <= 1 ? 1 : Infinity);
  18914. if (bestTargetChunk) {
  18915. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  18916. small.delete(mergedChunk);
  18917. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  18918. bestTargetChunk.modules.push(...modules);
  18919. bestTargetChunk.size += size;
  18920. bestTargetChunk.pure &&= pure;
  18921. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  18922. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  18923. bestTargetChunk.containedAtoms |= containedAtoms;
  18924. for (const entry of mergedChunk.dependentEntries) {
  18925. dependentEntries.add(entry);
  18926. }
  18927. for (const dependency of mergedChunk.dependencies) {
  18928. dependencies.add(dependency);
  18929. dependency.dependentChunks.delete(mergedChunk);
  18930. dependency.dependentChunks.add(bestTargetChunk);
  18931. }
  18932. for (const dependentChunk of mergedChunk.dependentChunks) {
  18933. dependentChunks.add(dependentChunk);
  18934. dependentChunk.dependencies.delete(mergedChunk);
  18935. dependentChunk.dependencies.add(bestTargetChunk);
  18936. }
  18937. dependencies.delete(bestTargetChunk);
  18938. dependentChunks.delete(bestTargetChunk);
  18939. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  18940. }
  18941. }
  18942. }
  18943. function findBestMergeTarget(mergedChunk, { big, small }, sideEffectAtoms, sizeByAtom, smallestAdditionalSize) {
  18944. let bestTargetChunk = null;
  18945. // In the default case, we do not accept size increases
  18946. for (const targetChunk of concatLazy([small, big])) {
  18947. if (mergedChunk === targetChunk)
  18948. continue;
  18949. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  18950. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  18951. bestTargetChunk = targetChunk;
  18952. if (additionalSizeAfterMerge === 0)
  18953. break;
  18954. smallestAdditionalSize = additionalSizeAfterMerge;
  18955. }
  18956. }
  18957. return bestTargetChunk;
  18958. }
  18959. /**
  18960. * Determine the additional unused code size that would be added by merging the
  18961. * two chunks. This is not an exact measurement but rather an upper bound. If
  18962. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  18963. * is returned.
  18964. * Merging will not produce cycles if none of the direct non-merged
  18965. * dependencies of a chunk have the other chunk as a transitive dependency.
  18966. */
  18967. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  18968. // The maximum additional unused code size allowed to be added by the merge,
  18969. // taking dependencies into account, needs to be below this number
  18970. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  18971. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  18972. return firstSize < currentAdditionalSize
  18973. ? firstSize +
  18974. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  18975. : Infinity;
  18976. }
  18977. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  18978. const { correlatedAtoms } = dependencyChunk;
  18979. let dependencyAtoms = dependentChunk.containedAtoms;
  18980. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  18981. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  18982. return Infinity;
  18983. }
  18984. const chunksToCheck = new Set(dependentChunk.dependencies);
  18985. for (const { dependencies, containedAtoms } of chunksToCheck) {
  18986. dependencyAtoms |= containedAtoms;
  18987. const containedSideEffects = containedAtoms & sideEffectAtoms;
  18988. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  18989. return Infinity;
  18990. }
  18991. for (const dependency of dependencies) {
  18992. if (dependency === dependencyChunk) {
  18993. return Infinity;
  18994. }
  18995. chunksToCheck.add(dependency);
  18996. }
  18997. }
  18998. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  18999. }
  19000. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  19001. let size = 0;
  19002. let atomIndex = 0;
  19003. let atomSignature = 1n;
  19004. const { length } = sizeByAtom;
  19005. for (; atomIndex < length; atomIndex++) {
  19006. if ((atoms & atomSignature) === atomSignature) {
  19007. size += sizeByAtom[atomIndex];
  19008. }
  19009. atomSignature <<= 1n;
  19010. if (size >= currentAdditionalSize) {
  19011. return Infinity;
  19012. }
  19013. }
  19014. return size;
  19015. }
  19016. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  19017. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  19018. }
  19019. // ported from https://github.com/substack/node-commondir
  19020. function commondir(files) {
  19021. if (files.length === 0)
  19022. return '/';
  19023. if (files.length === 1)
  19024. return dirname(files[0]);
  19025. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  19026. const pathSegments = file.split(/\/+|\\+/);
  19027. let index;
  19028. for (index = 0; commonSegments[index] === pathSegments[index] &&
  19029. index < Math.min(commonSegments.length, pathSegments.length); index++)
  19030. ;
  19031. return commonSegments.slice(0, index);
  19032. }, files[0].split(/\/+|\\+/));
  19033. // Windows correctly handles paths with forward-slashes
  19034. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  19035. }
  19036. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  19037. function sortByExecutionOrder(units) {
  19038. units.sort(compareExecIndex);
  19039. }
  19040. // This process is currently faulty in so far as it only takes the first entry
  19041. // module into account and assumes that dynamic imports are imported in a
  19042. // certain order.
  19043. // A better algorithm would follow every possible execution path and mark which
  19044. // modules are executed before or after which other modules. THen the chunking
  19045. // would need to take care that in each chunk, all modules are always executed
  19046. // in the same sequence.
  19047. function analyseModuleExecution(entryModules) {
  19048. let nextExecIndex = 0;
  19049. const cyclePaths = [];
  19050. const analysedModules = new Set();
  19051. const dynamicImports = new Set();
  19052. const parents = new Map();
  19053. const orderedModules = [];
  19054. const handleSyncLoadedModule = (module, parent) => {
  19055. if (parents.has(module)) {
  19056. if (!analysedModules.has(module)) {
  19057. cyclePaths.push(getCyclePath(module, parent, parents));
  19058. }
  19059. return;
  19060. }
  19061. parents.set(module, parent);
  19062. analyseModule(module);
  19063. };
  19064. const analyseModule = (module) => {
  19065. if (module instanceof Module) {
  19066. for (const dependency of module.dependencies) {
  19067. handleSyncLoadedModule(dependency, module);
  19068. }
  19069. for (const dependency of module.implicitlyLoadedBefore) {
  19070. dynamicImports.add(dependency);
  19071. }
  19072. for (const { resolution, node } of module.dynamicImports) {
  19073. if (resolution instanceof Module) {
  19074. if (node.scope.context.usesTopLevelAwait) {
  19075. handleSyncLoadedModule(resolution, module);
  19076. }
  19077. else {
  19078. dynamicImports.add(resolution);
  19079. }
  19080. }
  19081. }
  19082. orderedModules.push(module);
  19083. }
  19084. module.execIndex = nextExecIndex++;
  19085. analysedModules.add(module);
  19086. };
  19087. for (const currentEntry of entryModules) {
  19088. if (!parents.has(currentEntry)) {
  19089. parents.set(currentEntry, null);
  19090. analyseModule(currentEntry);
  19091. }
  19092. }
  19093. for (const currentEntry of dynamicImports) {
  19094. if (!parents.has(currentEntry)) {
  19095. parents.set(currentEntry, null);
  19096. analyseModule(currentEntry);
  19097. }
  19098. }
  19099. return { cyclePaths, orderedModules };
  19100. }
  19101. function getCyclePath(module, parent, parents) {
  19102. const cycleSymbol = Symbol(module.id);
  19103. const path = [module.id];
  19104. let nextModule = parent;
  19105. module.cycles.add(cycleSymbol);
  19106. while (nextModule !== module) {
  19107. nextModule.cycles.add(cycleSymbol);
  19108. path.push(nextModule.id);
  19109. nextModule = parents.get(nextModule);
  19110. }
  19111. path.push(path[0]);
  19112. path.reverse();
  19113. return path;
  19114. }
  19115. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  19116. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  19117. const cnst = constBindings ? 'const' : 'var';
  19118. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  19119. const getFunctionIntro = arrowFunctions
  19120. ? (parameters, { isAsync, name }) => {
  19121. const singleParameter = parameters.length === 1;
  19122. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  19123. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  19124. }
  19125. : getNonArrowFunctionIntro;
  19126. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  19127. `${getFunctionIntro(parameters, {
  19128. isAsync: false,
  19129. name
  19130. })}${arrowFunctions
  19131. ? lineBreakIndent
  19132. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  19133. : ''
  19134. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  19135. arrowFunctions
  19136. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  19137. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  19138. ];
  19139. const isValidPropertyName = reservedNamesAsProps
  19140. ? (name) => VALID_IDENTIFIER_REGEXP.test(name)
  19141. : (name) => !RESERVED_NAMES.has(name) && VALID_IDENTIFIER_REGEXP.test(name);
  19142. return {
  19143. _,
  19144. cnst,
  19145. getDirectReturnFunction,
  19146. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  19147. const [left, right] = getDirectReturnFunction(parameters, {
  19148. functionReturn: true,
  19149. lineBreakIndent: null,
  19150. name: null
  19151. });
  19152. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  19153. },
  19154. getFunctionIntro,
  19155. getNonArrowFunctionIntro,
  19156. getObject(fields, { lineBreakIndent }) {
  19157. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  19158. return `{${fields
  19159. .map(([key, value]) => {
  19160. if (key === null)
  19161. return `${prefix}${value}`;
  19162. const keyInObject = stringifyObjectKeyIfNeeded(key);
  19163. return key === value && objectShorthand && key === keyInObject
  19164. ? prefix + key
  19165. : `${prefix}${keyInObject}:${_}${value}`;
  19166. })
  19167. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  19168. },
  19169. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  19170. n,
  19171. s
  19172. };
  19173. }
  19174. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  19175. class Source {
  19176. constructor(filename, content) {
  19177. this.isOriginal = true;
  19178. this.filename = filename;
  19179. this.content = content;
  19180. }
  19181. traceSegment(line, column, name) {
  19182. return { column, line, name, source: this };
  19183. }
  19184. }
  19185. class Link {
  19186. constructor(map, sources) {
  19187. this.sources = sources;
  19188. this.names = map.names;
  19189. this.mappings = map.mappings;
  19190. }
  19191. traceMappings() {
  19192. const sources = [];
  19193. const sourceIndexMap = new Map();
  19194. const sourcesContent = [];
  19195. const names = [];
  19196. const nameIndexMap = new Map();
  19197. const mappings = [];
  19198. for (const line of this.mappings) {
  19199. const tracedLine = [];
  19200. for (const segment of line) {
  19201. if (segment.length === 1)
  19202. continue;
  19203. const source = this.sources[segment[1]];
  19204. if (!source)
  19205. continue;
  19206. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  19207. if (traced) {
  19208. const { column, line, name, source: { content, filename } } = traced;
  19209. let sourceIndex = sourceIndexMap.get(filename);
  19210. if (sourceIndex === undefined) {
  19211. sourceIndex = sources.length;
  19212. sources.push(filename);
  19213. sourceIndexMap.set(filename, sourceIndex);
  19214. sourcesContent[sourceIndex] = content;
  19215. }
  19216. else if (sourcesContent[sourceIndex] == null) {
  19217. sourcesContent[sourceIndex] = content;
  19218. }
  19219. else if (content != null && sourcesContent[sourceIndex] !== content) {
  19220. return error(logConflictingSourcemapSources(filename));
  19221. }
  19222. const tracedSegment = [segment[0], sourceIndex, line, column];
  19223. if (name) {
  19224. let nameIndex = nameIndexMap.get(name);
  19225. if (nameIndex === undefined) {
  19226. nameIndex = names.length;
  19227. names.push(name);
  19228. nameIndexMap.set(name, nameIndex);
  19229. }
  19230. tracedSegment[4] = nameIndex;
  19231. }
  19232. tracedLine.push(tracedSegment);
  19233. }
  19234. }
  19235. mappings.push(tracedLine);
  19236. }
  19237. return { mappings, names, sources, sourcesContent };
  19238. }
  19239. traceSegment(line, column, name) {
  19240. const segments = this.mappings[line];
  19241. if (!segments)
  19242. return null;
  19243. // binary search through segments for the given column
  19244. let searchStart = 0;
  19245. const lastSegmentIndex = segments.length - 1;
  19246. let searchEnd = lastSegmentIndex;
  19247. while (searchStart <= searchEnd) {
  19248. const m = (searchStart + searchEnd) >> 1;
  19249. let segment = segments[m];
  19250. // If a sourcemap does not have sufficient resolution to contain a
  19251. // necessary mapping, e.g. because it only contains line information or
  19252. // 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),
  19253. // we approximate by finding the closest segment whose segment[0] is less than the given column
  19254. if (segment[0] !== column && searchStart === searchEnd) {
  19255. const approximatedSegmentIndex = segments[searchStart][0] > column ? Math.max(0, searchStart - 1) : searchStart;
  19256. segment = segments[approximatedSegmentIndex];
  19257. }
  19258. if (segment[0] === column || searchStart === searchEnd) {
  19259. if (segment.length == 1)
  19260. return null;
  19261. const source = this.sources[segment[1]];
  19262. if (!source)
  19263. return null;
  19264. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  19265. }
  19266. if (segment[0] > column) {
  19267. searchEnd = m - 1;
  19268. }
  19269. else {
  19270. searchStart = m + 1;
  19271. }
  19272. }
  19273. return null;
  19274. }
  19275. }
  19276. function getLinkMap(log) {
  19277. return function linkMap(source, map) {
  19278. if (!map.missing) {
  19279. return new Link(map, [source]);
  19280. }
  19281. log(LOGLEVEL_WARN, logSourcemapBroken(map.plugin));
  19282. return new Link({
  19283. mappings: [],
  19284. names: []
  19285. }, [source]);
  19286. };
  19287. }
  19288. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  19289. let source;
  19290. if (originalSourcemap) {
  19291. const sources = originalSourcemap.sources;
  19292. const sourcesContent = originalSourcemap.sourcesContent || [];
  19293. const directory = dirname(id) || '.';
  19294. const sourceRoot = originalSourcemap.sourceRoot || '.';
  19295. const baseSources = sources.map((source, index) => new Source(resolve$1(directory, sourceRoot, source), sourcesContent[index]));
  19296. source = new Link(originalSourcemap, baseSources);
  19297. }
  19298. else {
  19299. source = new Source(id, originalCode);
  19300. }
  19301. return sourcemapChain.reduce(linkMap, source);
  19302. }
  19303. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  19304. const linkMap = getLinkMap(log);
  19305. const moduleSources = modules
  19306. .filter(module => !module.excludeFromSourcemap)
  19307. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  19308. const link = new Link(map, moduleSources);
  19309. const source = bundleSourcemapChain.reduce(linkMap, link);
  19310. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  19311. if (file) {
  19312. const directory = dirname(file);
  19313. sources = sources.map((source) => relative(directory, source));
  19314. file = basename(file);
  19315. }
  19316. sourcesContent = (excludeContent ? null : sourcesContent);
  19317. for (const module of modules) {
  19318. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  19319. }
  19320. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  19321. }
  19322. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  19323. if (sourcemapChain.length === 0) {
  19324. return originalSourcemap;
  19325. }
  19326. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  19327. const map = source.traceMappings();
  19328. return decodedSourcemap({ version: 3, ...map });
  19329. }
  19330. let textEncoder;
  19331. const getHash64 = input => xxhashBase64Url(ensureBuffer(input));
  19332. const getHash36 = input => xxhashBase36(ensureBuffer(input));
  19333. const getHash16 = input => xxhashBase16(ensureBuffer(input));
  19334. const hasherByType = {
  19335. base36: getHash36,
  19336. base64: getHash64,
  19337. hex: getHash16
  19338. };
  19339. function ensureBuffer(input) {
  19340. if (typeof input === 'string') {
  19341. if (typeof Buffer === 'undefined') {
  19342. textEncoder ??= new TextEncoder();
  19343. return textEncoder.encode(input);
  19344. }
  19345. return Buffer.from(input);
  19346. }
  19347. return input;
  19348. }
  19349. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  19350. // this for an actual sourceMappingURL
  19351. let SOURCEMAPPING_URL = 'sourceMa';
  19352. SOURCEMAPPING_URL += 'ppingURL';
  19353. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  19354. timeStart('render chunks', 2);
  19355. reserveEntryChunksInBundle(chunks);
  19356. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  19357. timeEnd('render chunks', 2);
  19358. timeStart('transform chunks', 2);
  19359. const getHash = hasherByType[outputOptions.hashCharacters];
  19360. const chunkGraph = getChunkGraph(chunks);
  19361. const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
  19362. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
  19363. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  19364. timeEnd('transform chunks', 2);
  19365. }
  19366. function reserveEntryChunksInBundle(chunks) {
  19367. for (const chunk of chunks) {
  19368. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  19369. // reserves name in bundle as side effect if it does not contain a hash
  19370. chunk.getPreliminaryFileName();
  19371. }
  19372. }
  19373. }
  19374. function getChunkGraph(chunks) {
  19375. return Object.fromEntries(chunks.map(chunk => {
  19376. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  19377. return [renderedChunkInfo.fileName, renderedChunkInfo];
  19378. }));
  19379. }
  19380. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  19381. let map = null;
  19382. const sourcemapChain = [];
  19383. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  19384. if (result == null)
  19385. return code;
  19386. if (typeof result === 'string')
  19387. result = {
  19388. code: result,
  19389. map: undefined
  19390. };
  19391. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  19392. if (result.map !== null) {
  19393. const map = decodedSourcemap(result.map);
  19394. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  19395. }
  19396. return result.code;
  19397. });
  19398. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  19399. if (!compact && code[code.length - 1] !== '\n')
  19400. code += '\n';
  19401. if (sourcemap) {
  19402. timeStart('sourcemaps', 3);
  19403. let resultingFile;
  19404. if (file)
  19405. resultingFile = resolve$1(sourcemapFile || file);
  19406. else if (dir)
  19407. resultingFile = resolve$1(dir, fileName);
  19408. else
  19409. resultingFile = resolve$1(fileName);
  19410. const decodedMap = magicString.generateDecodedMap({});
  19411. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  19412. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  19413. let sourcePath = map.sources[sourcesIndex];
  19414. const sourcemapPath = `${resultingFile}.map`;
  19415. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  19416. if (typeof ignoreList !== 'boolean') {
  19417. error(logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  19418. }
  19419. if (ignoreList) {
  19420. if (map.x_google_ignoreList === undefined) {
  19421. map.x_google_ignoreList = [];
  19422. }
  19423. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  19424. map.x_google_ignoreList.push(sourcesIndex);
  19425. }
  19426. }
  19427. if (sourcemapPathTransform) {
  19428. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  19429. if (typeof sourcePath !== 'string') {
  19430. error(logFailedValidation(`sourcemapPathTransform function must return a string.`));
  19431. }
  19432. }
  19433. map.sources[sourcesIndex] = normalize(sourcePath);
  19434. }
  19435. timeEnd('sourcemaps', 3);
  19436. }
  19437. return {
  19438. code,
  19439. map
  19440. };
  19441. }
  19442. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
  19443. const nonHashedChunksWithPlaceholders = [];
  19444. const renderedChunksByPlaceholder = new Map();
  19445. const hashDependenciesByPlaceholder = new Map();
  19446. const initialHashesByPlaceholder = new Map();
  19447. const placeholders = new Set();
  19448. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  19449. if (hashPlaceholder)
  19450. placeholders.add(hashPlaceholder);
  19451. }
  19452. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  19453. const transformedChunk = {
  19454. chunk,
  19455. fileName,
  19456. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  19457. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  19458. };
  19459. const { code, map } = transformedChunk;
  19460. if (hashPlaceholder) {
  19461. // To create a reproducible content-only hash, all placeholders are
  19462. // replaced with the same value before hashing
  19463. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  19464. let contentToHash = transformedCode;
  19465. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  19466. if (pluginHash) {
  19467. augmentation += pluginHash;
  19468. }
  19469. return augmentation;
  19470. });
  19471. if (hashAugmentation) {
  19472. contentToHash += hashAugmentation;
  19473. }
  19474. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  19475. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  19476. containedPlaceholders,
  19477. contentHash: getHash(contentToHash)
  19478. });
  19479. }
  19480. else {
  19481. nonHashedChunksWithPlaceholders.push(transformedChunk);
  19482. }
  19483. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  19484. if (map && sourcemapHashPlaceholder) {
  19485. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  19486. }
  19487. }));
  19488. return {
  19489. hashDependenciesByPlaceholder,
  19490. initialHashesByPlaceholder,
  19491. nonHashedChunksWithPlaceholders,
  19492. placeholders,
  19493. renderedChunksByPlaceholder
  19494. };
  19495. }
  19496. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
  19497. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  19498. for (const placeholder of placeholders) {
  19499. const { fileName } = renderedChunksByPlaceholder.get(placeholder);
  19500. let contentToHash = '';
  19501. const hashDependencyPlaceholders = new Set([placeholder]);
  19502. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  19503. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  19504. contentToHash += contentHash;
  19505. for (const containedPlaceholder of containedPlaceholders) {
  19506. // When looping over a map, setting an entry only causes a new iteration if the key is new
  19507. hashDependencyPlaceholders.add(containedPlaceholder);
  19508. }
  19509. }
  19510. let finalFileName;
  19511. let finalHash;
  19512. do {
  19513. // In case of a hash collision, create a hash of the hash
  19514. if (finalHash) {
  19515. contentToHash = finalHash;
  19516. }
  19517. finalHash = getHash(contentToHash).slice(0, placeholder.length);
  19518. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  19519. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  19520. bundle[finalFileName] = FILE_PLACEHOLDER;
  19521. hashesByPlaceholder.set(placeholder, finalHash);
  19522. }
  19523. return hashesByPlaceholder;
  19524. }
  19525. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  19526. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  19527. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  19528. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  19529. let finalSourcemapFileName = null;
  19530. if (map) {
  19531. if (options.sourcemapDebugIds) {
  19532. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  19533. }
  19534. finalSourcemapFileName = sourcemapFileName
  19535. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  19536. : `${finalFileName}.map`;
  19537. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  19538. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  19539. }
  19540. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  19541. }
  19542. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  19543. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  19544. let finalSourcemapFileName = null;
  19545. if (map) {
  19546. if (options.sourcemapDebugIds) {
  19547. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  19548. }
  19549. finalSourcemapFileName = sourcemapFileName
  19550. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  19551. : `${fileName}.map`;
  19552. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  19553. }
  19554. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  19555. }
  19556. }
  19557. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  19558. let url;
  19559. if (sourcemap === 'inline') {
  19560. url = map.toUrl();
  19561. }
  19562. else {
  19563. const sourcemapFileName = basename(fileName);
  19564. url = sourcemapBaseUrl
  19565. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  19566. : sourcemapFileName;
  19567. pluginDriver.emitFile({
  19568. fileName,
  19569. originalFileName: null,
  19570. source: map.toString(),
  19571. type: 'asset'
  19572. });
  19573. }
  19574. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  19575. }
  19576. function calculateDebugIdAndGetComment(code, map) {
  19577. const hash = hasherByType.hex(code);
  19578. const debugId = [
  19579. hash.slice(0, 8),
  19580. hash.slice(8, 12),
  19581. '4' + hash.slice(12, 15),
  19582. ((parseInt(hash.slice(15, 16), 16) & 3) | 8).toString(16) + hash.slice(17, 20),
  19583. hash.slice(20, 32)
  19584. ].join('-');
  19585. map.debugId = debugId;
  19586. return '//# debugId=' + debugId + '\n';
  19587. }
  19588. class Bundle {
  19589. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  19590. this.outputOptions = outputOptions;
  19591. this.unsetOptions = unsetOptions;
  19592. this.inputOptions = inputOptions;
  19593. this.pluginDriver = pluginDriver;
  19594. this.graph = graph;
  19595. this.facadeChunkByModule = new Map();
  19596. this.includedNamespaces = new Set();
  19597. }
  19598. async generate(isWrite) {
  19599. timeStart('GENERATE', 1);
  19600. const outputBundleBase = Object.create(null);
  19601. const outputBundle = getOutputBundle(outputBundleBase);
  19602. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  19603. try {
  19604. timeStart('initialize render', 2);
  19605. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  19606. timeEnd('initialize render', 2);
  19607. timeStart('generate chunks', 2);
  19608. const getHashPlaceholder = getHashPlaceholderGenerator();
  19609. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  19610. if (chunks.length > 1) {
  19611. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  19612. }
  19613. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  19614. for (const chunk of chunks) {
  19615. chunk.generateExports();
  19616. chunk.inlineTransitiveImports();
  19617. }
  19618. timeEnd('generate chunks', 2);
  19619. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  19620. }
  19621. catch (error_) {
  19622. await this.pluginDriver.hookParallel('renderError', [error_]);
  19623. throw error_;
  19624. }
  19625. removeUnreferencedAssets(outputBundle);
  19626. timeStart('generate bundle', 2);
  19627. await this.pluginDriver.hookSeq('generateBundle', [
  19628. this.outputOptions,
  19629. outputBundle,
  19630. isWrite
  19631. ]);
  19632. this.finaliseAssets(outputBundle);
  19633. timeEnd('generate bundle', 2);
  19634. timeEnd('GENERATE', 1);
  19635. return outputBundleBase;
  19636. }
  19637. async addManualChunks(manualChunks) {
  19638. const manualChunkAliasByEntry = new Map();
  19639. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  19640. alias,
  19641. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  19642. })));
  19643. for (const { alias, entries } of chunkEntries) {
  19644. for (const entry of entries) {
  19645. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  19646. }
  19647. }
  19648. return manualChunkAliasByEntry;
  19649. }
  19650. assignManualChunks(getManualChunk) {
  19651. const manualChunkAliasesWithEntry = [];
  19652. const manualChunksApi = {
  19653. getModuleIds: () => this.graph.modulesById.keys(),
  19654. getModuleInfo: this.graph.getModuleInfo
  19655. };
  19656. for (const module of this.graph.modulesById.values()) {
  19657. if (module instanceof Module) {
  19658. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  19659. if (typeof manualChunkAlias === 'string') {
  19660. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  19661. }
  19662. }
  19663. }
  19664. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  19665. const manualChunkAliasByEntry = new Map();
  19666. for (const [alias, module] of manualChunkAliasesWithEntry) {
  19667. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  19668. }
  19669. return manualChunkAliasByEntry;
  19670. }
  19671. finaliseAssets(bundle) {
  19672. if (this.outputOptions.validate) {
  19673. for (const file of Object.values(bundle)) {
  19674. if ('code' in file) {
  19675. try {
  19676. parseAst(file.code, { jsx: this.inputOptions.jsx !== false });
  19677. }
  19678. catch (error_) {
  19679. this.inputOptions.onLog(LOGLEVEL_WARN, logChunkInvalid(file, error_));
  19680. }
  19681. }
  19682. }
  19683. }
  19684. this.pluginDriver.finaliseAssets();
  19685. }
  19686. async generateChunks(bundle, getHashPlaceholder) {
  19687. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules, onlyExplicitManualChunks } = this.outputOptions;
  19688. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  19689. ? await this.addManualChunks(manualChunks)
  19690. : this.assignManualChunks(manualChunks);
  19691. const snippets = getGenerateCodeSnippets(this.outputOptions);
  19692. const includedModules = getIncludedModules(this.graph.modulesById);
  19693. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  19694. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  19695. const executableModule = inlineDynamicImports
  19696. ? [{ alias: null, modules: includedModules }]
  19697. : preserveModules
  19698. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  19699. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog, typeof manualChunks === 'function', onlyExplicitManualChunks);
  19700. const chunks = new Array(executableModule.length);
  19701. const chunkByModule = new Map();
  19702. let index = 0;
  19703. for (const { alias, modules } of executableModule) {
  19704. sortByExecutionOrder(modules);
  19705. 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);
  19706. chunks[index++] = chunk;
  19707. }
  19708. for (const chunk of chunks) {
  19709. chunk.link();
  19710. }
  19711. const facades = [];
  19712. for (const chunk of chunks) {
  19713. facades.push(...chunk.generateFacades());
  19714. }
  19715. return [...chunks, ...facades];
  19716. }
  19717. }
  19718. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  19719. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  19720. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  19721. if (typeof outputOptions.file === 'string')
  19722. 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'));
  19723. if (outputOptions.sourcemapFile)
  19724. return error(logInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  19725. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  19726. 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'));
  19727. }
  19728. function getIncludedModules(modulesById) {
  19729. const includedModules = [];
  19730. for (const module of modulesById.values()) {
  19731. if (module instanceof Module &&
  19732. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  19733. includedModules.push(module);
  19734. }
  19735. }
  19736. return includedModules;
  19737. }
  19738. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  19739. const absoluteEntryModulePaths = [];
  19740. for (const module of includedModules) {
  19741. if ((module.info.isEntry || preserveModules) && isAbsolute$1(module.id)) {
  19742. absoluteEntryModulePaths.push(module.id);
  19743. }
  19744. }
  19745. return absoluteEntryModulePaths;
  19746. }
  19747. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  19748. const externalChunkByModule = new Map();
  19749. for (const module of modulesById.values()) {
  19750. if (module instanceof ExternalModule) {
  19751. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  19752. }
  19753. }
  19754. return externalChunkByModule;
  19755. }
  19756. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  19757. const existingAlias = manualChunkAliasByEntry.get(module);
  19758. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  19759. return error(logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  19760. }
  19761. manualChunkAliasByEntry.set(module, alias);
  19762. }
  19763. function flru (max) {
  19764. var num, curr, prev;
  19765. var limit = max;
  19766. function keep(key, value) {
  19767. if (++num > limit) {
  19768. prev = curr;
  19769. reset(1);
  19770. ++num;
  19771. }
  19772. curr[key] = value;
  19773. }
  19774. function reset(isPartial) {
  19775. num = 0;
  19776. curr = Object.create(null);
  19777. isPartial || (prev=Object.create(null));
  19778. }
  19779. reset();
  19780. return {
  19781. clear: reset,
  19782. has: function (key) {
  19783. return curr[key] !== void 0 || prev[key] !== void 0;
  19784. },
  19785. get: function (key) {
  19786. var val = curr[key];
  19787. if (val !== void 0) return val;
  19788. if ((val=prev[key]) !== void 0) {
  19789. keep(key, val);
  19790. return val;
  19791. }
  19792. },
  19793. set: function (key, value) {
  19794. if (curr[key] !== void 0) {
  19795. curr[key] = value;
  19796. } else {
  19797. keep(key, value);
  19798. }
  19799. }
  19800. };
  19801. }
  19802. class GlobalScope extends Scope {
  19803. constructor() {
  19804. super();
  19805. this.parent = null;
  19806. this.variables.set('undefined', new UndefinedVariable());
  19807. }
  19808. findVariable(name) {
  19809. let variable = this.variables.get(name);
  19810. if (!variable) {
  19811. variable = new GlobalVariable(name);
  19812. this.variables.set(name, variable);
  19813. }
  19814. return variable;
  19815. }
  19816. }
  19817. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  19818. let skipped = null;
  19819. let replaceContext = null;
  19820. if (skip) {
  19821. skipped = new Set();
  19822. for (const skippedCall of skip) {
  19823. if (source === skippedCall.source && importer === skippedCall.importer) {
  19824. skipped.add(skippedCall.plugin);
  19825. }
  19826. }
  19827. replaceContext = (pluginContext, plugin) => ({
  19828. ...pluginContext,
  19829. resolve: (source, importer, { attributes, custom, isEntry, skipSelf } = BLANK) => {
  19830. skipSelf ??= true;
  19831. if (skipSelf &&
  19832. skip.findIndex(skippedCall => {
  19833. return (skippedCall.plugin === plugin &&
  19834. skippedCall.source === source &&
  19835. skippedCall.importer === importer);
  19836. }) !== -1) {
  19837. // This means that the plugin recursively called itself
  19838. // Thus returning Promise.resolve(null) in purpose of fallback to default behavior of `resolveId` plugin hook.
  19839. return Promise.resolve(null);
  19840. }
  19841. return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  19842. }
  19843. });
  19844. }
  19845. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, isEntry }], replaceContext, skipped);
  19846. }
  19847. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, fs) {
  19848. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes);
  19849. if (pluginResult != null) {
  19850. const [resolveIdResult, plugin] = pluginResult;
  19851. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  19852. return {
  19853. ...resolveIdResult,
  19854. resolvedBy: plugin.name
  19855. };
  19856. }
  19857. if (typeof resolveIdResult === 'string') {
  19858. return {
  19859. id: resolveIdResult,
  19860. resolvedBy: plugin.name
  19861. };
  19862. }
  19863. return resolveIdResult;
  19864. }
  19865. // external modules (non-entry modules that start with neither '.' or '/')
  19866. // are skipped at this stage.
  19867. if (importer !== undefined && !isAbsolute$1(source) && source[0] !== '.')
  19868. return null;
  19869. // `resolve` processes paths from right to left, prepending them until an
  19870. // absolute path is created. Absolute importees therefore shortcircuit the
  19871. // resolve call and require no special handing on our part.
  19872. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  19873. return addJsExtensionIfNecessary(importer ? resolve$1(dirname(importer), source) : resolve$1(source), preserveSymlinks, fs);
  19874. }
  19875. async function addJsExtensionIfNecessary(file, preserveSymlinks, fs) {
  19876. return ((await findFile(file, preserveSymlinks, fs)) ??
  19877. (await findFile(file + '.mjs', preserveSymlinks, fs)) ??
  19878. (await findFile(file + '.js', preserveSymlinks, fs)));
  19879. }
  19880. async function findFile(file, preserveSymlinks, fs) {
  19881. try {
  19882. const stats = await fs.lstat(file);
  19883. if (!preserveSymlinks && stats.isSymbolicLink())
  19884. return await findFile(await fs.realpath(file), preserveSymlinks, fs);
  19885. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  19886. // check case
  19887. const name = basename(file);
  19888. const files = await fs.readdir(dirname(file));
  19889. if (files.includes(name))
  19890. return file;
  19891. }
  19892. }
  19893. catch {
  19894. // suppress
  19895. }
  19896. }
  19897. function stripBom(content) {
  19898. if (content.charCodeAt(0) === 0xfe_ff) {
  19899. return stripBom(content.slice(1));
  19900. }
  19901. return content;
  19902. }
  19903. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  19904. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  19905. function createPluginCache(cache) {
  19906. return {
  19907. delete(id) {
  19908. return delete cache[id];
  19909. },
  19910. get(id) {
  19911. const item = cache[id];
  19912. if (!item)
  19913. return;
  19914. item[0] = 0;
  19915. return item[1];
  19916. },
  19917. has(id) {
  19918. const item = cache[id];
  19919. if (!item)
  19920. return false;
  19921. item[0] = 0;
  19922. return true;
  19923. },
  19924. set(id, value) {
  19925. cache[id] = [0, value];
  19926. }
  19927. };
  19928. }
  19929. function getTrackedPluginCache(pluginCache, onUse) {
  19930. return {
  19931. delete(id) {
  19932. onUse();
  19933. return pluginCache.delete(id);
  19934. },
  19935. get(id) {
  19936. onUse();
  19937. return pluginCache.get(id);
  19938. },
  19939. has(id) {
  19940. onUse();
  19941. return pluginCache.has(id);
  19942. },
  19943. set(id, value) {
  19944. onUse();
  19945. return pluginCache.set(id, value);
  19946. }
  19947. };
  19948. }
  19949. const NO_CACHE = {
  19950. delete() {
  19951. return false;
  19952. },
  19953. get() {
  19954. return undefined;
  19955. },
  19956. has() {
  19957. return false;
  19958. },
  19959. set() { }
  19960. };
  19961. function uncacheablePluginError(pluginName) {
  19962. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  19963. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  19964. return error(logAnonymousPluginCache());
  19965. }
  19966. return error(logDuplicatePluginName(pluginName));
  19967. }
  19968. function getCacheForUncacheablePlugin(pluginName) {
  19969. return {
  19970. delete() {
  19971. return uncacheablePluginError(pluginName);
  19972. },
  19973. get() {
  19974. return uncacheablePluginError(pluginName);
  19975. },
  19976. has() {
  19977. return uncacheablePluginError(pluginName);
  19978. },
  19979. set() {
  19980. return uncacheablePluginError(pluginName);
  19981. }
  19982. };
  19983. }
  19984. async function asyncFlatten(array) {
  19985. do {
  19986. array = (await Promise.all(array)).flat(Infinity);
  19987. } while (array.some((v) => v?.then));
  19988. return array;
  19989. }
  19990. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  19991. const { onwarn, onLog } = config;
  19992. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  19993. if (onLog) {
  19994. const minimalPriority = logLevelPriority[logLevel];
  19995. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  19996. if (level === LOGLEVEL_ERROR) {
  19997. return error(normalizeLog(handledLog));
  19998. }
  19999. if (logLevelPriority[level] >= minimalPriority) {
  20000. defaultOnLog(level, normalizeLog(handledLog));
  20001. }
  20002. });
  20003. }
  20004. return defaultOnLog;
  20005. };
  20006. const getDefaultOnLog = (printLog, onwarn) => onwarn
  20007. ? (level, log) => {
  20008. if (level === LOGLEVEL_WARN) {
  20009. onwarn(addLogToString(log), warning => printLog(LOGLEVEL_WARN, normalizeLog(warning)));
  20010. }
  20011. else {
  20012. printLog(level, log);
  20013. }
  20014. }
  20015. : printLog;
  20016. const addLogToString = (log) => {
  20017. Object.defineProperty(log, 'toString', {
  20018. value: () => log.message,
  20019. writable: true
  20020. });
  20021. return log;
  20022. };
  20023. const normalizeLog = (log) => typeof log === 'string'
  20024. ? { message: log }
  20025. : typeof log === 'function'
  20026. ? normalizeLog(log())
  20027. : log;
  20028. const defaultPrintLog = (level, { message }) => {
  20029. switch (level) {
  20030. case LOGLEVEL_WARN: {
  20031. return console.warn(message);
  20032. }
  20033. case LOGLEVEL_DEBUG: {
  20034. return console.debug(message);
  20035. }
  20036. default: {
  20037. return console.info(message);
  20038. }
  20039. }
  20040. };
  20041. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  20042. const validOptionSet = new Set(validOptions);
  20043. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  20044. if (unknownOptions.length > 0) {
  20045. log(LOGLEVEL_WARN, logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  20046. }
  20047. }
  20048. const treeshakePresets = {
  20049. recommended: {
  20050. annotations: true,
  20051. correctVarValueBeforeDeclaration: false,
  20052. manualPureFunctions: EMPTY_ARRAY,
  20053. moduleSideEffects: () => true,
  20054. propertyReadSideEffects: true,
  20055. tryCatchDeoptimization: true,
  20056. unknownGlobalSideEffects: false
  20057. },
  20058. safest: {
  20059. annotations: true,
  20060. correctVarValueBeforeDeclaration: true,
  20061. manualPureFunctions: EMPTY_ARRAY,
  20062. moduleSideEffects: () => true,
  20063. propertyReadSideEffects: true,
  20064. tryCatchDeoptimization: true,
  20065. unknownGlobalSideEffects: true
  20066. },
  20067. smallest: {
  20068. annotations: true,
  20069. correctVarValueBeforeDeclaration: false,
  20070. manualPureFunctions: EMPTY_ARRAY,
  20071. moduleSideEffects: () => false,
  20072. propertyReadSideEffects: false,
  20073. tryCatchDeoptimization: false,
  20074. unknownGlobalSideEffects: false
  20075. }
  20076. };
  20077. const jsxPresets = {
  20078. preserve: {
  20079. factory: null,
  20080. fragment: null,
  20081. importSource: null,
  20082. mode: 'preserve'
  20083. },
  20084. 'preserve-react': {
  20085. factory: 'React.createElement',
  20086. fragment: 'React.Fragment',
  20087. importSource: 'react',
  20088. mode: 'preserve'
  20089. },
  20090. react: {
  20091. factory: 'React.createElement',
  20092. fragment: 'React.Fragment',
  20093. importSource: 'react',
  20094. mode: 'classic'
  20095. },
  20096. 'react-jsx': {
  20097. factory: 'React.createElement',
  20098. importSource: 'react',
  20099. jsxImportSource: 'react/jsx-runtime',
  20100. mode: 'automatic'
  20101. }
  20102. };
  20103. const generatedCodePresets = {
  20104. es2015: {
  20105. arrowFunctions: true,
  20106. constBindings: true,
  20107. objectShorthand: true,
  20108. reservedNamesAsProps: true,
  20109. symbols: true
  20110. },
  20111. es5: {
  20112. arrowFunctions: false,
  20113. constBindings: false,
  20114. objectShorthand: false,
  20115. reservedNamesAsProps: true,
  20116. symbols: false
  20117. }
  20118. };
  20119. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  20120. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  20121. if (typeof value === 'string') {
  20122. const preset = presets[value];
  20123. if (preset) {
  20124. return preset;
  20125. }
  20126. error(logInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  20127. }
  20128. return objectifyOption(value);
  20129. };
  20130. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  20131. const presetName = value?.preset;
  20132. if (presetName) {
  20133. const preset = presets[presetName];
  20134. if (preset) {
  20135. return { ...preset, ...value };
  20136. }
  20137. else {
  20138. error(logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  20139. }
  20140. }
  20141. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  20142. };
  20143. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  20144. async function transform(source, module, pluginDriver, log) {
  20145. const id = module.id;
  20146. const sourcemapChain = [];
  20147. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  20148. const originalCode = source.code;
  20149. let ast = source.ast;
  20150. const transformDependencies = [];
  20151. const emittedFiles = [];
  20152. let customTransformCache = false;
  20153. const useCustomTransformCache = () => (customTransformCache = true);
  20154. let pluginName = '';
  20155. let currentSource = source.code;
  20156. function transformReducer(previousCode, result, plugin) {
  20157. let code;
  20158. let map;
  20159. if (typeof result === 'string') {
  20160. code = result;
  20161. }
  20162. else if (result && typeof result === 'object') {
  20163. module.updateOptions(result);
  20164. if (result.code == null) {
  20165. if (result.map || result.ast) {
  20166. log(LOGLEVEL_WARN, logNoTransformMapOrAstWithoutCode(plugin.name));
  20167. }
  20168. return previousCode;
  20169. }
  20170. ({ code, map, ast } = result);
  20171. }
  20172. else {
  20173. return previousCode;
  20174. }
  20175. // strict null check allows 'null' maps to not be pushed to the chain,
  20176. // while 'undefined' gets the missing map warning
  20177. if (map !== null) {
  20178. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  20179. missing: true,
  20180. plugin: plugin.name
  20181. });
  20182. }
  20183. currentSource = code;
  20184. return code;
  20185. }
  20186. const getLogHandler = (handler) => (log, pos) => {
  20187. log = normalizeLog(log);
  20188. if (pos)
  20189. augmentCodeLocation(log, pos, currentSource, id);
  20190. log.id = id;
  20191. log.hook = 'transform';
  20192. handler(log);
  20193. };
  20194. let code;
  20195. try {
  20196. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  20197. pluginName = plugin.name;
  20198. return {
  20199. ...pluginContext,
  20200. addWatchFile(id) {
  20201. transformDependencies.push(id);
  20202. pluginContext.addWatchFile(id);
  20203. },
  20204. cache: customTransformCache
  20205. ? pluginContext.cache
  20206. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  20207. debug: getLogHandler(pluginContext.debug),
  20208. emitFile(emittedFile) {
  20209. emittedFiles.push(emittedFile);
  20210. return pluginDriver.emitFile(emittedFile);
  20211. },
  20212. error(error_, pos) {
  20213. if (typeof error_ === 'string')
  20214. error_ = { message: error_ };
  20215. if (pos)
  20216. augmentCodeLocation(error_, pos, currentSource, id);
  20217. error_.id = id;
  20218. error_.hook = 'transform';
  20219. return pluginContext.error(error_);
  20220. },
  20221. getCombinedSourcemap() {
  20222. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  20223. if (!combinedMap) {
  20224. const magicString = new MagicString(originalCode);
  20225. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  20226. }
  20227. if (originalSourcemap !== combinedMap) {
  20228. originalSourcemap = combinedMap;
  20229. sourcemapChain.length = 0;
  20230. }
  20231. return new SourceMap({
  20232. ...combinedMap,
  20233. file: null,
  20234. sourcesContent: combinedMap.sourcesContent
  20235. });
  20236. },
  20237. info: getLogHandler(pluginContext.info),
  20238. setAssetSource() {
  20239. return this.error(logInvalidSetAssetSourceCall());
  20240. },
  20241. warn: getLogHandler(pluginContext.warn)
  20242. };
  20243. });
  20244. }
  20245. catch (error_) {
  20246. return error(logPluginError(error_, pluginName, { hook: 'transform', id }));
  20247. }
  20248. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  20249. emittedFiles.length > 0)
  20250. module.transformFiles = emittedFiles;
  20251. return {
  20252. ast,
  20253. code,
  20254. customTransformCache,
  20255. originalCode,
  20256. originalSourcemap,
  20257. sourcemapChain,
  20258. transformDependencies
  20259. };
  20260. }
  20261. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  20262. class ModuleLoader {
  20263. constructor(graph, modulesById, options, pluginDriver) {
  20264. this.graph = graph;
  20265. this.modulesById = modulesById;
  20266. this.options = options;
  20267. this.pluginDriver = pluginDriver;
  20268. this.implicitEntryModules = new Set();
  20269. this.indexedEntryModules = [];
  20270. this.latestLoadModulesPromise = Promise.resolve();
  20271. this.moduleLoadPromises = new Map();
  20272. this.modulesWithLoadedDependencies = new Set();
  20273. this.nextChunkNamePriority = 0;
  20274. this.nextEntryModuleIndex = 0;
  20275. this.resolveId = async (source, importer, customOptions, isEntry, attributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  20276. ? false
  20277. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes, this.options.fs), importer, source), attributes);
  20278. this.hasModuleSideEffects = options.treeshake
  20279. ? options.treeshake.moduleSideEffects
  20280. : () => true;
  20281. }
  20282. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  20283. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  20284. await this.awaitLoadModulesPromise();
  20285. return result;
  20286. }
  20287. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  20288. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  20289. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  20290. const firstChunkNamePriority = this.nextChunkNamePriority;
  20291. this.nextChunkNamePriority += unresolvedEntryModules.length;
  20292. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  20293. for (const [index, entryModule] of entryModules.entries()) {
  20294. entryModule.isUserDefinedEntryPoint =
  20295. entryModule.isUserDefinedEntryPoint || isUserDefined;
  20296. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  20297. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  20298. if (existingIndexedModule) {
  20299. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  20300. }
  20301. else {
  20302. this.indexedEntryModules.push({
  20303. index: firstEntryModuleIndex + index,
  20304. module: entryModule
  20305. });
  20306. }
  20307. }
  20308. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  20309. return entryModules;
  20310. }));
  20311. await this.awaitLoadModulesPromise();
  20312. return {
  20313. entryModules: this.indexedEntryModules.map(({ module }) => module),
  20314. implicitEntryModules: [...this.implicitEntryModules],
  20315. newEntryModules
  20316. };
  20317. }
  20318. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  20319. const unresolvedModule = {
  20320. fileName: fileName || null,
  20321. id,
  20322. importer,
  20323. name: name || null
  20324. };
  20325. const module = implicitlyLoadedAfterOneOf
  20326. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  20327. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  20328. if (preserveSignature != null) {
  20329. module.preserveSignature = preserveSignature;
  20330. }
  20331. return module;
  20332. }
  20333. async preloadModule(resolvedId) {
  20334. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  20335. return module.info;
  20336. }
  20337. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  20338. const chunkNamePriority = this.nextChunkNamePriority++;
  20339. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  20340. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  20341. if (!entryModule.info.isEntry) {
  20342. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  20343. // We need to check again if this is still an entry module as these
  20344. // changes need to be performed atomically to avoid race conditions
  20345. // if the same module is re-emitted as an entry module.
  20346. // The inverse changes happen in "handleExistingModule"
  20347. if (!entryModule.info.isEntry) {
  20348. this.implicitEntryModules.add(entryModule);
  20349. for (const module of implicitlyLoadedAfterModules) {
  20350. entryModule.implicitlyLoadedAfter.add(module);
  20351. }
  20352. for (const dependant of entryModule.implicitlyLoadedAfter) {
  20353. dependant.implicitlyLoadedBefore.add(entryModule);
  20354. }
  20355. }
  20356. }
  20357. return entryModule;
  20358. }));
  20359. }
  20360. async addModuleSource(id, importer, module) {
  20361. let source;
  20362. try {
  20363. source = await this.graph.fileOperationQueue.run(async () => {
  20364. const content = await this.pluginDriver.hookFirst('load', [id]);
  20365. if (content !== null)
  20366. return content;
  20367. this.graph.watchFiles[id] = true;
  20368. return (await this.options.fs.readFile(id, { encoding: 'utf8' }));
  20369. });
  20370. }
  20371. catch (error_) {
  20372. let message = `Could not load ${id}`;
  20373. if (importer)
  20374. message += ` (imported by ${relativeId(importer)})`;
  20375. message += `: ${error_.message}`;
  20376. error_.message = message;
  20377. throw error_;
  20378. }
  20379. const sourceDescription = typeof source === 'string'
  20380. ? { code: source }
  20381. : source != null && typeof source === 'object' && typeof source.code === 'string'
  20382. ? source
  20383. : error(logBadLoader(id));
  20384. sourceDescription.code = stripBom(sourceDescription.code);
  20385. const cachedModule = this.graph.cachedModules.get(id);
  20386. if (cachedModule &&
  20387. !cachedModule.customTransformCache &&
  20388. cachedModule.originalCode === sourceDescription.code &&
  20389. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  20390. {
  20391. ast: cachedModule.ast,
  20392. code: cachedModule.code,
  20393. id: cachedModule.id,
  20394. meta: cachedModule.meta,
  20395. moduleSideEffects: cachedModule.moduleSideEffects,
  20396. resolvedSources: cachedModule.resolvedIds,
  20397. syntheticNamedExports: cachedModule.syntheticNamedExports
  20398. }
  20399. ]))) {
  20400. if (cachedModule.transformFiles) {
  20401. for (const emittedFile of cachedModule.transformFiles)
  20402. this.pluginDriver.emitFile(emittedFile);
  20403. }
  20404. await module.setSource(cachedModule);
  20405. }
  20406. else {
  20407. module.updateOptions(sourceDescription);
  20408. await module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  20409. }
  20410. }
  20411. async awaitLoadModulesPromise() {
  20412. let startingPromise;
  20413. do {
  20414. startingPromise = this.latestLoadModulesPromise;
  20415. await startingPromise;
  20416. } while (startingPromise !== this.latestLoadModulesPromise);
  20417. }
  20418. extendLoadModulesPromise(loadNewModulesPromise) {
  20419. this.latestLoadModulesPromise = Promise.all([
  20420. loadNewModulesPromise,
  20421. this.latestLoadModulesPromise
  20422. ]);
  20423. this.latestLoadModulesPromise.catch(() => {
  20424. /* Avoid unhandled Promise rejections */
  20425. });
  20426. return loadNewModulesPromise;
  20427. }
  20428. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  20429. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  20430. if (resolvedId === null)
  20431. return null;
  20432. if (typeof resolvedId === 'string') {
  20433. dynamicImport.resolution = resolvedId;
  20434. return null;
  20435. }
  20436. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  20437. })));
  20438. for (const dependency of dependencies) {
  20439. if (dependency) {
  20440. module.dynamicDependencies.add(dependency);
  20441. dependency.dynamicImporters.push(module.id);
  20442. }
  20443. }
  20444. }
  20445. // If this is a preload, then this method always waits for the dependencies of
  20446. // the module to be resolved.
  20447. // Otherwise, if the module does not exist, it waits for the module and all
  20448. // its dependencies to be loaded.
  20449. // Otherwise, it returns immediately.
  20450. async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  20451. const existingModule = this.modulesById.get(id);
  20452. if (existingModule instanceof Module) {
  20453. if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
  20454. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
  20455. }
  20456. await this.handleExistingModule(existingModule, isEntry, isPreload);
  20457. return existingModule;
  20458. }
  20459. if (existingModule instanceof ExternalModule) {
  20460. return error(logExternalModulesCannotBeTransformedToModules(existingModule.id));
  20461. }
  20462. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
  20463. this.modulesById.set(id, module);
  20464. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  20465. this.getResolveStaticDependencyPromises(module),
  20466. this.getResolveDynamicImportPromises(module),
  20467. loadAndResolveDependenciesPromise
  20468. ]);
  20469. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  20470. loadAndResolveDependenciesPromise.catch(() => {
  20471. /* avoid unhandled promise rejections */
  20472. });
  20473. this.moduleLoadPromises.set(module, loadPromise);
  20474. const resolveDependencyPromises = await loadPromise;
  20475. if (!isPreload) {
  20476. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  20477. }
  20478. else if (isPreload === RESOLVE_DEPENDENCIES) {
  20479. await loadAndResolveDependenciesPromise;
  20480. }
  20481. return module;
  20482. }
  20483. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  20484. if (this.modulesWithLoadedDependencies.has(module)) {
  20485. return;
  20486. }
  20487. this.modulesWithLoadedDependencies.add(module);
  20488. await Promise.all([
  20489. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  20490. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  20491. ]);
  20492. module.linkImports();
  20493. // To handle errors when resolving dependencies or in moduleParsed
  20494. await loadAndResolveDependenciesPromise;
  20495. }
  20496. fetchResolvedDependency(source, importer, resolvedId) {
  20497. if (resolvedId.external) {
  20498. const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
  20499. let externalModule = this.modulesById.get(id);
  20500. if (!externalModule) {
  20501. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute$1(id), attributes);
  20502. this.modulesById.set(id, externalModule);
  20503. }
  20504. else if (!(externalModule instanceof ExternalModule)) {
  20505. return error(logInternalIdCannotBeExternal(source, importer));
  20506. }
  20507. else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
  20508. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
  20509. }
  20510. return Promise.resolve(externalModule);
  20511. }
  20512. return this.fetchModule(resolvedId, importer, false, false);
  20513. }
  20514. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  20515. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  20516. module.dependencies.add(dependency);
  20517. dependency.importers.push(module.id);
  20518. }
  20519. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  20520. for (const dependency of module.dependencies) {
  20521. if (dependency instanceof Module) {
  20522. dependency.importedFromNotTreeshaken = true;
  20523. }
  20524. }
  20525. }
  20526. }
  20527. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  20528. const { makeAbsoluteExternalsRelative } = this.options;
  20529. if (resolveIdResult) {
  20530. if (typeof resolveIdResult === 'object') {
  20531. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  20532. return {
  20533. ...resolveIdResult,
  20534. external: external &&
  20535. (external === 'relative' ||
  20536. !isAbsolute$1(resolveIdResult.id) ||
  20537. (external === true &&
  20538. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  20539. 'absolute')
  20540. };
  20541. }
  20542. const external = this.options.external(resolveIdResult, importer, true);
  20543. return {
  20544. external: external &&
  20545. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  20546. 'absolute'),
  20547. id: external && makeAbsoluteExternalsRelative
  20548. ? normalizeRelativeExternalId(resolveIdResult, importer)
  20549. : resolveIdResult
  20550. };
  20551. }
  20552. const id = makeAbsoluteExternalsRelative
  20553. ? normalizeRelativeExternalId(source, importer)
  20554. : source;
  20555. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  20556. return null;
  20557. }
  20558. return {
  20559. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  20560. id
  20561. };
  20562. }
  20563. getResolveDynamicImportPromises(module) {
  20564. return module.dynamicImports.map(async (dynamicImport) => {
  20565. const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
  20566. if (!resolvedId || typeof resolvedId === 'string') {
  20567. dynamicImport.node.shouldIncludeDynamicAttributes = true;
  20568. }
  20569. else {
  20570. dynamicImport.node.shouldIncludeDynamicAttributes = !!resolvedId.external;
  20571. dynamicImport.id = resolvedId.id;
  20572. }
  20573. return [dynamicImport, resolvedId];
  20574. });
  20575. }
  20576. getResolveStaticDependencyPromises(module) {
  20577. return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
  20578. source,
  20579. (module.resolvedIds[source] =
  20580. module.resolvedIds[source] ||
  20581. this.handleInvalidResolvedId(await this.resolveId(source, module.id, EMPTY_OBJECT, false, attributes), source, module.id, attributes))
  20582. ]);
  20583. }
  20584. getResolvedIdWithDefaults(resolvedId, attributes) {
  20585. if (!resolvedId) {
  20586. return null;
  20587. }
  20588. const external = resolvedId.external || false;
  20589. return {
  20590. attributes: resolvedId.attributes || attributes,
  20591. external,
  20592. id: resolvedId.id,
  20593. meta: resolvedId.meta || {},
  20594. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  20595. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  20596. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  20597. };
  20598. }
  20599. async handleExistingModule(module, isEntry, isPreload) {
  20600. const loadPromise = this.moduleLoadPromises.get(module);
  20601. if (isPreload) {
  20602. return isPreload === RESOLVE_DEPENDENCIES
  20603. ? waitForDependencyResolution(loadPromise)
  20604. : loadPromise;
  20605. }
  20606. if (isEntry) {
  20607. // This reverts the changes in addEntryWithImplicitDependants and needs to
  20608. // be performed atomically
  20609. module.info.isEntry = true;
  20610. this.implicitEntryModules.delete(module);
  20611. for (const dependant of module.implicitlyLoadedAfter) {
  20612. dependant.implicitlyLoadedBefore.delete(module);
  20613. }
  20614. module.implicitlyLoadedAfter.clear();
  20615. }
  20616. return this.fetchModuleDependencies(module, ...(await loadPromise));
  20617. }
  20618. handleInvalidResolvedId(resolvedId, source, importer, attributes) {
  20619. if (resolvedId === null) {
  20620. if (isRelative(source)) {
  20621. return error(logUnresolvedImport(source, importer));
  20622. }
  20623. this.options.onLog(LOGLEVEL_WARN, logUnresolvedImportTreatedAsExternal(source, importer));
  20624. return {
  20625. attributes,
  20626. external: true,
  20627. id: source,
  20628. meta: {},
  20629. moduleSideEffects: this.hasModuleSideEffects(source, true),
  20630. resolvedBy: 'rollup',
  20631. syntheticNamedExports: false
  20632. };
  20633. }
  20634. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  20635. this.options.onLog(LOGLEVEL_WARN, logExternalSyntheticExports(source, importer));
  20636. }
  20637. return resolvedId;
  20638. }
  20639. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  20640. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT, this.options.fs);
  20641. if (resolveIdResult == null) {
  20642. return error(implicitlyLoadedBefore === null
  20643. ? logUnresolvedEntry(unresolvedId)
  20644. : logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  20645. }
  20646. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  20647. if (resolveIdResult === false || isExternalModules) {
  20648. return error(implicitlyLoadedBefore === null
  20649. ? isExternalModules && isLoadForManualChunks
  20650. ? logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  20651. : logEntryCannotBeExternal(unresolvedId)
  20652. : logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  20653. }
  20654. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  20655. ? resolveIdResult
  20656. : { id: resolveIdResult }, EMPTY_OBJECT), undefined, isEntry, false);
  20657. }
  20658. async resolveDynamicImport(module, specifier, importer, attributes) {
  20659. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  20660. specifier,
  20661. importer,
  20662. { attributes }
  20663. ]);
  20664. if (typeof specifier !== 'string') {
  20665. if (typeof resolution === 'string') {
  20666. return resolution;
  20667. }
  20668. if (!resolution) {
  20669. return null;
  20670. }
  20671. return this.getResolvedIdWithDefaults(resolution, attributes);
  20672. }
  20673. if (resolution == null) {
  20674. const existingResolution = module.resolvedIds[specifier];
  20675. if (existingResolution) {
  20676. if (doAttributesDiffer(existingResolution.attributes, attributes)) {
  20677. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
  20678. }
  20679. return existingResolution;
  20680. }
  20681. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false, attributes), specifier, module.id, attributes));
  20682. }
  20683. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
  20684. }
  20685. }
  20686. function normalizeRelativeExternalId(source, importer) {
  20687. return isRelative(source)
  20688. ? importer
  20689. ? resolve$1(importer, '..', source)
  20690. : resolve$1(source)
  20691. : source;
  20692. }
  20693. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  20694. if (fileName !== null) {
  20695. module.chunkFileNames.add(fileName);
  20696. }
  20697. else if (name !== null) {
  20698. // Always keep chunkNames sorted by priority
  20699. let namePosition = 0;
  20700. while (module.chunkNames[namePosition]?.priority < priority)
  20701. namePosition++;
  20702. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  20703. }
  20704. }
  20705. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  20706. return (makeAbsoluteExternalsRelative === true ||
  20707. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  20708. !isAbsolute$1(id));
  20709. }
  20710. async function waitForDependencyResolution(loadPromise) {
  20711. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  20712. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  20713. }
  20714. function generateAssetFileName(name, names, source, originalFileName, originalFileNames, sourceHash, outputOptions, bundle, inputOptions) {
  20715. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  20716. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  20717. ? outputOptions.assetFileNames({
  20718. // Additionally, this should be non-enumerable in the next major
  20719. get name() {
  20720. warnDeprecation('Accessing the "name" property of emitted assets when generating the file name is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
  20721. return name;
  20722. },
  20723. names,
  20724. // Additionally, this should be non-enumerable in the next major
  20725. get originalFileName() {
  20726. warnDeprecation('Accessing the "originalFileName" property of emitted assets when generating the file name is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
  20727. return originalFileName;
  20728. },
  20729. originalFileNames,
  20730. source,
  20731. type: 'asset'
  20732. })
  20733. : outputOptions.assetFileNames, 'output.assetFileNames', {
  20734. ext: () => extname(emittedName).slice(1),
  20735. extname: () => extname(emittedName),
  20736. hash: size => sourceHash.slice(0, Math.min(Math.max(0, size || DEFAULT_HASH_SIZE), MAX_HASH_SIZE)),
  20737. name: () => emittedName.slice(0, Math.max(0, emittedName.length - extname(emittedName).length))
  20738. }), bundle);
  20739. }
  20740. function reserveFileNameInBundle(fileName, { bundle }, log) {
  20741. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  20742. log(LOGLEVEL_WARN, logFileNameConflict(fileName));
  20743. }
  20744. else {
  20745. bundle[fileName] = FILE_PLACEHOLDER;
  20746. }
  20747. }
  20748. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  20749. function hasValidType(emittedFile) {
  20750. return Boolean(emittedFile &&
  20751. emittedFileTypes.has(emittedFile.type));
  20752. }
  20753. function hasValidName(emittedFile) {
  20754. const validatedName = emittedFile.fileName || emittedFile.name;
  20755. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  20756. }
  20757. function getValidSource(source, emittedFile, fileReferenceId) {
  20758. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  20759. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  20760. 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.`));
  20761. }
  20762. return source;
  20763. }
  20764. function getAssetFileName(file, referenceId) {
  20765. if (typeof file.fileName !== 'string') {
  20766. return error(logAssetNotFinalisedForFileName(file.name || referenceId));
  20767. }
  20768. return file.fileName;
  20769. }
  20770. function getChunkFileName(file, facadeChunkByModule) {
  20771. if (file.fileName) {
  20772. return file.fileName;
  20773. }
  20774. if (facadeChunkByModule) {
  20775. return facadeChunkByModule.get(file.module).getFileName();
  20776. }
  20777. return error(logChunkNotGeneratedForFileName(file.fileName || file.name));
  20778. }
  20779. class FileEmitter {
  20780. constructor(graph, options, baseFileEmitter) {
  20781. this.graph = graph;
  20782. this.options = options;
  20783. this.facadeChunkByModule = null;
  20784. this.nextIdBase = 1;
  20785. this.output = null;
  20786. this.outputFileEmitters = [];
  20787. this.emitFile = (emittedFile) => {
  20788. if (!hasValidType(emittedFile)) {
  20789. return error(logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  20790. }
  20791. if (emittedFile.type === 'prebuilt-chunk') {
  20792. return this.emitPrebuiltChunk(emittedFile);
  20793. }
  20794. if (!hasValidName(emittedFile)) {
  20795. 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}".`));
  20796. }
  20797. if (emittedFile.type === 'chunk') {
  20798. return this.emitChunk(emittedFile);
  20799. }
  20800. return this.emitAsset(emittedFile);
  20801. };
  20802. this.finaliseAssets = () => {
  20803. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  20804. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  20805. return error(logNoAssetSourceSet(emittedFile.name || referenceId));
  20806. }
  20807. };
  20808. this.getFileName = (fileReferenceId) => {
  20809. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  20810. if (!emittedFile)
  20811. return error(logFileReferenceIdNotFoundForFilename(fileReferenceId));
  20812. if (emittedFile.type === 'chunk') {
  20813. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  20814. }
  20815. if (emittedFile.type === 'prebuilt-chunk') {
  20816. return emittedFile.fileName;
  20817. }
  20818. return getAssetFileName(emittedFile, fileReferenceId);
  20819. };
  20820. this.setAssetSource = (referenceId, requestedSource) => {
  20821. const consumedFile = this.filesByReferenceId.get(referenceId);
  20822. if (!consumedFile)
  20823. return error(logAssetReferenceIdNotFoundForSetSource(referenceId));
  20824. if (consumedFile.type !== 'asset') {
  20825. return error(logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  20826. }
  20827. if (consumedFile.source !== undefined) {
  20828. return error(logAssetSourceAlreadySet(consumedFile.name || referenceId));
  20829. }
  20830. const source = getValidSource(requestedSource, consumedFile, referenceId);
  20831. if (this.output) {
  20832. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  20833. }
  20834. else {
  20835. consumedFile.source = source;
  20836. for (const emitter of this.outputFileEmitters) {
  20837. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  20838. }
  20839. }
  20840. };
  20841. this.setChunkInformation = (facadeChunkByModule) => {
  20842. this.facadeChunkByModule = facadeChunkByModule;
  20843. };
  20844. this.setOutputBundle = (bundle, outputOptions) => {
  20845. const getHash = hasherByType[outputOptions.hashCharacters];
  20846. const output = (this.output = {
  20847. bundle,
  20848. fileNamesBySourceHash: new Map(),
  20849. getHash,
  20850. outputOptions
  20851. });
  20852. for (const emittedFile of this.filesByReferenceId.values()) {
  20853. if (emittedFile.fileName) {
  20854. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  20855. }
  20856. }
  20857. const consumedAssetsByHash = new Map();
  20858. for (const consumedFile of this.filesByReferenceId.values()) {
  20859. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  20860. if (consumedFile.fileName) {
  20861. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  20862. }
  20863. else {
  20864. const sourceHash = getHash(consumedFile.source);
  20865. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  20866. }
  20867. }
  20868. else if (consumedFile.type === 'prebuilt-chunk') {
  20869. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  20870. }
  20871. }
  20872. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  20873. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  20874. }
  20875. };
  20876. this.filesByReferenceId = baseFileEmitter
  20877. ? new Map(baseFileEmitter.filesByReferenceId)
  20878. : new Map();
  20879. baseFileEmitter?.addOutputFileEmitter(this);
  20880. }
  20881. addOutputFileEmitter(outputFileEmitter) {
  20882. this.outputFileEmitters.push(outputFileEmitter);
  20883. }
  20884. assignReferenceId(file, idBase) {
  20885. let referenceId = idBase;
  20886. do {
  20887. referenceId = getHash64(referenceId).slice(0, 8).replaceAll('-', '$');
  20888. } while (this.filesByReferenceId.has(referenceId) ||
  20889. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  20890. file.referenceId = referenceId;
  20891. this.filesByReferenceId.set(referenceId, file);
  20892. for (const { filesByReferenceId } of this.outputFileEmitters) {
  20893. filesByReferenceId.set(referenceId, file);
  20894. }
  20895. return referenceId;
  20896. }
  20897. createPrebuiltChunk(prebuiltChunk) {
  20898. return {
  20899. code: prebuiltChunk.code,
  20900. dynamicImports: [],
  20901. exports: prebuiltChunk.exports || [],
  20902. facadeModuleId: null,
  20903. fileName: prebuiltChunk.fileName,
  20904. implicitlyLoadedBefore: [],
  20905. importedBindings: {},
  20906. imports: [],
  20907. isDynamicEntry: false,
  20908. isEntry: false,
  20909. isImplicitEntry: false,
  20910. map: prebuiltChunk.map || null,
  20911. moduleIds: [],
  20912. modules: {},
  20913. name: prebuiltChunk.fileName,
  20914. preliminaryFileName: prebuiltChunk.fileName,
  20915. referencedFiles: [],
  20916. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  20917. type: 'chunk'
  20918. };
  20919. }
  20920. emitAsset(emittedAsset) {
  20921. const source = emittedAsset.source === undefined
  20922. ? undefined
  20923. : getValidSource(emittedAsset.source, emittedAsset, null);
  20924. const originalFileName = emittedAsset.originalFileName || null;
  20925. if (typeof originalFileName === 'string') {
  20926. this.graph.watchFiles[originalFileName] = true;
  20927. }
  20928. const consumedAsset = {
  20929. fileName: emittedAsset.fileName,
  20930. name: emittedAsset.name,
  20931. needsCodeReference: !!emittedAsset.needsCodeReference,
  20932. originalFileName,
  20933. referenceId: '',
  20934. source,
  20935. type: 'asset'
  20936. };
  20937. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  20938. if (this.output) {
  20939. this.emitAssetWithReferenceId(consumedAsset, this.output);
  20940. }
  20941. else {
  20942. for (const fileEmitter of this.outputFileEmitters) {
  20943. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  20944. }
  20945. }
  20946. return referenceId;
  20947. }
  20948. emitAssetWithReferenceId(consumedAsset, output) {
  20949. const { fileName, source } = consumedAsset;
  20950. if (fileName) {
  20951. reserveFileNameInBundle(fileName, output, this.options.onLog);
  20952. }
  20953. if (source !== undefined) {
  20954. this.finalizeAdditionalAsset(consumedAsset, source, output);
  20955. }
  20956. }
  20957. emitChunk(emittedChunk) {
  20958. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  20959. return error(logInvalidRollupPhaseForChunkEmission());
  20960. }
  20961. if (typeof emittedChunk.id !== 'string') {
  20962. return error(logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  20963. }
  20964. const consumedChunk = {
  20965. fileName: emittedChunk.fileName,
  20966. module: null,
  20967. name: emittedChunk.name || emittedChunk.id,
  20968. referenceId: '',
  20969. type: 'chunk'
  20970. };
  20971. this.graph.moduleLoader
  20972. .emitChunk(emittedChunk)
  20973. .then(module => (consumedChunk.module = module))
  20974. .catch(() => {
  20975. // Avoid unhandled Promise rejection as the error will be thrown later
  20976. // once module loading has finished
  20977. });
  20978. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  20979. }
  20980. emitPrebuiltChunk(emitPrebuiltChunk) {
  20981. if (typeof emitPrebuiltChunk.code !== 'string') {
  20982. return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  20983. }
  20984. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  20985. isPathFragment(emitPrebuiltChunk.fileName)) {
  20986. return error(logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  20987. }
  20988. const consumedPrebuiltChunk = {
  20989. code: emitPrebuiltChunk.code,
  20990. exports: emitPrebuiltChunk.exports,
  20991. fileName: emitPrebuiltChunk.fileName,
  20992. map: emitPrebuiltChunk.map,
  20993. referenceId: '',
  20994. type: 'prebuilt-chunk'
  20995. };
  20996. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  20997. if (this.output) {
  20998. this.output.bundle[consumedPrebuiltChunk.fileName] =
  20999. this.createPrebuiltChunk(consumedPrebuiltChunk);
  21000. }
  21001. return referenceId;
  21002. }
  21003. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySourceHash, getHash, outputOptions }) {
  21004. let { fileName, name, needsCodeReference, originalFileName, referenceId } = consumedFile;
  21005. // Deduplicate assets if an explicit fileName is not provided
  21006. if (!fileName) {
  21007. const sourceHash = getHash(source);
  21008. fileName = fileNamesBySourceHash.get(sourceHash);
  21009. if (!fileName) {
  21010. fileName = generateAssetFileName(name, name ? [name] : [], source, originalFileName, originalFileName ? [originalFileName] : [], sourceHash, outputOptions, bundle, this.options);
  21011. fileNamesBySourceHash.set(sourceHash, fileName);
  21012. }
  21013. }
  21014. // We must not modify the original assets to avoid interaction between outputs
  21015. const assetWithFileName = { ...consumedFile, fileName, source };
  21016. this.filesByReferenceId.set(referenceId, assetWithFileName);
  21017. const existingAsset = bundle[fileName];
  21018. if (existingAsset?.type === 'asset') {
  21019. existingAsset.needsCodeReference &&= needsCodeReference;
  21020. if (name) {
  21021. existingAsset.names.push(name);
  21022. }
  21023. if (originalFileName) {
  21024. existingAsset.originalFileNames.push(originalFileName);
  21025. }
  21026. }
  21027. else {
  21028. const { options } = this;
  21029. bundle[fileName] = {
  21030. fileName,
  21031. get name() {
  21032. // Additionally, this should be non-enumerable in the next major
  21033. warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
  21034. return name;
  21035. },
  21036. names: name ? [name] : [],
  21037. needsCodeReference,
  21038. get originalFileName() {
  21039. // Additionally, this should be non-enumerable in the next major
  21040. warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
  21041. return originalFileName;
  21042. },
  21043. originalFileNames: originalFileName ? [originalFileName] : [],
  21044. source,
  21045. type: 'asset'
  21046. };
  21047. }
  21048. }
  21049. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySourceHash, outputOptions }) {
  21050. const { names, originalFileNames } = getNamesFromAssets(consumedFiles);
  21051. let fileName = '';
  21052. let usedConsumedFile;
  21053. let needsCodeReference = true;
  21054. for (const consumedFile of consumedFiles) {
  21055. needsCodeReference &&= consumedFile.needsCodeReference;
  21056. const assetFileName = generateAssetFileName(consumedFile.name, names, consumedFile.source, consumedFile.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
  21057. if (!fileName ||
  21058. assetFileName.length < fileName.length ||
  21059. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  21060. fileName = assetFileName;
  21061. usedConsumedFile = consumedFile;
  21062. }
  21063. }
  21064. fileNamesBySourceHash.set(sourceHash, fileName);
  21065. for (const consumedFile of consumedFiles) {
  21066. // We must not modify the original assets to avoid interaction between outputs
  21067. const assetWithFileName = { ...consumedFile, fileName };
  21068. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  21069. }
  21070. const { options } = this;
  21071. bundle[fileName] = {
  21072. fileName,
  21073. get name() {
  21074. // Additionally, this should be non-enumerable in the next major
  21075. warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
  21076. return usedConsumedFile.name;
  21077. },
  21078. names,
  21079. needsCodeReference,
  21080. get originalFileName() {
  21081. // Additionally, this should be non-enumerable in the next major
  21082. warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
  21083. return usedConsumedFile.originalFileName;
  21084. },
  21085. originalFileNames,
  21086. source: usedConsumedFile.source,
  21087. type: 'asset'
  21088. };
  21089. }
  21090. }
  21091. function getNamesFromAssets(consumedFiles) {
  21092. const names = [];
  21093. const originalFileNames = [];
  21094. for (const { name, originalFileName } of consumedFiles) {
  21095. if (typeof name === 'string') {
  21096. names.push(name);
  21097. }
  21098. if (originalFileName) {
  21099. originalFileNames.push(originalFileName);
  21100. }
  21101. }
  21102. originalFileNames.sort();
  21103. // Sort by length first and then alphabetically so that the order is stable
  21104. // and the shortest names come first
  21105. names.sort((a, b) => a.length - b.length || (a > b ? 1 : a === b ? 0 : -1));
  21106. return { names, originalFileNames };
  21107. }
  21108. function getLogHandler(level, code, logger, pluginName, logLevel) {
  21109. if (logLevelPriority[level] < logLevelPriority[logLevel]) {
  21110. return doNothing;
  21111. }
  21112. return (log, pos) => {
  21113. if (pos != null) {
  21114. logger(LOGLEVEL_WARN, logInvalidLogPosition(pluginName));
  21115. }
  21116. log = normalizeLog(log);
  21117. if (log.code && !log.pluginCode) {
  21118. log.pluginCode = log.code;
  21119. }
  21120. log.code = code;
  21121. log.plugin = pluginName;
  21122. logger(level, log);
  21123. };
  21124. }
  21125. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  21126. const { logLevel, onLog } = options;
  21127. let cacheable = true;
  21128. if (typeof plugin.cacheKey !== 'string') {
  21129. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  21130. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  21131. existingPluginNames.has(plugin.name)) {
  21132. cacheable = false;
  21133. }
  21134. else {
  21135. existingPluginNames.add(plugin.name);
  21136. }
  21137. }
  21138. let cacheInstance;
  21139. if (!pluginCache) {
  21140. cacheInstance = NO_CACHE;
  21141. }
  21142. else if (cacheable) {
  21143. const cacheKey = plugin.cacheKey || plugin.name;
  21144. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  21145. }
  21146. else {
  21147. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  21148. }
  21149. return {
  21150. addWatchFile(id) {
  21151. graph.watchFiles[id] = true;
  21152. },
  21153. cache: cacheInstance,
  21154. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  21155. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  21156. error(error_) {
  21157. return error(logPluginError(normalizeLog(error_), plugin.name));
  21158. },
  21159. fs: options.fs,
  21160. getFileName: fileEmitter.getFileName,
  21161. getModuleIds: () => graph.modulesById.keys(),
  21162. getModuleInfo: graph.getModuleInfo,
  21163. getWatchFiles: () => Object.keys(graph.watchFiles),
  21164. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  21165. load(resolvedId) {
  21166. return graph.moduleLoader.preloadModule(resolvedId);
  21167. },
  21168. meta: {
  21169. rollupVersion: version,
  21170. watchMode: graph.watchMode
  21171. },
  21172. parse: parseAst,
  21173. resolve(source, importer, { attributes, custom, isEntry, skipSelf } = BLANK) {
  21174. skipSelf ??= true;
  21175. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  21176. },
  21177. setAssetSource: fileEmitter.setAssetSource,
  21178. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  21179. };
  21180. }
  21181. function ensureArray(items) {
  21182. if (Array.isArray(items)) {
  21183. return items.filter(Boolean);
  21184. }
  21185. if (items) {
  21186. return [items];
  21187. }
  21188. return [];
  21189. }
  21190. function getMatcherString(glob, cwd) {
  21191. if (glob.startsWith('**') || isAbsolute$1(glob)) {
  21192. return normalize(glob);
  21193. }
  21194. const resolved = resolve$1(cwd, glob);
  21195. return normalize(resolved);
  21196. }
  21197. function patternToIdFilter(pattern) {
  21198. if (pattern instanceof RegExp) {
  21199. return (id) => {
  21200. const normalizedId = normalize(id);
  21201. const result = pattern.test(normalizedId);
  21202. pattern.lastIndex = 0;
  21203. return result;
  21204. };
  21205. }
  21206. const cwd = process.cwd();
  21207. const glob = getMatcherString(pattern, cwd);
  21208. const matcher = picomatch(glob, { dot: true });
  21209. return (id) => {
  21210. const normalizedId = normalize(id);
  21211. return matcher(normalizedId);
  21212. };
  21213. }
  21214. function patternToCodeFilter(pattern) {
  21215. if (pattern instanceof RegExp) {
  21216. return (code) => {
  21217. const result = pattern.test(code);
  21218. pattern.lastIndex = 0;
  21219. return result;
  21220. };
  21221. }
  21222. return (code) => code.includes(pattern);
  21223. }
  21224. function createFilter(exclude, include) {
  21225. if (!exclude && !include) {
  21226. return;
  21227. }
  21228. return input => {
  21229. if (exclude?.some(filter => filter(input))) {
  21230. return false;
  21231. }
  21232. if (include?.some(filter => filter(input))) {
  21233. return true;
  21234. }
  21235. return !(include && include.length > 0);
  21236. };
  21237. }
  21238. function normalizeFilter(filter) {
  21239. if (typeof filter === 'string' || filter instanceof RegExp) {
  21240. return {
  21241. include: [filter]
  21242. };
  21243. }
  21244. if (Array.isArray(filter)) {
  21245. return {
  21246. include: filter
  21247. };
  21248. }
  21249. return {
  21250. exclude: filter.exclude ? ensureArray(filter.exclude) : undefined,
  21251. include: filter.include ? ensureArray(filter.include) : undefined
  21252. };
  21253. }
  21254. function createIdFilter(filter) {
  21255. if (!filter)
  21256. return;
  21257. const { exclude, include } = normalizeFilter(filter);
  21258. const excludeFilter = exclude?.map(patternToIdFilter);
  21259. const includeFilter = include?.map(patternToIdFilter);
  21260. return createFilter(excludeFilter, includeFilter);
  21261. }
  21262. function createCodeFilter(filter) {
  21263. if (!filter)
  21264. return;
  21265. const { exclude, include } = normalizeFilter(filter);
  21266. const excludeFilter = exclude?.map(patternToCodeFilter);
  21267. const includeFilter = include?.map(patternToCodeFilter);
  21268. return createFilter(excludeFilter, includeFilter);
  21269. }
  21270. function createFilterForId(filter) {
  21271. const filterFunction = createIdFilter(filter);
  21272. return filterFunction ? id => !!filterFunction(id) : undefined;
  21273. }
  21274. function createFilterForTransform(idFilter, codeFilter) {
  21275. if (!idFilter && !codeFilter)
  21276. return;
  21277. const idFilterFunction = createIdFilter(idFilter);
  21278. const codeFilterFunction = createCodeFilter(codeFilter);
  21279. return (id, code) => {
  21280. let fallback = true;
  21281. if (idFilterFunction) {
  21282. fallback &&= idFilterFunction(id);
  21283. }
  21284. if (!fallback) {
  21285. return false;
  21286. }
  21287. if (codeFilterFunction) {
  21288. fallback &&= codeFilterFunction(code);
  21289. }
  21290. return fallback;
  21291. };
  21292. }
  21293. // This will make sure no input hook is omitted
  21294. const inputHookNames = {
  21295. buildEnd: 1,
  21296. buildStart: 1,
  21297. closeBundle: 1,
  21298. closeWatcher: 1,
  21299. load: 1,
  21300. moduleParsed: 1,
  21301. onLog: 1,
  21302. options: 1,
  21303. resolveDynamicImport: 1,
  21304. resolveId: 1,
  21305. shouldTransformCachedModule: 1,
  21306. transform: 1,
  21307. watchChange: 1
  21308. };
  21309. const inputHooks = Object.keys(inputHookNames);
  21310. class PluginDriver {
  21311. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  21312. this.graph = graph;
  21313. this.options = options;
  21314. this.pluginCache = pluginCache;
  21315. this.sortedPlugins = new Map();
  21316. this.unfulfilledActions = new Set();
  21317. this.compiledPluginFilters = {
  21318. idOnlyFilter: new WeakMap(),
  21319. transformFilter: new WeakMap()
  21320. };
  21321. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  21322. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  21323. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  21324. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  21325. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  21326. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  21327. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  21328. const existingPluginNames = new Set();
  21329. this.pluginContexts = new Map(this.plugins.map(plugin => [
  21330. plugin,
  21331. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  21332. ]));
  21333. if (basePluginDriver) {
  21334. for (const plugin of userPlugins) {
  21335. for (const hook of inputHooks) {
  21336. if (hook in plugin) {
  21337. options.onLog(LOGLEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
  21338. }
  21339. }
  21340. }
  21341. }
  21342. }
  21343. createOutputPluginDriver(plugins) {
  21344. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  21345. }
  21346. getUnfulfilledHookActions() {
  21347. return this.unfulfilledActions;
  21348. }
  21349. // chains, first non-null result stops and returns
  21350. hookFirst(hookName, parameters, replaceContext, skipped) {
  21351. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  21352. }
  21353. // chains, first non-null result stops and returns result and last plugin
  21354. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  21355. for (const plugin of this.getSortedPlugins(hookName)) {
  21356. if (skipped?.has(plugin))
  21357. continue;
  21358. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  21359. if (result != null)
  21360. return [result, plugin];
  21361. }
  21362. return null;
  21363. }
  21364. // chains synchronously, first non-null result stops and returns
  21365. hookFirstSync(hookName, parameters, replaceContext) {
  21366. for (const plugin of this.getSortedPlugins(hookName)) {
  21367. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21368. if (result != null)
  21369. return result;
  21370. }
  21371. return null;
  21372. }
  21373. // parallel, ignores returns
  21374. async hookParallel(hookName, parameters, replaceContext) {
  21375. const parallelPromises = [];
  21376. for (const plugin of this.getSortedPlugins(hookName)) {
  21377. if (plugin[hookName].sequential) {
  21378. await Promise.all(parallelPromises);
  21379. parallelPromises.length = 0;
  21380. await this.runHook(hookName, parameters, plugin, replaceContext);
  21381. }
  21382. else {
  21383. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  21384. }
  21385. }
  21386. await Promise.all(parallelPromises);
  21387. }
  21388. // chains, reduces returned value, handling the reduced value as the first hook argument
  21389. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  21390. let promise = Promise.resolve(argument0);
  21391. for (const plugin of this.getSortedPlugins(hookName)) {
  21392. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  21393. }
  21394. return promise;
  21395. }
  21396. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  21397. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  21398. for (const plugin of this.getSortedPlugins(hookName)) {
  21399. const parameters = [argument0, ...rest];
  21400. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21401. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  21402. }
  21403. return argument0;
  21404. }
  21405. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  21406. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  21407. const results = [];
  21408. const parallelResults = [];
  21409. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  21410. if (plugin[hookName].sequential) {
  21411. results.push(...(await Promise.all(parallelResults)));
  21412. parallelResults.length = 0;
  21413. results.push(await this.runHook(hookName, parameters, plugin));
  21414. }
  21415. else {
  21416. parallelResults.push(this.runHook(hookName, parameters, plugin));
  21417. }
  21418. }
  21419. results.push(...(await Promise.all(parallelResults)));
  21420. return results.reduce(reducer, await initialValue);
  21421. }
  21422. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  21423. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  21424. let accumulator = initialValue;
  21425. for (const plugin of this.getSortedPlugins(hookName)) {
  21426. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21427. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  21428. }
  21429. return accumulator;
  21430. }
  21431. // chains, ignores returns
  21432. hookSeq(hookName, parameters, replaceContext) {
  21433. let promise = Promise.resolve();
  21434. for (const plugin of this.getSortedPlugins(hookName)) {
  21435. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  21436. }
  21437. return promise.then(noReturn);
  21438. }
  21439. getSortedPlugins(hookName, validateHandler) {
  21440. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  21441. }
  21442. // Implementation signature
  21443. runHook(hookName, parameters, plugin, replaceContext) {
  21444. // We always filter for plugins that support the hook before running it
  21445. const hook = plugin[hookName];
  21446. const handler = typeof hook === 'object' ? hook.handler : hook;
  21447. if (typeof hook === 'object' && 'filter' in hook && hook.filter) {
  21448. if (hookName === 'transform') {
  21449. const filter = hook.filter;
  21450. const hookParameters = parameters;
  21451. const compiledFilter = getOrCreate(this.compiledPluginFilters.transformFilter, filter, () => createFilterForTransform(filter.id, filter.code));
  21452. if (compiledFilter && !compiledFilter(hookParameters[1], hookParameters[0])) {
  21453. return Promise.resolve();
  21454. }
  21455. }
  21456. else if (hookName === 'resolveId' || hookName === 'load') {
  21457. const filter = hook.filter;
  21458. const hookParameters = parameters;
  21459. const compiledFilter = getOrCreate(this.compiledPluginFilters.idOnlyFilter, filter, () => createFilterForId(filter.id));
  21460. if (compiledFilter && !compiledFilter(hookParameters[0])) {
  21461. return Promise.resolve();
  21462. }
  21463. }
  21464. }
  21465. let context = this.pluginContexts.get(plugin);
  21466. if (replaceContext) {
  21467. context = replaceContext(context, plugin);
  21468. }
  21469. let action = null;
  21470. return Promise.resolve()
  21471. .then(() => {
  21472. if (typeof handler !== 'function') {
  21473. return handler;
  21474. }
  21475. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  21476. const hookResult = handler.apply(context, parameters);
  21477. if (!hookResult?.then) {
  21478. // short circuit for non-thenables and non-Promises
  21479. return hookResult;
  21480. }
  21481. // Track pending hook actions to properly error out when
  21482. // unfulfilled promises cause rollup to abruptly and confusingly
  21483. // exit with a successful 0 return code but without producing any
  21484. // output, errors or warnings.
  21485. action = [plugin.name, hookName, parameters];
  21486. this.unfulfilledActions.add(action);
  21487. // Although it would be more elegant to just return hookResult here
  21488. // and put the .then() handler just above the .catch() handler below,
  21489. // doing so would subtly change the defacto async event dispatch order
  21490. // which at least one test and some plugins in the wild may depend on.
  21491. return Promise.resolve(hookResult).then(result => {
  21492. // action was fulfilled
  21493. this.unfulfilledActions.delete(action);
  21494. return result;
  21495. });
  21496. })
  21497. .catch(error_ => {
  21498. if (action !== null) {
  21499. // action considered to be fulfilled since error being handled
  21500. this.unfulfilledActions.delete(action);
  21501. }
  21502. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  21503. });
  21504. }
  21505. /**
  21506. * Run a sync plugin hook and return the result.
  21507. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  21508. * @param args Arguments passed to the plugin hook.
  21509. * @param plugin The acutal plugin
  21510. * @param replaceContext When passed, the plugin context can be overridden.
  21511. */
  21512. runHookSync(hookName, parameters, plugin, replaceContext) {
  21513. const hook = plugin[hookName];
  21514. const handler = typeof hook === 'object' ? hook.handler : hook;
  21515. let context = this.pluginContexts.get(plugin);
  21516. if (replaceContext) {
  21517. context = replaceContext(context, plugin);
  21518. }
  21519. try {
  21520. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  21521. return handler.apply(context, parameters);
  21522. }
  21523. catch (error_) {
  21524. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  21525. }
  21526. }
  21527. }
  21528. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  21529. const pre = [];
  21530. const normal = [];
  21531. const post = [];
  21532. for (const plugin of plugins) {
  21533. const hook = plugin[hookName];
  21534. if (hook) {
  21535. if (typeof hook === 'object') {
  21536. validateHandler(hook.handler, hookName, plugin);
  21537. if (hook.order === 'pre') {
  21538. pre.push(plugin);
  21539. continue;
  21540. }
  21541. if (hook.order === 'post') {
  21542. post.push(plugin);
  21543. continue;
  21544. }
  21545. }
  21546. else {
  21547. validateHandler(hook, hookName, plugin);
  21548. }
  21549. normal.push(plugin);
  21550. }
  21551. }
  21552. return [...pre, ...normal, ...post];
  21553. }
  21554. function validateFunctionPluginHandler(handler, hookName, plugin) {
  21555. if (typeof handler !== 'function') {
  21556. error(logInvalidFunctionPluginHook(hookName, plugin.name));
  21557. }
  21558. }
  21559. function validateAddonPluginHandler(handler, hookName, plugin) {
  21560. if (typeof handler !== 'string' && typeof handler !== 'function') {
  21561. return error(logInvalidAddonPluginHook(hookName, plugin.name));
  21562. }
  21563. }
  21564. function noReturn() { }
  21565. class Queue {
  21566. constructor(maxParallel) {
  21567. this.maxParallel = maxParallel;
  21568. this.queue = [];
  21569. this.workerCount = 0;
  21570. }
  21571. run(task) {
  21572. return new Promise((resolve, reject) => {
  21573. this.queue.push({ reject, resolve, task });
  21574. this.work();
  21575. });
  21576. }
  21577. async work() {
  21578. if (this.workerCount >= this.maxParallel)
  21579. return;
  21580. this.workerCount++;
  21581. let entry;
  21582. while ((entry = this.queue.shift())) {
  21583. const { reject, resolve, task } = entry;
  21584. try {
  21585. const result = await task();
  21586. resolve(result);
  21587. }
  21588. catch (error) {
  21589. reject(error);
  21590. }
  21591. }
  21592. this.workerCount--;
  21593. }
  21594. }
  21595. function normalizeEntryModules(entryModules) {
  21596. if (Array.isArray(entryModules)) {
  21597. return entryModules.map(id => ({
  21598. fileName: null,
  21599. id,
  21600. implicitlyLoadedAfter: [],
  21601. importer: undefined,
  21602. name: null
  21603. }));
  21604. }
  21605. return Object.entries(entryModules).map(([name, id]) => ({
  21606. fileName: null,
  21607. id,
  21608. implicitlyLoadedAfter: [],
  21609. importer: undefined,
  21610. name
  21611. }));
  21612. }
  21613. class Graph {
  21614. constructor(options, watcher) {
  21615. this.options = options;
  21616. this.astLru = flru(5);
  21617. this.cachedModules = new Map();
  21618. this.deoptimizationTracker = new EntityPathTracker();
  21619. this.entryModules = [];
  21620. this.modulesById = new Map();
  21621. this.needsTreeshakingPass = false;
  21622. this.newlyIncludedVariableInits = new Set();
  21623. this.phase = BuildPhase.LOAD_AND_PARSE;
  21624. this.scope = new GlobalScope();
  21625. this.watchFiles = Object.create(null);
  21626. this.watchMode = false;
  21627. this.externalModules = [];
  21628. this.implicitEntryModules = [];
  21629. this.modules = [];
  21630. this.getModuleInfo = (moduleId) => {
  21631. const foundModule = this.modulesById.get(moduleId);
  21632. if (!foundModule)
  21633. return null;
  21634. return foundModule.info;
  21635. };
  21636. if (options.cache !== false) {
  21637. if (options.cache?.modules) {
  21638. for (const module of options.cache.modules)
  21639. this.cachedModules.set(module.id, module);
  21640. }
  21641. this.pluginCache = options.cache?.plugins || Object.create(null);
  21642. // increment access counter
  21643. for (const name in this.pluginCache) {
  21644. const cache = this.pluginCache[name];
  21645. for (const value of Object.values(cache))
  21646. value[0]++;
  21647. }
  21648. }
  21649. if (watcher) {
  21650. this.watchMode = true;
  21651. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  21652. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  21653. watcher.onCurrentRun('change', handleChange);
  21654. watcher.onCurrentRun('close', handleClose);
  21655. }
  21656. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  21657. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  21658. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  21659. this.pureFunctions = getPureFunctions(options);
  21660. }
  21661. async build() {
  21662. timeStart('generate module graph', 2);
  21663. await this.generateModuleGraph();
  21664. timeEnd('generate module graph', 2);
  21665. timeStart('sort and bind modules', 2);
  21666. this.phase = BuildPhase.ANALYSE;
  21667. this.sortModules();
  21668. timeEnd('sort and bind modules', 2);
  21669. timeStart('mark included statements', 2);
  21670. this.includeStatements();
  21671. timeEnd('mark included statements', 2);
  21672. this.phase = BuildPhase.GENERATE;
  21673. }
  21674. getCache() {
  21675. // handle plugin cache eviction
  21676. for (const name in this.pluginCache) {
  21677. const cache = this.pluginCache[name];
  21678. let allDeleted = true;
  21679. for (const [key, value] of Object.entries(cache)) {
  21680. if (value[0] >= this.options.experimentalCacheExpiry)
  21681. delete cache[key];
  21682. else
  21683. allDeleted = false;
  21684. }
  21685. if (allDeleted)
  21686. delete this.pluginCache[name];
  21687. }
  21688. return {
  21689. modules: this.modules.map(module => module.toJSON()),
  21690. plugins: this.pluginCache
  21691. };
  21692. }
  21693. async generateModuleGraph() {
  21694. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  21695. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  21696. if (this.entryModules.length === 0) {
  21697. throw new Error('You must supply options.input to rollup');
  21698. }
  21699. for (const module of this.modulesById.values()) {
  21700. module.cacheInfoGetters();
  21701. if (module instanceof Module) {
  21702. this.modules.push(module);
  21703. }
  21704. else {
  21705. this.externalModules.push(module);
  21706. }
  21707. }
  21708. }
  21709. includeStatements() {
  21710. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  21711. for (const module of entryModules) {
  21712. markModuleAndImpureDependenciesAsExecuted(module);
  21713. }
  21714. if (this.options.treeshake) {
  21715. let treeshakingPass = 1;
  21716. this.newlyIncludedVariableInits.clear();
  21717. do {
  21718. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  21719. this.needsTreeshakingPass = false;
  21720. for (const module of this.modules) {
  21721. if (module.isExecuted) {
  21722. module.hasTreeShakingPassStarted = true;
  21723. if (module.info.moduleSideEffects === 'no-treeshake') {
  21724. module.includeAllInBundle();
  21725. }
  21726. else {
  21727. module.include();
  21728. }
  21729. for (const entity of this.newlyIncludedVariableInits) {
  21730. this.newlyIncludedVariableInits.delete(entity);
  21731. entity.include(createInclusionContext(), false);
  21732. }
  21733. }
  21734. }
  21735. if (treeshakingPass === 1) {
  21736. // We only include exports after the first pass to avoid issues with
  21737. // the TDZ detection logic
  21738. for (const module of entryModules) {
  21739. if (module.preserveSignature !== false) {
  21740. module.includeAllExports(false);
  21741. this.needsTreeshakingPass = true;
  21742. }
  21743. }
  21744. }
  21745. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  21746. } while (this.needsTreeshakingPass);
  21747. }
  21748. else {
  21749. for (const module of this.modules)
  21750. module.includeAllInBundle();
  21751. }
  21752. for (const externalModule of this.externalModules)
  21753. externalModule.warnUnusedImports();
  21754. for (const module of this.implicitEntryModules) {
  21755. for (const dependant of module.implicitlyLoadedAfter) {
  21756. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  21757. error(logImplicitDependantIsNotIncluded(dependant));
  21758. }
  21759. }
  21760. }
  21761. }
  21762. sortModules() {
  21763. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  21764. for (const cyclePath of cyclePaths) {
  21765. this.options.onLog(LOGLEVEL_WARN, logCircularDependency(cyclePath));
  21766. }
  21767. this.modules = orderedModules;
  21768. for (const module of this.modules) {
  21769. module.bindReferences();
  21770. }
  21771. this.warnForMissingExports();
  21772. }
  21773. warnForMissingExports() {
  21774. for (const module of this.modules) {
  21775. for (const importDescription of module.importDescriptions.values()) {
  21776. if (importDescription.name !== '*') {
  21777. const [variable, options] = importDescription.module.getVariableForExportName(importDescription.name);
  21778. if (!variable) {
  21779. module.log(LOGLEVEL_WARN, logMissingExport(importDescription.name, module.id, importDescription.module.id, !!options?.missingButExportExists), importDescription.start);
  21780. }
  21781. }
  21782. }
  21783. }
  21784. }
  21785. }
  21786. function formatAction([pluginName, hookName, parameters]) {
  21787. const action = `(${pluginName}) ${hookName}`;
  21788. const s = JSON.stringify;
  21789. switch (hookName) {
  21790. case 'resolveId': {
  21791. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  21792. }
  21793. case 'load': {
  21794. return `${action} ${s(parameters[0])}`;
  21795. }
  21796. case 'transform': {
  21797. return `${action} ${s(parameters[1])}`;
  21798. }
  21799. case 'shouldTransformCachedModule': {
  21800. return `${action} ${s(parameters[0].id)}`;
  21801. }
  21802. case 'moduleParsed': {
  21803. return `${action} ${s(parameters[0].id)}`;
  21804. }
  21805. }
  21806. return action;
  21807. }
  21808. let handleBeforeExit = null;
  21809. const rejectByPluginDriver = new Map();
  21810. async function catchUnfinishedHookActions(pluginDriver, callback) {
  21811. const emptyEventLoopPromise = new Promise((_, reject) => {
  21812. rejectByPluginDriver.set(pluginDriver, reject);
  21813. if (!handleBeforeExit) {
  21814. // We only ever create a single event listener to avoid max listener and
  21815. // other issues
  21816. handleBeforeExit = () => {
  21817. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  21818. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  21819. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  21820. [...unfulfilledActions].map(formatAction).join('\n')));
  21821. }
  21822. };
  21823. process$1.once('beforeExit', handleBeforeExit);
  21824. }
  21825. });
  21826. try {
  21827. return await Promise.race([callback(), emptyEventLoopPromise]);
  21828. }
  21829. finally {
  21830. rejectByPluginDriver.delete(pluginDriver);
  21831. if (rejectByPluginDriver.size === 0) {
  21832. process$1.off('beforeExit', handleBeforeExit);
  21833. handleBeforeExit = null;
  21834. }
  21835. }
  21836. }
  21837. async function initWasm() { }
  21838. function getLogger(plugins, onLog, watchMode, logLevel) {
  21839. plugins = getSortedValidatedPlugins('onLog', plugins);
  21840. const minimalPriority = logLevelPriority[logLevel];
  21841. const logger = (level, log, skipped = EMPTY_SET) => {
  21842. augmentLogMessage(log);
  21843. const logPriority = logLevelPriority[level];
  21844. if (logPriority < minimalPriority) {
  21845. return;
  21846. }
  21847. for (const plugin of plugins) {
  21848. if (skipped.has(plugin))
  21849. continue;
  21850. const { onLog: pluginOnLog } = plugin;
  21851. const getLogHandler = (level) => {
  21852. if (logLevelPriority[level] < minimalPriority) {
  21853. return doNothing;
  21854. }
  21855. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  21856. };
  21857. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  21858. if (handler.call({
  21859. debug: getLogHandler(LOGLEVEL_DEBUG),
  21860. error: (log) => error(normalizeLog(log)),
  21861. info: getLogHandler(LOGLEVEL_INFO),
  21862. meta: { rollupVersion: version, watchMode },
  21863. warn: getLogHandler(LOGLEVEL_WARN)
  21864. }, level, log) === false) {
  21865. return;
  21866. }
  21867. }
  21868. onLog(level, log);
  21869. };
  21870. return logger;
  21871. }
  21872. const fs = /*#__PURE__*/_mergeNamespaces({
  21873. __proto__: null
  21874. }, [promises]);
  21875. async function normalizeInputOptions(config, watchMode) {
  21876. // These are options that may trigger special warnings or behaviour later
  21877. // if the user did not select an explicit value
  21878. const unsetOptions = new Set();
  21879. const context = config.context ?? 'undefined';
  21880. const plugins = await normalizePluginOption(config.plugins);
  21881. const logLevel = config.logLevel || LOGLEVEL_INFO;
  21882. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  21883. const strictDeprecations = config.strictDeprecations || false;
  21884. const maxParallelFileOps = getMaxParallelFileOps(config);
  21885. const options = {
  21886. cache: getCache(config),
  21887. context,
  21888. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  21889. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  21890. external: getIdMatcher(config.external),
  21891. fs: config.fs ?? fs,
  21892. input: getInput(config),
  21893. jsx: getJsx(config),
  21894. logLevel,
  21895. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  21896. maxParallelFileOps,
  21897. moduleContext: getModuleContext(config, context),
  21898. onLog,
  21899. perf: config.perf || false,
  21900. plugins,
  21901. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  21902. preserveSymlinks: config.preserveSymlinks || false,
  21903. shimMissingExports: config.shimMissingExports || false,
  21904. strictDeprecations,
  21905. treeshake: getTreeshake(config)
  21906. };
  21907. warnUnknownOptions(config, [...Object.keys(options), 'onwarn', 'watch'], 'input options', onLog, /^(output)$/);
  21908. return { options, unsetOptions };
  21909. }
  21910. const getCache = (config) => config.cache === true // `true` is the default
  21911. ? undefined
  21912. : config.cache?.cache || config.cache;
  21913. const getIdMatcher = (option) => {
  21914. if (option === true) {
  21915. return () => true;
  21916. }
  21917. if (typeof option === 'function') {
  21918. return (id, ...parameters) => (id[0] !== '\0' && option(id, ...parameters)) || false;
  21919. }
  21920. if (option) {
  21921. const ids = new Set();
  21922. const matchers = [];
  21923. for (const value of ensureArray(option)) {
  21924. if (value instanceof RegExp) {
  21925. matchers.push(value);
  21926. }
  21927. else {
  21928. ids.add(value);
  21929. }
  21930. }
  21931. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  21932. }
  21933. return () => false;
  21934. };
  21935. const getInput = (config) => {
  21936. const configInput = config.input;
  21937. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  21938. };
  21939. const getJsx = (config) => {
  21940. const configJsx = config.jsx;
  21941. if (!configJsx)
  21942. return false;
  21943. const configWithPreset = getOptionWithPreset(configJsx, jsxPresets, 'jsx', URL_JSX, 'false, ');
  21944. const { factory, importSource, mode } = configWithPreset;
  21945. switch (mode) {
  21946. case 'automatic': {
  21947. return {
  21948. factory: factory || 'React.createElement',
  21949. importSource: importSource || 'react',
  21950. jsxImportSource: configWithPreset.jsxImportSource || 'react/jsx-runtime',
  21951. mode: 'automatic'
  21952. };
  21953. }
  21954. case 'preserve': {
  21955. if (importSource && !(factory || configWithPreset.fragment)) {
  21956. error(logInvalidOption('jsx', URL_JSX, 'when preserving JSX and specifying an importSource, you also need to specify a factory or fragment'));
  21957. }
  21958. return {
  21959. factory: factory || null,
  21960. fragment: configWithPreset.fragment || null,
  21961. importSource: importSource || null,
  21962. mode: 'preserve'
  21963. };
  21964. }
  21965. // case 'classic':
  21966. default: {
  21967. if (mode && mode !== 'classic') {
  21968. error(logInvalidOption('jsx.mode', URL_JSX, 'mode must be "automatic", "classic" or "preserve"', mode));
  21969. }
  21970. return {
  21971. factory: factory || 'React.createElement',
  21972. fragment: configWithPreset.fragment || 'React.Fragment',
  21973. importSource: importSource || null,
  21974. mode: 'classic'
  21975. };
  21976. }
  21977. }
  21978. };
  21979. const getMaxParallelFileOps = (config) => {
  21980. const maxParallelFileOps = config.maxParallelFileOps;
  21981. if (typeof maxParallelFileOps === 'number') {
  21982. if (maxParallelFileOps <= 0)
  21983. return Infinity;
  21984. return maxParallelFileOps;
  21985. }
  21986. return 1000;
  21987. };
  21988. const getModuleContext = (config, context) => {
  21989. const configModuleContext = config.moduleContext;
  21990. if (typeof configModuleContext === 'function') {
  21991. return id => configModuleContext(id) ?? context;
  21992. }
  21993. if (configModuleContext) {
  21994. const contextByModuleId = Object.create(null);
  21995. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  21996. contextByModuleId[resolve$1(key)] = moduleContext;
  21997. }
  21998. return id => contextByModuleId[id] ?? context;
  21999. }
  22000. return () => context;
  22001. };
  22002. const getTreeshake = (config) => {
  22003. const configTreeshake = config.treeshake;
  22004. if (configTreeshake === false) {
  22005. return false;
  22006. }
  22007. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ');
  22008. return {
  22009. annotations: configWithPreset.annotations !== false,
  22010. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  22011. manualPureFunctions: configWithPreset.manualPureFunctions ?? EMPTY_ARRAY,
  22012. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  22013. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  22014. ? 'always'
  22015. : configWithPreset.propertyReadSideEffects !== false,
  22016. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  22017. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  22018. };
  22019. };
  22020. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  22021. if (typeof moduleSideEffectsOption === 'boolean') {
  22022. return () => moduleSideEffectsOption;
  22023. }
  22024. if (moduleSideEffectsOption === 'no-external') {
  22025. return (_id, external) => !external;
  22026. }
  22027. if (typeof moduleSideEffectsOption === 'function') {
  22028. return (id, external) => id[0] === '\0' ? true : moduleSideEffectsOption(id, external) !== false;
  22029. }
  22030. if (Array.isArray(moduleSideEffectsOption)) {
  22031. const ids = new Set(moduleSideEffectsOption);
  22032. return id => ids.has(id);
  22033. }
  22034. if (moduleSideEffectsOption) {
  22035. error(logInvalidOption('treeshake.moduleSideEffects', URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  22036. }
  22037. return () => true;
  22038. };
  22039. // https://datatracker.ietf.org/doc/html/rfc2396
  22040. // eslint-disable-next-line no-control-regex
  22041. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g;
  22042. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  22043. function sanitizeFileName(name) {
  22044. const match = DRIVE_LETTER_REGEX.exec(name);
  22045. const driveLetter = match ? match[0] : '';
  22046. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  22047. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  22048. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  22049. }
  22050. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  22051. // These are options that may trigger special warnings or behaviour later
  22052. // if the user did not select an explicit value
  22053. const unsetOptions = new Set(unsetInputOptions);
  22054. const compact = config.compact || false;
  22055. const format = getFormat(config);
  22056. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  22057. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  22058. const file = getFile(config, preserveModules, inputOptions);
  22059. const generatedCode = getGeneratedCode(config);
  22060. const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
  22061. const outputOptions = {
  22062. amd: getAmd(config),
  22063. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  22064. banner: getAddon(config, 'banner'),
  22065. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  22066. compact,
  22067. dir: getDir(config, file),
  22068. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  22069. entryFileNames: getEntryFileNames(config, unsetOptions),
  22070. esModule: config.esModule ?? 'if-default-prop',
  22071. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  22072. exports: getExports(config, unsetOptions),
  22073. extend: config.extend || false,
  22074. externalImportAssertions: externalImportAttributes,
  22075. externalImportAttributes,
  22076. externalLiveBindings: config.externalLiveBindings ?? true,
  22077. file,
  22078. footer: getAddon(config, 'footer'),
  22079. format,
  22080. freeze: config.freeze ?? true,
  22081. generatedCode,
  22082. globals: config.globals || {},
  22083. hashCharacters: config.hashCharacters ?? 'base64',
  22084. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  22085. importAttributesKey: config.importAttributesKey ?? 'assert',
  22086. indent: getIndent(config, compact),
  22087. inlineDynamicImports,
  22088. interop: getInterop(config),
  22089. intro: getAddon(config, 'intro'),
  22090. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules),
  22091. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  22092. name: config.name,
  22093. noConflict: config.noConflict || false,
  22094. onlyExplicitManualChunks: config.onlyExplicitManualChunks || false,
  22095. outro: getAddon(config, 'outro'),
  22096. paths: config.paths || {},
  22097. plugins: await normalizePluginOption(config.plugins),
  22098. preserveModules,
  22099. preserveModulesRoot: getPreserveModulesRoot(config),
  22100. reexportProtoFromExternal: config.reexportProtoFromExternal ?? true,
  22101. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  22102. ? config.sanitizeFileName
  22103. : config.sanitizeFileName === false
  22104. ? id => id
  22105. : sanitizeFileName,
  22106. sourcemap: config.sourcemap || false,
  22107. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  22108. sourcemapDebugIds: config.sourcemapDebugIds || false,
  22109. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  22110. sourcemapFile: config.sourcemapFile,
  22111. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  22112. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  22113. ? config.sourcemapIgnoreList
  22114. : config.sourcemapIgnoreList === false
  22115. ? () => false
  22116. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  22117. sourcemapPathTransform: config.sourcemapPathTransform,
  22118. strict: config.strict ?? true,
  22119. systemNullSetters: config.systemNullSetters ?? true,
  22120. validate: config.validate || false,
  22121. virtualDirname: config.virtualDirname || '_virtual'
  22122. };
  22123. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  22124. return { options: outputOptions, unsetOptions };
  22125. }
  22126. const getFile = (config, preserveModules, inputOptions) => {
  22127. const { file } = config;
  22128. if (typeof file === 'string') {
  22129. if (preserveModules) {
  22130. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  22131. }
  22132. if (!Array.isArray(inputOptions.input))
  22133. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  22134. }
  22135. return file;
  22136. };
  22137. const getFormat = (config) => {
  22138. const configFormat = config.format;
  22139. switch (configFormat) {
  22140. case undefined:
  22141. case 'es':
  22142. case 'esm':
  22143. case 'module': {
  22144. return 'es';
  22145. }
  22146. case 'cjs':
  22147. case 'commonjs': {
  22148. return 'cjs';
  22149. }
  22150. case 'system':
  22151. case 'systemjs': {
  22152. return 'system';
  22153. }
  22154. case 'amd':
  22155. case 'iife':
  22156. case 'umd': {
  22157. return configFormat;
  22158. }
  22159. default: {
  22160. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  22161. }
  22162. }
  22163. };
  22164. const getInlineDynamicImports = (config, inputOptions) => {
  22165. const inlineDynamicImports = config.inlineDynamicImports || false;
  22166. const { input } = inputOptions;
  22167. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  22168. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  22169. }
  22170. return inlineDynamicImports;
  22171. };
  22172. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  22173. const preserveModules = config.preserveModules || false;
  22174. if (preserveModules) {
  22175. if (inlineDynamicImports) {
  22176. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  22177. }
  22178. if (inputOptions.preserveEntrySignatures === false) {
  22179. return error(logInvalidOption('preserveEntrySignatures', URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  22180. }
  22181. }
  22182. return preserveModules;
  22183. };
  22184. const getPreserveModulesRoot = (config) => {
  22185. const { preserveModulesRoot } = config;
  22186. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  22187. return undefined;
  22188. }
  22189. return resolve$1(preserveModulesRoot);
  22190. };
  22191. const getAmd = (config) => {
  22192. const mergedOption = {
  22193. autoId: false,
  22194. basePath: '',
  22195. define: 'define',
  22196. forceJsExtensionForImports: false,
  22197. ...config.amd
  22198. };
  22199. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  22200. return error(logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  22201. }
  22202. if (mergedOption.basePath && !mergedOption.autoId) {
  22203. return error(logInvalidOption('output.amd.basePath', URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  22204. }
  22205. return mergedOption.autoId
  22206. ? {
  22207. autoId: true,
  22208. basePath: mergedOption.basePath,
  22209. define: mergedOption.define,
  22210. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  22211. }
  22212. : {
  22213. autoId: false,
  22214. define: mergedOption.define,
  22215. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  22216. id: mergedOption.id
  22217. };
  22218. };
  22219. const getAddon = (config, name) => {
  22220. const configAddon = config[name];
  22221. if (typeof configAddon === 'function') {
  22222. return configAddon;
  22223. }
  22224. return () => configAddon || '';
  22225. };
  22226. const getDir = (config, file) => {
  22227. const { dir } = config;
  22228. if (typeof dir === 'string' && typeof file === 'string') {
  22229. 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'));
  22230. }
  22231. return dir;
  22232. };
  22233. const getEntryFileNames = (config, unsetOptions) => {
  22234. const configEntryFileNames = config.entryFileNames;
  22235. if (configEntryFileNames == null) {
  22236. unsetOptions.add('entryFileNames');
  22237. }
  22238. return configEntryFileNames ?? '[name].js';
  22239. };
  22240. function getExports(config, unsetOptions) {
  22241. const configExports = config.exports;
  22242. if (configExports == null) {
  22243. unsetOptions.add('exports');
  22244. }
  22245. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  22246. return error(logInvalidExportOptionValue(configExports));
  22247. }
  22248. return configExports || 'auto';
  22249. }
  22250. const getExternalImportAttributes = (config, inputOptions) => {
  22251. if (config.externalImportAssertions != undefined) {
  22252. warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
  22253. }
  22254. return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
  22255. };
  22256. const getGeneratedCode = (config) => {
  22257. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
  22258. return {
  22259. arrowFunctions: configWithPreset.arrowFunctions === true,
  22260. constBindings: configWithPreset.constBindings === true,
  22261. objectShorthand: configWithPreset.objectShorthand === true,
  22262. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  22263. symbols: configWithPreset.symbols === true
  22264. };
  22265. };
  22266. const getIndent = (config, compact) => {
  22267. if (compact) {
  22268. return '';
  22269. }
  22270. const configIndent = config.indent;
  22271. return configIndent === false ? '' : (configIndent ?? true);
  22272. };
  22273. const ALLOWED_INTEROP_TYPES = new Set([
  22274. 'compat',
  22275. 'auto',
  22276. 'esModule',
  22277. 'default',
  22278. 'defaultOnly'
  22279. ]);
  22280. const getInterop = (config) => {
  22281. const configInterop = config.interop;
  22282. if (typeof configInterop === 'function') {
  22283. const interopPerId = Object.create(null);
  22284. let defaultInterop = null;
  22285. return id => id === null
  22286. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22287. : id in interopPerId
  22288. ? interopPerId[id]
  22289. : validateInterop((interopPerId[id] = configInterop(id)));
  22290. }
  22291. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  22292. };
  22293. const validateInterop = (interop) => {
  22294. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22295. return error(logInvalidOption('output.interop', URL_OUTPUT_INTEROP, `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  22296. }
  22297. return interop;
  22298. };
  22299. const getManualChunks = (config, inlineDynamicImports, preserveModules) => {
  22300. const configManualChunks = config.manualChunks;
  22301. if (configManualChunks) {
  22302. if (inlineDynamicImports) {
  22303. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  22304. }
  22305. if (preserveModules) {
  22306. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  22307. }
  22308. }
  22309. return configManualChunks || {};
  22310. };
  22311. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  22312. const getSourcemapFileNames = (config, unsetOptions) => {
  22313. const configSourcemapFileNames = config.sourcemapFileNames;
  22314. if (configSourcemapFileNames == null) {
  22315. unsetOptions.add('sourcemapFileNames');
  22316. }
  22317. return configSourcemapFileNames;
  22318. };
  22319. const getSourcemapBaseUrl = (config) => {
  22320. const { sourcemapBaseUrl } = config;
  22321. if (sourcemapBaseUrl) {
  22322. if (isValidUrl(sourcemapBaseUrl)) {
  22323. return addTrailingSlashIfMissed(sourcemapBaseUrl);
  22324. }
  22325. return error(logInvalidOption('output.sourcemapBaseUrl', URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22326. }
  22327. };
  22328. // @ts-expect-error TS2540: the polyfill of `asyncDispose`.
  22329. Symbol.asyncDispose ??= Symbol('Symbol.asyncDispose');
  22330. function rollup(rawInputOptions) {
  22331. return rollupInternal(rawInputOptions, null);
  22332. }
  22333. async function rollupInternal(rawInputOptions, watcher) {
  22334. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22335. initialiseTimers(inputOptions);
  22336. await initWasm();
  22337. const graph = new Graph(inputOptions, watcher);
  22338. // remove the cache object from the memory after graph creation (cache is not used anymore)
  22339. const useCache = rawInputOptions.cache !== false;
  22340. if (rawInputOptions.cache) {
  22341. inputOptions.cache = undefined;
  22342. rawInputOptions.cache = undefined;
  22343. }
  22344. timeStart('BUILD', 1);
  22345. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22346. try {
  22347. timeStart('initialize', 2);
  22348. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22349. timeEnd('initialize', 2);
  22350. await graph.build();
  22351. }
  22352. catch (error_) {
  22353. const watchFiles = Object.keys(graph.watchFiles);
  22354. if (watchFiles.length > 0) {
  22355. error_.watchFiles = watchFiles;
  22356. }
  22357. try {
  22358. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  22359. }
  22360. catch (buildEndError) {
  22361. // Create a compound error object to include both errors, based on the original error
  22362. const compoundError = getRollupError({
  22363. ...error_,
  22364. 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}`
  22365. });
  22366. await graph.pluginDriver.hookParallel('closeBundle', [compoundError]);
  22367. throw compoundError;
  22368. }
  22369. await graph.pluginDriver.hookParallel('closeBundle', [error_]);
  22370. throw error_;
  22371. }
  22372. try {
  22373. await graph.pluginDriver.hookParallel('buildEnd', []);
  22374. }
  22375. catch (buildEndError) {
  22376. await graph.pluginDriver.hookParallel('closeBundle', [buildEndError]);
  22377. throw buildEndError;
  22378. }
  22379. });
  22380. timeEnd('BUILD', 1);
  22381. const result = {
  22382. cache: useCache ? graph.getCache() : undefined,
  22383. async close() {
  22384. if (result.closed)
  22385. return;
  22386. result.closed = true;
  22387. await graph.pluginDriver.hookParallel('closeBundle', []);
  22388. },
  22389. closed: false,
  22390. async [Symbol.asyncDispose]() {
  22391. await this.close();
  22392. },
  22393. async generate(rawOutputOptions) {
  22394. if (result.closed)
  22395. return error(logAlreadyClosed());
  22396. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22397. },
  22398. get watchFiles() {
  22399. return Object.keys(graph.watchFiles);
  22400. },
  22401. async write(rawOutputOptions) {
  22402. if (result.closed)
  22403. return error(logAlreadyClosed());
  22404. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22405. }
  22406. };
  22407. if (inputOptions.perf)
  22408. result.getTimings = getTimings;
  22409. return result;
  22410. }
  22411. async function getInputOptions(initialInputOptions, watchMode) {
  22412. if (!initialInputOptions) {
  22413. throw new Error('You must supply an options object to rollup');
  22414. }
  22415. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  22416. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  22417. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22418. return { options, unsetOptions };
  22419. }
  22420. async function getProcessedInputOptions(inputOptions, watchMode) {
  22421. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  22422. const logLevel = inputOptions.logLevel || LOGLEVEL_INFO;
  22423. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  22424. for (const plugin of plugins) {
  22425. const { name, options } = plugin;
  22426. const handler = 'handler' in options ? options.handler : options;
  22427. const processedOptions = await handler.call({
  22428. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  22429. error: (error_) => error(logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  22430. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  22431. meta: { rollupVersion: version, watchMode },
  22432. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  22433. }, inputOptions);
  22434. if (processedOptions) {
  22435. inputOptions = processedOptions;
  22436. }
  22437. }
  22438. return inputOptions;
  22439. }
  22440. function normalizePlugins(plugins, anonymousPrefix) {
  22441. for (const [index, plugin] of plugins.entries()) {
  22442. if (!plugin.name) {
  22443. plugin.name = `${anonymousPrefix}${index + 1}`;
  22444. }
  22445. }
  22446. }
  22447. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22448. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22449. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22450. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22451. const generated = await bundle.generate(isWrite);
  22452. if (isWrite) {
  22453. timeStart('WRITE', 1);
  22454. if (!outputOptions.dir && !outputOptions.file) {
  22455. return error(logMissingFileOrDirOption());
  22456. }
  22457. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions, inputOptions))));
  22458. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22459. timeEnd('WRITE', 1);
  22460. }
  22461. return createOutput(generated);
  22462. });
  22463. }
  22464. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22465. if (!rawOutputOptions) {
  22466. throw new Error('You must supply an options object');
  22467. }
  22468. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  22469. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22470. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22471. return {
  22472. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  22473. outputPluginDriver
  22474. };
  22475. }
  22476. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22477. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22478. const emitError = () => pluginContext.error(logCannotEmitFromOptionsHook());
  22479. return {
  22480. ...pluginContext,
  22481. emitFile: emitError,
  22482. setAssetSource: emitError
  22483. };
  22484. }), inputOptions, unsetInputOptions);
  22485. }
  22486. function createOutput(outputBundle) {
  22487. return {
  22488. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  22489. };
  22490. }
  22491. var SortingFileType;
  22492. (function (SortingFileType) {
  22493. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22494. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22495. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22496. })(SortingFileType || (SortingFileType = {}));
  22497. function getSortingFileType(file) {
  22498. if (file.type === 'asset') {
  22499. return SortingFileType.ASSET;
  22500. }
  22501. if (file.isEntry) {
  22502. return SortingFileType.ENTRY_CHUNK;
  22503. }
  22504. return SortingFileType.SECONDARY_CHUNK;
  22505. }
  22506. async function writeOutputFile(outputFile, outputOptions, { fs: { mkdir, writeFile } }) {
  22507. const fileName = resolve$1(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  22508. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22509. await mkdir(dirname(fileName), { recursive: true });
  22510. return writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  22511. }
  22512. /**
  22513. * Auxiliary function for defining rollup configuration
  22514. * Mainly to facilitate IDE code prompts, after all, export default does not
  22515. * prompt, even if you add @type annotations, it is not accurate
  22516. * @param options
  22517. */
  22518. function defineConfig(options) {
  22519. return options;
  22520. }
  22521. var picocolors = {exports: {}};
  22522. var hasRequiredPicocolors;
  22523. function requirePicocolors () {
  22524. if (hasRequiredPicocolors) return picocolors.exports;
  22525. hasRequiredPicocolors = 1;
  22526. let p = process || {}, argv = p.argv || [], env = p.env || {};
  22527. let isColorSupported =
  22528. !(!!env.NO_COLOR || argv.includes("--no-color")) &&
  22529. (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
  22530. let formatter = (open, close, replace = open) =>
  22531. input => {
  22532. let string = "" + input, index = string.indexOf(close, open.length);
  22533. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  22534. };
  22535. let replaceClose = (string, close, replace, index) => {
  22536. let result = "", cursor = 0;
  22537. do {
  22538. result += string.substring(cursor, index) + replace;
  22539. cursor = index + close.length;
  22540. index = string.indexOf(close, cursor);
  22541. } while (~index)
  22542. return result + string.substring(cursor)
  22543. };
  22544. let createColors = (enabled = isColorSupported) => {
  22545. let f = enabled ? formatter : () => String;
  22546. return {
  22547. isColorSupported: enabled,
  22548. reset: f("\x1b[0m", "\x1b[0m"),
  22549. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  22550. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  22551. italic: f("\x1b[3m", "\x1b[23m"),
  22552. underline: f("\x1b[4m", "\x1b[24m"),
  22553. inverse: f("\x1b[7m", "\x1b[27m"),
  22554. hidden: f("\x1b[8m", "\x1b[28m"),
  22555. strikethrough: f("\x1b[9m", "\x1b[29m"),
  22556. black: f("\x1b[30m", "\x1b[39m"),
  22557. red: f("\x1b[31m", "\x1b[39m"),
  22558. green: f("\x1b[32m", "\x1b[39m"),
  22559. yellow: f("\x1b[33m", "\x1b[39m"),
  22560. blue: f("\x1b[34m", "\x1b[39m"),
  22561. magenta: f("\x1b[35m", "\x1b[39m"),
  22562. cyan: f("\x1b[36m", "\x1b[39m"),
  22563. white: f("\x1b[37m", "\x1b[39m"),
  22564. gray: f("\x1b[90m", "\x1b[39m"),
  22565. bgBlack: f("\x1b[40m", "\x1b[49m"),
  22566. bgRed: f("\x1b[41m", "\x1b[49m"),
  22567. bgGreen: f("\x1b[42m", "\x1b[49m"),
  22568. bgYellow: f("\x1b[43m", "\x1b[49m"),
  22569. bgBlue: f("\x1b[44m", "\x1b[49m"),
  22570. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  22571. bgCyan: f("\x1b[46m", "\x1b[49m"),
  22572. bgWhite: f("\x1b[47m", "\x1b[49m"),
  22573. blackBright: f("\x1b[90m", "\x1b[39m"),
  22574. redBright: f("\x1b[91m", "\x1b[39m"),
  22575. greenBright: f("\x1b[92m", "\x1b[39m"),
  22576. yellowBright: f("\x1b[93m", "\x1b[39m"),
  22577. blueBright: f("\x1b[94m", "\x1b[39m"),
  22578. magentaBright: f("\x1b[95m", "\x1b[39m"),
  22579. cyanBright: f("\x1b[96m", "\x1b[39m"),
  22580. whiteBright: f("\x1b[97m", "\x1b[39m"),
  22581. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  22582. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  22583. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  22584. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  22585. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  22586. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  22587. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  22588. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  22589. }
  22590. };
  22591. picocolors.exports = createColors();
  22592. picocolors.exports.createColors = createColors;
  22593. return picocolors.exports;
  22594. }
  22595. var picocolorsExports = /*@__PURE__*/ requirePicocolors();
  22596. const pc = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  22597. // @see https://no-color.org
  22598. // @see https://www.npmjs.com/package/chalk
  22599. const { bold, cyan, dim, red} = pc.createColors(env.FORCE_COLOR !== '0' && !env.NO_COLOR);
  22600. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  22601. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  22602. function handleError(error, recover = false) {
  22603. const name = error.name || error.cause?.name;
  22604. const nameSection = name ? `${name}: ` : '';
  22605. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  22606. const message = `${pluginSection}${nameSection}${error.message}`;
  22607. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  22608. if (error.url) {
  22609. outputLines.push(cyan(error.url));
  22610. }
  22611. if (error.loc) {
  22612. outputLines.push(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  22613. }
  22614. else if (error.id) {
  22615. outputLines.push(relativeId(error.id));
  22616. }
  22617. if (error.frame) {
  22618. outputLines.push(dim(error.frame));
  22619. }
  22620. if (error.stack) {
  22621. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  22622. }
  22623. // ES2022: Error.prototype.cause is optional
  22624. if (error.cause) {
  22625. let cause = error.cause;
  22626. const causeErrorLines = [];
  22627. let indent = '';
  22628. while (cause) {
  22629. indent += ' ';
  22630. const message = cause.stack || cause;
  22631. causeErrorLines.push(...`[cause] ${message}`.split('\n').map(line => indent + line));
  22632. cause = cause.cause;
  22633. }
  22634. outputLines.push(dim(causeErrorLines.join('\n')));
  22635. }
  22636. outputLines.push('', '');
  22637. stderr(outputLines.join('\n'));
  22638. if (!recover)
  22639. process$1.exit(1);
  22640. }
  22641. const commandAliases = {
  22642. c: 'config',
  22643. d: 'dir',
  22644. e: 'external',
  22645. f: 'format',
  22646. g: 'globals',
  22647. h: 'help',
  22648. i: 'input',
  22649. m: 'sourcemap',
  22650. n: 'name',
  22651. o: 'file',
  22652. p: 'plugin',
  22653. v: 'version',
  22654. w: 'watch'
  22655. };
  22656. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  22657. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  22658. const command = getCommandOptions(rawCommandOptions);
  22659. const plugins = await normalizePluginOption(config.plugins);
  22660. const logLevel = config.logLevel || LOGLEVEL_INFO;
  22661. const onLog = getOnLog(config, logLevel, printLog);
  22662. const log = getLogger(plugins, onLog, watchMode, logLevel);
  22663. const inputOptions = mergeInputOptions(config, command, plugins, log, onLog);
  22664. if (command.output) {
  22665. Object.assign(command, command.output);
  22666. }
  22667. const outputOptionsArray = ensureArray(config.output);
  22668. if (outputOptionsArray.length === 0)
  22669. outputOptionsArray.push({});
  22670. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  22671. warnUnknownOptions(command, [
  22672. ...Object.keys(inputOptions).filter(option => option !== 'fs'),
  22673. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  22674. ...Object.keys(commandAliases),
  22675. 'bundleConfigAsCjs',
  22676. 'config',
  22677. 'configImportAttributesKey',
  22678. 'configPlugin',
  22679. 'environment',
  22680. 'failAfterWarnings',
  22681. 'filterLogs',
  22682. 'forceExit',
  22683. 'plugin',
  22684. 'silent',
  22685. 'stdin',
  22686. 'waitForBundleInput'
  22687. ], 'CLI flags', log, /^_$|output$|config/);
  22688. inputOptions.output = outputOptions;
  22689. return inputOptions;
  22690. }
  22691. function getCommandOptions(rawCommandOptions) {
  22692. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  22693. ? rawCommandOptions.external.split(',')
  22694. : [];
  22695. return {
  22696. ...rawCommandOptions,
  22697. external,
  22698. globals: typeof rawCommandOptions.globals === 'string'
  22699. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  22700. const [id, variableName] = globalDefinition.split(':');
  22701. globals[id] = variableName;
  22702. if (!external.includes(id)) {
  22703. external.push(id);
  22704. }
  22705. return globals;
  22706. }, Object.create(null))
  22707. : undefined
  22708. };
  22709. }
  22710. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  22711. const getOption = (name) => overrides[name] ?? config[name];
  22712. const inputOptions = {
  22713. cache: config.cache,
  22714. context: getOption('context'),
  22715. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  22716. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  22717. external: getExternal(config, overrides),
  22718. fs: getOption('fs'),
  22719. input: getOption('input') || [],
  22720. jsx: getObjectOption(config, overrides, 'jsx', objectifyOptionWithPresets(jsxPresets, 'jsx', URL_JSX, 'false, ')),
  22721. logLevel: getOption('logLevel'),
  22722. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  22723. maxParallelFileOps: getOption('maxParallelFileOps'),
  22724. moduleContext: getOption('moduleContext'),
  22725. onLog,
  22726. onwarn: undefined,
  22727. perf: getOption('perf'),
  22728. plugins,
  22729. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  22730. preserveSymlinks: getOption('preserveSymlinks'),
  22731. shimMissingExports: getOption('shimMissingExports'),
  22732. strictDeprecations: getOption('strictDeprecations'),
  22733. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ')),
  22734. watch: getWatch(config, overrides)
  22735. };
  22736. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  22737. return inputOptions;
  22738. }
  22739. const getExternal = (config, overrides) => {
  22740. const configExternal = config.external;
  22741. return typeof configExternal === 'function'
  22742. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  22743. : [...ensureArray(configExternal), ...overrides.external];
  22744. };
  22745. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  22746. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  22747. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  22748. if (commandOption !== undefined) {
  22749. return commandOption && { ...configOption, ...commandOption };
  22750. }
  22751. return configOption;
  22752. };
  22753. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  22754. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  22755. if (!optionValue) {
  22756. return optionValue;
  22757. }
  22758. if (Array.isArray(optionValue)) {
  22759. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  22760. }
  22761. return objectifyValue(optionValue);
  22762. };
  22763. async function mergeOutputOptions(config, overrides, log) {
  22764. const getOption = (name) => overrides[name] ?? config[name];
  22765. const outputOptions = {
  22766. amd: getObjectOption(config, overrides, 'amd'),
  22767. assetFileNames: getOption('assetFileNames'),
  22768. banner: getOption('banner'),
  22769. chunkFileNames: getOption('chunkFileNames'),
  22770. compact: getOption('compact'),
  22771. dir: getOption('dir'),
  22772. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  22773. entryFileNames: getOption('entryFileNames'),
  22774. esModule: getOption('esModule'),
  22775. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  22776. exports: getOption('exports'),
  22777. extend: getOption('extend'),
  22778. externalImportAssertions: getOption('externalImportAssertions'),
  22779. externalImportAttributes: getOption('externalImportAttributes'),
  22780. externalLiveBindings: getOption('externalLiveBindings'),
  22781. file: getOption('file'),
  22782. footer: getOption('footer'),
  22783. format: getOption('format'),
  22784. freeze: getOption('freeze'),
  22785. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '')),
  22786. globals: getOption('globals'),
  22787. hashCharacters: getOption('hashCharacters'),
  22788. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  22789. importAttributesKey: getOption('importAttributesKey'),
  22790. indent: getOption('indent'),
  22791. inlineDynamicImports: getOption('inlineDynamicImports'),
  22792. interop: getOption('interop'),
  22793. intro: getOption('intro'),
  22794. manualChunks: getOption('manualChunks'),
  22795. minifyInternalExports: getOption('minifyInternalExports'),
  22796. name: getOption('name'),
  22797. noConflict: getOption('noConflict'),
  22798. onlyExplicitManualChunks: getOption('onlyExplicitManualChunks'),
  22799. outro: getOption('outro'),
  22800. paths: getOption('paths'),
  22801. plugins: await normalizePluginOption(config.plugins),
  22802. preserveModules: getOption('preserveModules'),
  22803. preserveModulesRoot: getOption('preserveModulesRoot'),
  22804. reexportProtoFromExternal: getOption('reexportProtoFromExternal'),
  22805. sanitizeFileName: getOption('sanitizeFileName'),
  22806. sourcemap: getOption('sourcemap'),
  22807. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  22808. sourcemapDebugIds: getOption('sourcemapDebugIds'),
  22809. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  22810. sourcemapFile: getOption('sourcemapFile'),
  22811. sourcemapFileNames: getOption('sourcemapFileNames'),
  22812. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  22813. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  22814. strict: getOption('strict'),
  22815. systemNullSetters: getOption('systemNullSetters'),
  22816. validate: getOption('validate'),
  22817. virtualDirname: getOption('virtualDirname')
  22818. };
  22819. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  22820. return outputOptions;
  22821. }
  22822. let fsEvents;
  22823. let fsEventsImportError;
  22824. async function loadFsEvents() {
  22825. try {
  22826. ({ default: fsEvents } = await import('fsevents'));
  22827. }
  22828. catch (error) {
  22829. fsEventsImportError = error;
  22830. }
  22831. }
  22832. // A call to this function will be injected into the chokidar code
  22833. function getFsEvents() {
  22834. if (fsEventsImportError)
  22835. throw fsEventsImportError;
  22836. return fsEvents;
  22837. }
  22838. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  22839. __proto__: null,
  22840. getFsEvents,
  22841. loadFsEvents
  22842. }, Symbol.toStringTag, { value: 'Module' });
  22843. class WatchEmitter {
  22844. constructor() {
  22845. this.currentHandlers = Object.create(null);
  22846. this.persistentHandlers = Object.create(null);
  22847. }
  22848. // Will be overwritten by Rollup
  22849. async close() { }
  22850. emit(event, ...parameters) {
  22851. return Promise.all([...this.getCurrentHandlers(event), ...this.getPersistentHandlers(event)].map(handler => handler(...parameters)));
  22852. }
  22853. off(event, listener) {
  22854. const listeners = this.persistentHandlers[event];
  22855. if (listeners) {
  22856. // A hack stolen from "mitt": ">>> 0" does not change numbers >= 0, but -1
  22857. // (which would remove the last array element if used unchanged) is turned
  22858. // into max_int, which is outside the array and does not change anything.
  22859. listeners.splice(listeners.indexOf(listener) >>> 0, 1);
  22860. }
  22861. return this;
  22862. }
  22863. on(event, listener) {
  22864. this.getPersistentHandlers(event).push(listener);
  22865. return this;
  22866. }
  22867. onCurrentRun(event, listener) {
  22868. this.getCurrentHandlers(event).push(listener);
  22869. return this;
  22870. }
  22871. once(event, listener) {
  22872. const selfRemovingListener = (...parameters) => {
  22873. this.off(event, selfRemovingListener);
  22874. return listener(...parameters);
  22875. };
  22876. this.on(event, selfRemovingListener);
  22877. return this;
  22878. }
  22879. removeAllListeners() {
  22880. this.removeListenersForCurrentRun();
  22881. this.persistentHandlers = Object.create(null);
  22882. return this;
  22883. }
  22884. removeListenersForCurrentRun() {
  22885. this.currentHandlers = Object.create(null);
  22886. return this;
  22887. }
  22888. getCurrentHandlers(event) {
  22889. return this.currentHandlers[event] || (this.currentHandlers[event] = []);
  22890. }
  22891. getPersistentHandlers(event) {
  22892. return this.persistentHandlers[event] || (this.persistentHandlers[event] = []);
  22893. }
  22894. }
  22895. function watch(configs) {
  22896. const emitter = new WatchEmitter();
  22897. watchInternal(configs, emitter).catch(error => {
  22898. handleError(error);
  22899. });
  22900. return emitter;
  22901. }
  22902. function ensureTrailingSlash(path) {
  22903. if (path[path.length - 1] !== '/') {
  22904. return `${path}/`;
  22905. }
  22906. return path;
  22907. }
  22908. function checkWatchConfig(config) {
  22909. for (const item of config) {
  22910. if (typeof item.watch !== 'boolean' && item.watch?.allowInputInsideOutputPath) {
  22911. break;
  22912. }
  22913. if (item.input && item.output) {
  22914. const input = typeof item.input === 'string' ? ensureArray(item.input) : item.input;
  22915. const outputs = ensureArray(item.output);
  22916. for (const index in input) {
  22917. const inputPath = input[index];
  22918. if (typeof inputPath !== 'string') {
  22919. continue;
  22920. }
  22921. const outputWithInputAsSubPath = outputs.find(({ dir }) => dir && ensureTrailingSlash(inputPath).startsWith(ensureTrailingSlash(dir)));
  22922. if (outputWithInputAsSubPath) {
  22923. error(logInvalidOption('watch', URL_WATCH, `the input "${inputPath}" is a subpath of the output "${outputWithInputAsSubPath.dir}"`));
  22924. }
  22925. }
  22926. }
  22927. }
  22928. }
  22929. async function watchInternal(configs, emitter) {
  22930. const optionsList = await Promise.all(ensureArray(configs).map(config => mergeOptions(config, true)));
  22931. const watchOptionsList = optionsList.filter(config => config.watch !== false);
  22932. if (watchOptionsList.length === 0) {
  22933. return error(logInvalidOption('watch', URL_WATCH, 'there must be at least one config where "watch" is not set to "false"'));
  22934. }
  22935. checkWatchConfig(watchOptionsList);
  22936. await loadFsEvents();
  22937. const { Watcher } = await import('./watch.js');
  22938. new Watcher(watchOptionsList, emitter);
  22939. }
  22940. export { createFilter$1 as createFilter, defineConfig, fseventsImporter, getAugmentedNamespace, getDefaultExportFromCjs, rollup, rollupInternal, version, watch };