node-entry.js 894 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724
  1. /*
  2. @license
  3. Rollup.js v4.41.0
  4. Sun, 18 May 2025 05:33:01 GMT - commit 0928185cd544907dab472754634ddf988452aae6
  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, 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 { lstat, realpath, readdir, readFile, mkdir, writeFile } from 'node:fs/promises';
  15. var version = "4.41.0";
  16. const comma = ','.charCodeAt(0);
  17. const semicolon = ';'.charCodeAt(0);
  18. const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  19. const intToChar = new Uint8Array(64); // 64 possible chars.
  20. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  21. for (let i = 0; i < chars$1.length; i++) {
  22. const c = chars$1.charCodeAt(i);
  23. intToChar[i] = c;
  24. charToInt[c] = i;
  25. }
  26. function decodeInteger(reader, relative) {
  27. let value = 0;
  28. let shift = 0;
  29. let integer = 0;
  30. do {
  31. const c = reader.next();
  32. integer = charToInt[c];
  33. value |= (integer & 31) << shift;
  34. shift += 5;
  35. } while (integer & 32);
  36. const shouldNegate = value & 1;
  37. value >>>= 1;
  38. if (shouldNegate) {
  39. value = -2147483648 | -value;
  40. }
  41. return relative + value;
  42. }
  43. function encodeInteger(builder, num, relative) {
  44. let delta = num - relative;
  45. delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
  46. do {
  47. let clamped = delta & 0b011111;
  48. delta >>>= 5;
  49. if (delta > 0)
  50. clamped |= 0b100000;
  51. builder.write(intToChar[clamped]);
  52. } while (delta > 0);
  53. return num;
  54. }
  55. function hasMoreVlq(reader, max) {
  56. if (reader.pos >= max)
  57. return false;
  58. return reader.peek() !== comma;
  59. }
  60. const bufLength = 1024 * 16;
  61. // Provide a fallback for older environments.
  62. const td = typeof TextDecoder !== 'undefined'
  63. ? /* #__PURE__ */ new TextDecoder()
  64. : typeof Buffer !== 'undefined'
  65. ? {
  66. decode(buf) {
  67. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  68. return out.toString();
  69. },
  70. }
  71. : {
  72. decode(buf) {
  73. let out = '';
  74. for (let i = 0; i < buf.length; i++) {
  75. out += String.fromCharCode(buf[i]);
  76. }
  77. return out;
  78. },
  79. };
  80. class StringWriter {
  81. constructor() {
  82. this.pos = 0;
  83. this.out = '';
  84. this.buffer = new Uint8Array(bufLength);
  85. }
  86. write(v) {
  87. const { buffer } = this;
  88. buffer[this.pos++] = v;
  89. if (this.pos === bufLength) {
  90. this.out += td.decode(buffer);
  91. this.pos = 0;
  92. }
  93. }
  94. flush() {
  95. const { buffer, out, pos } = this;
  96. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  97. }
  98. }
  99. class StringReader {
  100. constructor(buffer) {
  101. this.pos = 0;
  102. this.buffer = buffer;
  103. }
  104. next() {
  105. return this.buffer.charCodeAt(this.pos++);
  106. }
  107. peek() {
  108. return this.buffer.charCodeAt(this.pos);
  109. }
  110. indexOf(char) {
  111. const { buffer, pos } = this;
  112. const idx = buffer.indexOf(char, pos);
  113. return idx === -1 ? buffer.length : idx;
  114. }
  115. }
  116. function decode(mappings) {
  117. const { length } = mappings;
  118. const reader = new StringReader(mappings);
  119. const decoded = [];
  120. let genColumn = 0;
  121. let sourcesIndex = 0;
  122. let sourceLine = 0;
  123. let sourceColumn = 0;
  124. let namesIndex = 0;
  125. do {
  126. const semi = reader.indexOf(';');
  127. const line = [];
  128. let sorted = true;
  129. let lastCol = 0;
  130. genColumn = 0;
  131. while (reader.pos < semi) {
  132. let seg;
  133. genColumn = decodeInteger(reader, genColumn);
  134. if (genColumn < lastCol)
  135. sorted = false;
  136. lastCol = genColumn;
  137. if (hasMoreVlq(reader, semi)) {
  138. sourcesIndex = decodeInteger(reader, sourcesIndex);
  139. sourceLine = decodeInteger(reader, sourceLine);
  140. sourceColumn = decodeInteger(reader, sourceColumn);
  141. if (hasMoreVlq(reader, semi)) {
  142. namesIndex = decodeInteger(reader, namesIndex);
  143. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
  144. }
  145. else {
  146. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
  147. }
  148. }
  149. else {
  150. seg = [genColumn];
  151. }
  152. line.push(seg);
  153. reader.pos++;
  154. }
  155. if (!sorted)
  156. sort(line);
  157. decoded.push(line);
  158. reader.pos = semi + 1;
  159. } while (reader.pos <= length);
  160. return decoded;
  161. }
  162. function sort(line) {
  163. line.sort(sortComparator);
  164. }
  165. function sortComparator(a, b) {
  166. return a[0] - b[0];
  167. }
  168. function encode(decoded) {
  169. const writer = new StringWriter();
  170. let sourcesIndex = 0;
  171. let sourceLine = 0;
  172. let sourceColumn = 0;
  173. let namesIndex = 0;
  174. for (let i = 0; i < decoded.length; i++) {
  175. const line = decoded[i];
  176. if (i > 0)
  177. writer.write(semicolon);
  178. if (line.length === 0)
  179. continue;
  180. let genColumn = 0;
  181. for (let j = 0; j < line.length; j++) {
  182. const segment = line[j];
  183. if (j > 0)
  184. writer.write(comma);
  185. genColumn = encodeInteger(writer, segment[0], genColumn);
  186. if (segment.length === 1)
  187. continue;
  188. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  189. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  190. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  191. if (segment.length === 4)
  192. continue;
  193. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  194. }
  195. }
  196. return writer.flush();
  197. }
  198. class BitSet {
  199. constructor(arg) {
  200. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  201. }
  202. add(n) {
  203. this.bits[n >> 5] |= 1 << (n & 31);
  204. }
  205. has(n) {
  206. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  207. }
  208. }
  209. let Chunk$1 = class Chunk {
  210. constructor(start, end, content) {
  211. this.start = start;
  212. this.end = end;
  213. this.original = content;
  214. this.intro = '';
  215. this.outro = '';
  216. this.content = content;
  217. this.storeName = false;
  218. this.edited = false;
  219. {
  220. this.previous = null;
  221. this.next = null;
  222. }
  223. }
  224. appendLeft(content) {
  225. this.outro += content;
  226. }
  227. appendRight(content) {
  228. this.intro = this.intro + content;
  229. }
  230. clone() {
  231. const chunk = new Chunk(this.start, this.end, this.original);
  232. chunk.intro = this.intro;
  233. chunk.outro = this.outro;
  234. chunk.content = this.content;
  235. chunk.storeName = this.storeName;
  236. chunk.edited = this.edited;
  237. return chunk;
  238. }
  239. contains(index) {
  240. return this.start < index && index < this.end;
  241. }
  242. eachNext(fn) {
  243. let chunk = this;
  244. while (chunk) {
  245. fn(chunk);
  246. chunk = chunk.next;
  247. }
  248. }
  249. eachPrevious(fn) {
  250. let chunk = this;
  251. while (chunk) {
  252. fn(chunk);
  253. chunk = chunk.previous;
  254. }
  255. }
  256. edit(content, storeName, contentOnly) {
  257. this.content = content;
  258. if (!contentOnly) {
  259. this.intro = '';
  260. this.outro = '';
  261. }
  262. this.storeName = storeName;
  263. this.edited = true;
  264. return this;
  265. }
  266. prependLeft(content) {
  267. this.outro = content + this.outro;
  268. }
  269. prependRight(content) {
  270. this.intro = content + this.intro;
  271. }
  272. reset() {
  273. this.intro = '';
  274. this.outro = '';
  275. if (this.edited) {
  276. this.content = this.original;
  277. this.storeName = false;
  278. this.edited = false;
  279. }
  280. }
  281. split(index) {
  282. const sliceIndex = index - this.start;
  283. const originalBefore = this.original.slice(0, sliceIndex);
  284. const originalAfter = this.original.slice(sliceIndex);
  285. this.original = originalBefore;
  286. const newChunk = new Chunk(index, this.end, originalAfter);
  287. newChunk.outro = this.outro;
  288. this.outro = '';
  289. this.end = index;
  290. if (this.edited) {
  291. // after split we should save the edit content record into the correct chunk
  292. // to make sure sourcemap correct
  293. // For example:
  294. // ' test'.trim()
  295. // split -> ' ' + 'test'
  296. // ✔️ edit -> '' + 'test'
  297. // ✖️ edit -> 'test' + ''
  298. // TODO is this block necessary?...
  299. newChunk.edit('', false);
  300. this.content = '';
  301. } else {
  302. this.content = originalBefore;
  303. }
  304. newChunk.next = this.next;
  305. if (newChunk.next) newChunk.next.previous = newChunk;
  306. newChunk.previous = this;
  307. this.next = newChunk;
  308. return newChunk;
  309. }
  310. toString() {
  311. return this.intro + this.content + this.outro;
  312. }
  313. trimEnd(rx) {
  314. this.outro = this.outro.replace(rx, '');
  315. if (this.outro.length) return true;
  316. const trimmed = this.content.replace(rx, '');
  317. if (trimmed.length) {
  318. if (trimmed !== this.content) {
  319. this.split(this.start + trimmed.length).edit('', undefined, true);
  320. if (this.edited) {
  321. // save the change, if it has been edited
  322. this.edit(trimmed, this.storeName, true);
  323. }
  324. }
  325. return true;
  326. } else {
  327. this.edit('', undefined, true);
  328. this.intro = this.intro.replace(rx, '');
  329. if (this.intro.length) return true;
  330. }
  331. }
  332. trimStart(rx) {
  333. this.intro = this.intro.replace(rx, '');
  334. if (this.intro.length) return true;
  335. const trimmed = this.content.replace(rx, '');
  336. if (trimmed.length) {
  337. if (trimmed !== this.content) {
  338. const newChunk = this.split(this.end - trimmed.length);
  339. if (this.edited) {
  340. // save the change, if it has been edited
  341. newChunk.edit(trimmed, this.storeName, true);
  342. }
  343. this.edit('', undefined, true);
  344. }
  345. return true;
  346. } else {
  347. this.edit('', undefined, true);
  348. this.outro = this.outro.replace(rx, '');
  349. if (this.outro.length) return true;
  350. }
  351. }
  352. };
  353. function getBtoa() {
  354. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  355. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  356. } else if (typeof Buffer === 'function') {
  357. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  358. } else {
  359. return () => {
  360. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  361. };
  362. }
  363. }
  364. const btoa = /*#__PURE__*/ getBtoa();
  365. class SourceMap {
  366. constructor(properties) {
  367. this.version = 3;
  368. this.file = properties.file;
  369. this.sources = properties.sources;
  370. this.sourcesContent = properties.sourcesContent;
  371. this.names = properties.names;
  372. this.mappings = encode(properties.mappings);
  373. if (typeof properties.x_google_ignoreList !== 'undefined') {
  374. this.x_google_ignoreList = properties.x_google_ignoreList;
  375. }
  376. if (typeof properties.debugId !== 'undefined') {
  377. this.debugId = properties.debugId;
  378. }
  379. }
  380. toString() {
  381. return JSON.stringify(this);
  382. }
  383. toUrl() {
  384. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  385. }
  386. }
  387. function guessIndent(code) {
  388. const lines = code.split('\n');
  389. const tabbed = lines.filter((line) => /^\t+/.test(line));
  390. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  391. if (tabbed.length === 0 && spaced.length === 0) {
  392. return null;
  393. }
  394. // More lines tabbed than spaced? Assume tabs, and
  395. // default to tabs in the case of a tie (or nothing
  396. // to go on)
  397. if (tabbed.length >= spaced.length) {
  398. return '\t';
  399. }
  400. // Otherwise, we need to guess the multiple
  401. const min = spaced.reduce((previous, current) => {
  402. const numSpaces = /^ +/.exec(current)[0].length;
  403. return Math.min(numSpaces, previous);
  404. }, Infinity);
  405. return new Array(min + 1).join(' ');
  406. }
  407. function getRelativePath(from, to) {
  408. const fromParts = from.split(/[/\\]/);
  409. const toParts = to.split(/[/\\]/);
  410. fromParts.pop(); // get dirname
  411. while (fromParts[0] === toParts[0]) {
  412. fromParts.shift();
  413. toParts.shift();
  414. }
  415. if (fromParts.length) {
  416. let i = fromParts.length;
  417. while (i--) fromParts[i] = '..';
  418. }
  419. return fromParts.concat(toParts).join('/');
  420. }
  421. const toString = Object.prototype.toString;
  422. function isObject(thing) {
  423. return toString.call(thing) === '[object Object]';
  424. }
  425. function getLocator(source) {
  426. const originalLines = source.split('\n');
  427. const lineOffsets = [];
  428. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  429. lineOffsets.push(pos);
  430. pos += originalLines[i].length + 1;
  431. }
  432. return function locate(index) {
  433. let i = 0;
  434. let j = lineOffsets.length;
  435. while (i < j) {
  436. const m = (i + j) >> 1;
  437. if (index < lineOffsets[m]) {
  438. j = m;
  439. } else {
  440. i = m + 1;
  441. }
  442. }
  443. const line = i - 1;
  444. const column = index - lineOffsets[line];
  445. return { line, column };
  446. };
  447. }
  448. const wordRegex = /\w/;
  449. class Mappings {
  450. constructor(hires) {
  451. this.hires = hires;
  452. this.generatedCodeLine = 0;
  453. this.generatedCodeColumn = 0;
  454. this.raw = [];
  455. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  456. this.pending = null;
  457. }
  458. addEdit(sourceIndex, content, loc, nameIndex) {
  459. if (content.length) {
  460. const contentLengthMinusOne = content.length - 1;
  461. let contentLineEnd = content.indexOf('\n', 0);
  462. let previousContentLineEnd = -1;
  463. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  464. // else code afterwards would fill one line too many
  465. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  466. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  467. if (nameIndex >= 0) {
  468. segment.push(nameIndex);
  469. }
  470. this.rawSegments.push(segment);
  471. this.generatedCodeLine += 1;
  472. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  473. this.generatedCodeColumn = 0;
  474. previousContentLineEnd = contentLineEnd;
  475. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  476. }
  477. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  478. if (nameIndex >= 0) {
  479. segment.push(nameIndex);
  480. }
  481. this.rawSegments.push(segment);
  482. this.advance(content.slice(previousContentLineEnd + 1));
  483. } else if (this.pending) {
  484. this.rawSegments.push(this.pending);
  485. this.advance(content);
  486. }
  487. this.pending = null;
  488. }
  489. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  490. let originalCharIndex = chunk.start;
  491. let first = true;
  492. // when iterating each char, check if it's in a word boundary
  493. let charInHiresBoundary = false;
  494. while (originalCharIndex < chunk.end) {
  495. if (original[originalCharIndex] === '\n') {
  496. loc.line += 1;
  497. loc.column = 0;
  498. this.generatedCodeLine += 1;
  499. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  500. this.generatedCodeColumn = 0;
  501. first = true;
  502. charInHiresBoundary = false;
  503. } else {
  504. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  505. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  506. if (this.hires === 'boundary') {
  507. // in hires "boundary", group segments per word boundary than per char
  508. if (wordRegex.test(original[originalCharIndex])) {
  509. // for first char in the boundary found, start the boundary by pushing a segment
  510. if (!charInHiresBoundary) {
  511. this.rawSegments.push(segment);
  512. charInHiresBoundary = true;
  513. }
  514. } else {
  515. // for non-word char, end the boundary by pushing a segment
  516. this.rawSegments.push(segment);
  517. charInHiresBoundary = false;
  518. }
  519. } else {
  520. this.rawSegments.push(segment);
  521. }
  522. }
  523. loc.column += 1;
  524. this.generatedCodeColumn += 1;
  525. first = false;
  526. }
  527. originalCharIndex += 1;
  528. }
  529. this.pending = null;
  530. }
  531. advance(str) {
  532. if (!str) return;
  533. const lines = str.split('\n');
  534. if (lines.length > 1) {
  535. for (let i = 0; i < lines.length - 1; i++) {
  536. this.generatedCodeLine++;
  537. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  538. }
  539. this.generatedCodeColumn = 0;
  540. }
  541. this.generatedCodeColumn += lines[lines.length - 1].length;
  542. }
  543. }
  544. const n = '\n';
  545. const warned = {
  546. insertLeft: false,
  547. insertRight: false,
  548. storeName: false,
  549. };
  550. class MagicString {
  551. constructor(string, options = {}) {
  552. const chunk = new Chunk$1(0, string.length, string);
  553. Object.defineProperties(this, {
  554. original: { writable: true, value: string },
  555. outro: { writable: true, value: '' },
  556. intro: { writable: true, value: '' },
  557. firstChunk: { writable: true, value: chunk },
  558. lastChunk: { writable: true, value: chunk },
  559. lastSearchedChunk: { writable: true, value: chunk },
  560. byStart: { writable: true, value: {} },
  561. byEnd: { writable: true, value: {} },
  562. filename: { writable: true, value: options.filename },
  563. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  564. sourcemapLocations: { writable: true, value: new BitSet() },
  565. storedNames: { writable: true, value: {} },
  566. indentStr: { writable: true, value: undefined },
  567. ignoreList: { writable: true, value: options.ignoreList },
  568. offset: { writable: true, value: options.offset || 0 },
  569. });
  570. this.byStart[0] = chunk;
  571. this.byEnd[string.length] = chunk;
  572. }
  573. addSourcemapLocation(char) {
  574. this.sourcemapLocations.add(char);
  575. }
  576. append(content) {
  577. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  578. this.outro += content;
  579. return this;
  580. }
  581. appendLeft(index, content) {
  582. index = index + this.offset;
  583. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  584. this._split(index);
  585. const chunk = this.byEnd[index];
  586. if (chunk) {
  587. chunk.appendLeft(content);
  588. } else {
  589. this.intro += content;
  590. }
  591. return this;
  592. }
  593. appendRight(index, content) {
  594. index = index + this.offset;
  595. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  596. this._split(index);
  597. const chunk = this.byStart[index];
  598. if (chunk) {
  599. chunk.appendRight(content);
  600. } else {
  601. this.outro += content;
  602. }
  603. return this;
  604. }
  605. clone() {
  606. const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
  607. let originalChunk = this.firstChunk;
  608. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  609. while (originalChunk) {
  610. cloned.byStart[clonedChunk.start] = clonedChunk;
  611. cloned.byEnd[clonedChunk.end] = clonedChunk;
  612. const nextOriginalChunk = originalChunk.next;
  613. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  614. if (nextClonedChunk) {
  615. clonedChunk.next = nextClonedChunk;
  616. nextClonedChunk.previous = clonedChunk;
  617. clonedChunk = nextClonedChunk;
  618. }
  619. originalChunk = nextOriginalChunk;
  620. }
  621. cloned.lastChunk = clonedChunk;
  622. if (this.indentExclusionRanges) {
  623. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  624. }
  625. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  626. cloned.intro = this.intro;
  627. cloned.outro = this.outro;
  628. return cloned;
  629. }
  630. generateDecodedMap(options) {
  631. options = options || {};
  632. const sourceIndex = 0;
  633. const names = Object.keys(this.storedNames);
  634. const mappings = new Mappings(options.hires);
  635. const locate = getLocator(this.original);
  636. if (this.intro) {
  637. mappings.advance(this.intro);
  638. }
  639. this.firstChunk.eachNext((chunk) => {
  640. const loc = locate(chunk.start);
  641. if (chunk.intro.length) mappings.advance(chunk.intro);
  642. if (chunk.edited) {
  643. mappings.addEdit(
  644. sourceIndex,
  645. chunk.content,
  646. loc,
  647. chunk.storeName ? names.indexOf(chunk.original) : -1,
  648. );
  649. } else {
  650. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  651. }
  652. if (chunk.outro.length) mappings.advance(chunk.outro);
  653. });
  654. return {
  655. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  656. sources: [
  657. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  658. ],
  659. sourcesContent: options.includeContent ? [this.original] : undefined,
  660. names,
  661. mappings: mappings.raw,
  662. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  663. };
  664. }
  665. generateMap(options) {
  666. return new SourceMap(this.generateDecodedMap(options));
  667. }
  668. _ensureindentStr() {
  669. if (this.indentStr === undefined) {
  670. this.indentStr = guessIndent(this.original);
  671. }
  672. }
  673. _getRawIndentString() {
  674. this._ensureindentStr();
  675. return this.indentStr;
  676. }
  677. getIndentString() {
  678. this._ensureindentStr();
  679. return this.indentStr === null ? '\t' : this.indentStr;
  680. }
  681. indent(indentStr, options) {
  682. const pattern = /^[^\r\n]/gm;
  683. if (isObject(indentStr)) {
  684. options = indentStr;
  685. indentStr = undefined;
  686. }
  687. if (indentStr === undefined) {
  688. this._ensureindentStr();
  689. indentStr = this.indentStr || '\t';
  690. }
  691. if (indentStr === '') return this; // noop
  692. options = options || {};
  693. // Process exclusion ranges
  694. const isExcluded = {};
  695. if (options.exclude) {
  696. const exclusions =
  697. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  698. exclusions.forEach((exclusion) => {
  699. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  700. isExcluded[i] = true;
  701. }
  702. });
  703. }
  704. let shouldIndentNextCharacter = options.indentStart !== false;
  705. const replacer = (match) => {
  706. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  707. shouldIndentNextCharacter = true;
  708. return match;
  709. };
  710. this.intro = this.intro.replace(pattern, replacer);
  711. let charIndex = 0;
  712. let chunk = this.firstChunk;
  713. while (chunk) {
  714. const end = chunk.end;
  715. if (chunk.edited) {
  716. if (!isExcluded[charIndex]) {
  717. chunk.content = chunk.content.replace(pattern, replacer);
  718. if (chunk.content.length) {
  719. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  720. }
  721. }
  722. } else {
  723. charIndex = chunk.start;
  724. while (charIndex < end) {
  725. if (!isExcluded[charIndex]) {
  726. const char = this.original[charIndex];
  727. if (char === '\n') {
  728. shouldIndentNextCharacter = true;
  729. } else if (char !== '\r' && shouldIndentNextCharacter) {
  730. shouldIndentNextCharacter = false;
  731. if (charIndex === chunk.start) {
  732. chunk.prependRight(indentStr);
  733. } else {
  734. this._splitChunk(chunk, charIndex);
  735. chunk = chunk.next;
  736. chunk.prependRight(indentStr);
  737. }
  738. }
  739. }
  740. charIndex += 1;
  741. }
  742. }
  743. charIndex = chunk.end;
  744. chunk = chunk.next;
  745. }
  746. this.outro = this.outro.replace(pattern, replacer);
  747. return this;
  748. }
  749. insert() {
  750. throw new Error(
  751. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  752. );
  753. }
  754. insertLeft(index, content) {
  755. if (!warned.insertLeft) {
  756. console.warn(
  757. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  758. );
  759. warned.insertLeft = true;
  760. }
  761. return this.appendLeft(index, content);
  762. }
  763. insertRight(index, content) {
  764. if (!warned.insertRight) {
  765. console.warn(
  766. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  767. );
  768. warned.insertRight = true;
  769. }
  770. return this.prependRight(index, content);
  771. }
  772. move(start, end, index) {
  773. start = start + this.offset;
  774. end = end + this.offset;
  775. index = index + this.offset;
  776. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  777. this._split(start);
  778. this._split(end);
  779. this._split(index);
  780. const first = this.byStart[start];
  781. const last = this.byEnd[end];
  782. const oldLeft = first.previous;
  783. const oldRight = last.next;
  784. const newRight = this.byStart[index];
  785. if (!newRight && last === this.lastChunk) return this;
  786. const newLeft = newRight ? newRight.previous : this.lastChunk;
  787. if (oldLeft) oldLeft.next = oldRight;
  788. if (oldRight) oldRight.previous = oldLeft;
  789. if (newLeft) newLeft.next = first;
  790. if (newRight) newRight.previous = last;
  791. if (!first.previous) this.firstChunk = last.next;
  792. if (!last.next) {
  793. this.lastChunk = first.previous;
  794. this.lastChunk.next = null;
  795. }
  796. first.previous = newLeft;
  797. last.next = newRight || null;
  798. if (!newLeft) this.firstChunk = first;
  799. if (!newRight) this.lastChunk = last;
  800. return this;
  801. }
  802. overwrite(start, end, content, options) {
  803. options = options || {};
  804. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  805. }
  806. update(start, end, content, options) {
  807. start = start + this.offset;
  808. end = end + this.offset;
  809. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  810. if (this.original.length !== 0) {
  811. while (start < 0) start += this.original.length;
  812. while (end < 0) end += this.original.length;
  813. }
  814. if (end > this.original.length) throw new Error('end is out of bounds');
  815. if (start === end)
  816. throw new Error(
  817. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  818. );
  819. this._split(start);
  820. this._split(end);
  821. if (options === true) {
  822. if (!warned.storeName) {
  823. console.warn(
  824. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  825. );
  826. warned.storeName = true;
  827. }
  828. options = { storeName: true };
  829. }
  830. const storeName = options !== undefined ? options.storeName : false;
  831. const overwrite = options !== undefined ? options.overwrite : false;
  832. if (storeName) {
  833. const original = this.original.slice(start, end);
  834. Object.defineProperty(this.storedNames, original, {
  835. writable: true,
  836. value: true,
  837. enumerable: true,
  838. });
  839. }
  840. const first = this.byStart[start];
  841. const last = this.byEnd[end];
  842. if (first) {
  843. let chunk = first;
  844. while (chunk !== last) {
  845. if (chunk.next !== this.byStart[chunk.end]) {
  846. throw new Error('Cannot overwrite across a split point');
  847. }
  848. chunk = chunk.next;
  849. chunk.edit('', false);
  850. }
  851. first.edit(content, storeName, !overwrite);
  852. } else {
  853. // must be inserting at the end
  854. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  855. // TODO last chunk in the array may not be the last chunk, if it's moved...
  856. last.next = newChunk;
  857. newChunk.previous = last;
  858. }
  859. return this;
  860. }
  861. prepend(content) {
  862. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  863. this.intro = content + this.intro;
  864. return this;
  865. }
  866. prependLeft(index, content) {
  867. index = index + this.offset;
  868. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  869. this._split(index);
  870. const chunk = this.byEnd[index];
  871. if (chunk) {
  872. chunk.prependLeft(content);
  873. } else {
  874. this.intro = content + this.intro;
  875. }
  876. return this;
  877. }
  878. prependRight(index, content) {
  879. index = index + this.offset;
  880. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  881. this._split(index);
  882. const chunk = this.byStart[index];
  883. if (chunk) {
  884. chunk.prependRight(content);
  885. } else {
  886. this.outro = content + this.outro;
  887. }
  888. return this;
  889. }
  890. remove(start, end) {
  891. start = start + this.offset;
  892. end = end + this.offset;
  893. if (this.original.length !== 0) {
  894. while (start < 0) start += this.original.length;
  895. while (end < 0) end += this.original.length;
  896. }
  897. if (start === end) return this;
  898. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  899. if (start > end) throw new Error('end must be greater than start');
  900. this._split(start);
  901. this._split(end);
  902. let chunk = this.byStart[start];
  903. while (chunk) {
  904. chunk.intro = '';
  905. chunk.outro = '';
  906. chunk.edit('');
  907. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  908. }
  909. return this;
  910. }
  911. reset(start, end) {
  912. start = start + this.offset;
  913. end = end + this.offset;
  914. if (this.original.length !== 0) {
  915. while (start < 0) start += this.original.length;
  916. while (end < 0) end += this.original.length;
  917. }
  918. if (start === end) return this;
  919. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  920. if (start > end) throw new Error('end must be greater than start');
  921. this._split(start);
  922. this._split(end);
  923. let chunk = this.byStart[start];
  924. while (chunk) {
  925. chunk.reset();
  926. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  927. }
  928. return this;
  929. }
  930. lastChar() {
  931. if (this.outro.length) return this.outro[this.outro.length - 1];
  932. let chunk = this.lastChunk;
  933. do {
  934. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  935. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  936. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  937. } while ((chunk = chunk.previous));
  938. if (this.intro.length) return this.intro[this.intro.length - 1];
  939. return '';
  940. }
  941. lastLine() {
  942. let lineIndex = this.outro.lastIndexOf(n);
  943. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  944. let lineStr = this.outro;
  945. let chunk = this.lastChunk;
  946. do {
  947. if (chunk.outro.length > 0) {
  948. lineIndex = chunk.outro.lastIndexOf(n);
  949. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  950. lineStr = chunk.outro + lineStr;
  951. }
  952. if (chunk.content.length > 0) {
  953. lineIndex = chunk.content.lastIndexOf(n);
  954. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  955. lineStr = chunk.content + lineStr;
  956. }
  957. if (chunk.intro.length > 0) {
  958. lineIndex = chunk.intro.lastIndexOf(n);
  959. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  960. lineStr = chunk.intro + lineStr;
  961. }
  962. } while ((chunk = chunk.previous));
  963. lineIndex = this.intro.lastIndexOf(n);
  964. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  965. return this.intro + lineStr;
  966. }
  967. slice(start = 0, end = this.original.length - this.offset) {
  968. start = start + this.offset;
  969. end = end + this.offset;
  970. if (this.original.length !== 0) {
  971. while (start < 0) start += this.original.length;
  972. while (end < 0) end += this.original.length;
  973. }
  974. let result = '';
  975. // find start chunk
  976. let chunk = this.firstChunk;
  977. while (chunk && (chunk.start > start || chunk.end <= start)) {
  978. // found end chunk before start
  979. if (chunk.start < end && chunk.end >= end) {
  980. return result;
  981. }
  982. chunk = chunk.next;
  983. }
  984. if (chunk && chunk.edited && chunk.start !== start)
  985. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  986. const startChunk = chunk;
  987. while (chunk) {
  988. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  989. result += chunk.intro;
  990. }
  991. const containsEnd = chunk.start < end && chunk.end >= end;
  992. if (containsEnd && chunk.edited && chunk.end !== end)
  993. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  994. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  995. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  996. result += chunk.content.slice(sliceStart, sliceEnd);
  997. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  998. result += chunk.outro;
  999. }
  1000. if (containsEnd) {
  1001. break;
  1002. }
  1003. chunk = chunk.next;
  1004. }
  1005. return result;
  1006. }
  1007. // TODO deprecate this? not really very useful
  1008. snip(start, end) {
  1009. const clone = this.clone();
  1010. clone.remove(0, start);
  1011. clone.remove(end, clone.original.length);
  1012. return clone;
  1013. }
  1014. _split(index) {
  1015. if (this.byStart[index] || this.byEnd[index]) return;
  1016. let chunk = this.lastSearchedChunk;
  1017. const searchForward = index > chunk.end;
  1018. while (chunk) {
  1019. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  1020. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  1021. }
  1022. }
  1023. _splitChunk(chunk, index) {
  1024. if (chunk.edited && chunk.content.length) {
  1025. // zero-length edited chunks are a special case (overlapping replacements)
  1026. const loc = getLocator(this.original)(index);
  1027. throw new Error(
  1028. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  1029. );
  1030. }
  1031. const newChunk = chunk.split(index);
  1032. this.byEnd[index] = chunk;
  1033. this.byStart[index] = newChunk;
  1034. this.byEnd[newChunk.end] = newChunk;
  1035. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  1036. this.lastSearchedChunk = chunk;
  1037. return true;
  1038. }
  1039. toString() {
  1040. let str = this.intro;
  1041. let chunk = this.firstChunk;
  1042. while (chunk) {
  1043. str += chunk.toString();
  1044. chunk = chunk.next;
  1045. }
  1046. return str + this.outro;
  1047. }
  1048. isEmpty() {
  1049. let chunk = this.firstChunk;
  1050. do {
  1051. if (
  1052. (chunk.intro.length && chunk.intro.trim()) ||
  1053. (chunk.content.length && chunk.content.trim()) ||
  1054. (chunk.outro.length && chunk.outro.trim())
  1055. )
  1056. return false;
  1057. } while ((chunk = chunk.next));
  1058. return true;
  1059. }
  1060. length() {
  1061. let chunk = this.firstChunk;
  1062. let length = 0;
  1063. do {
  1064. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  1065. } while ((chunk = chunk.next));
  1066. return length;
  1067. }
  1068. trimLines() {
  1069. return this.trim('[\\r\\n]');
  1070. }
  1071. trim(charType) {
  1072. return this.trimStart(charType).trimEnd(charType);
  1073. }
  1074. trimEndAborted(charType) {
  1075. const rx = new RegExp((charType || '\\s') + '+$');
  1076. this.outro = this.outro.replace(rx, '');
  1077. if (this.outro.length) return true;
  1078. let chunk = this.lastChunk;
  1079. do {
  1080. const end = chunk.end;
  1081. const aborted = chunk.trimEnd(rx);
  1082. // if chunk was trimmed, we have a new lastChunk
  1083. if (chunk.end !== end) {
  1084. if (this.lastChunk === chunk) {
  1085. this.lastChunk = chunk.next;
  1086. }
  1087. this.byEnd[chunk.end] = chunk;
  1088. this.byStart[chunk.next.start] = chunk.next;
  1089. this.byEnd[chunk.next.end] = chunk.next;
  1090. }
  1091. if (aborted) return true;
  1092. chunk = chunk.previous;
  1093. } while (chunk);
  1094. return false;
  1095. }
  1096. trimEnd(charType) {
  1097. this.trimEndAborted(charType);
  1098. return this;
  1099. }
  1100. trimStartAborted(charType) {
  1101. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1102. this.intro = this.intro.replace(rx, '');
  1103. if (this.intro.length) return true;
  1104. let chunk = this.firstChunk;
  1105. do {
  1106. const end = chunk.end;
  1107. const aborted = chunk.trimStart(rx);
  1108. if (chunk.end !== end) {
  1109. // special case...
  1110. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  1111. this.byEnd[chunk.end] = chunk;
  1112. this.byStart[chunk.next.start] = chunk.next;
  1113. this.byEnd[chunk.next.end] = chunk.next;
  1114. }
  1115. if (aborted) return true;
  1116. chunk = chunk.next;
  1117. } while (chunk);
  1118. return false;
  1119. }
  1120. trimStart(charType) {
  1121. this.trimStartAborted(charType);
  1122. return this;
  1123. }
  1124. hasChanged() {
  1125. return this.original !== this.toString();
  1126. }
  1127. _replaceRegexp(searchValue, replacement) {
  1128. function getReplacement(match, str) {
  1129. if (typeof replacement === 'string') {
  1130. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  1131. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  1132. if (i === '$') return '$';
  1133. if (i === '&') return match[0];
  1134. const num = +i;
  1135. if (num < match.length) return match[+i];
  1136. return `$${i}`;
  1137. });
  1138. } else {
  1139. return replacement(...match, match.index, str, match.groups);
  1140. }
  1141. }
  1142. function matchAll(re, str) {
  1143. let match;
  1144. const matches = [];
  1145. while ((match = re.exec(str))) {
  1146. matches.push(match);
  1147. }
  1148. return matches;
  1149. }
  1150. if (searchValue.global) {
  1151. const matches = matchAll(searchValue, this.original);
  1152. matches.forEach((match) => {
  1153. if (match.index != null) {
  1154. const replacement = getReplacement(match, this.original);
  1155. if (replacement !== match[0]) {
  1156. this.overwrite(match.index, match.index + match[0].length, replacement);
  1157. }
  1158. }
  1159. });
  1160. } else {
  1161. const match = this.original.match(searchValue);
  1162. if (match && match.index != null) {
  1163. const replacement = getReplacement(match, this.original);
  1164. if (replacement !== match[0]) {
  1165. this.overwrite(match.index, match.index + match[0].length, replacement);
  1166. }
  1167. }
  1168. }
  1169. return this;
  1170. }
  1171. _replaceString(string, replacement) {
  1172. const { original } = this;
  1173. const index = original.indexOf(string);
  1174. if (index !== -1) {
  1175. this.overwrite(index, index + string.length, replacement);
  1176. }
  1177. return this;
  1178. }
  1179. replace(searchValue, replacement) {
  1180. if (typeof searchValue === 'string') {
  1181. return this._replaceString(searchValue, replacement);
  1182. }
  1183. return this._replaceRegexp(searchValue, replacement);
  1184. }
  1185. _replaceAllString(string, replacement) {
  1186. const { original } = this;
  1187. const stringLength = string.length;
  1188. for (
  1189. let index = original.indexOf(string);
  1190. index !== -1;
  1191. index = original.indexOf(string, index + stringLength)
  1192. ) {
  1193. const previous = original.slice(index, index + stringLength);
  1194. if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
  1195. }
  1196. return this;
  1197. }
  1198. replaceAll(searchValue, replacement) {
  1199. if (typeof searchValue === 'string') {
  1200. return this._replaceAllString(searchValue, replacement);
  1201. }
  1202. if (!searchValue.global) {
  1203. throw new TypeError(
  1204. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  1205. );
  1206. }
  1207. return this._replaceRegexp(searchValue, replacement);
  1208. }
  1209. }
  1210. const hasOwnProp = Object.prototype.hasOwnProperty;
  1211. let Bundle$1 = class Bundle {
  1212. constructor(options = {}) {
  1213. this.intro = options.intro || '';
  1214. this.separator = options.separator !== undefined ? options.separator : '\n';
  1215. this.sources = [];
  1216. this.uniqueSources = [];
  1217. this.uniqueSourceIndexByFilename = {};
  1218. }
  1219. addSource(source) {
  1220. if (source instanceof MagicString) {
  1221. return this.addSource({
  1222. content: source,
  1223. filename: source.filename,
  1224. separator: this.separator,
  1225. });
  1226. }
  1227. if (!isObject(source) || !source.content) {
  1228. throw new Error(
  1229. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  1230. );
  1231. }
  1232. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1233. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1234. });
  1235. if (source.separator === undefined) {
  1236. // TODO there's a bunch of this sort of thing, needs cleaning up
  1237. source.separator = this.separator;
  1238. }
  1239. if (source.filename) {
  1240. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1241. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1242. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1243. } else {
  1244. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1245. if (source.content.original !== uniqueSource.content) {
  1246. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1247. }
  1248. }
  1249. }
  1250. this.sources.push(source);
  1251. return this;
  1252. }
  1253. append(str, options) {
  1254. this.addSource({
  1255. content: new MagicString(str),
  1256. separator: (options && options.separator) || '',
  1257. });
  1258. return this;
  1259. }
  1260. clone() {
  1261. const bundle = new Bundle({
  1262. intro: this.intro,
  1263. separator: this.separator,
  1264. });
  1265. this.sources.forEach((source) => {
  1266. bundle.addSource({
  1267. filename: source.filename,
  1268. content: source.content.clone(),
  1269. separator: source.separator,
  1270. });
  1271. });
  1272. return bundle;
  1273. }
  1274. generateDecodedMap(options = {}) {
  1275. const names = [];
  1276. let x_google_ignoreList = undefined;
  1277. this.sources.forEach((source) => {
  1278. Object.keys(source.content.storedNames).forEach((name) => {
  1279. if (!~names.indexOf(name)) names.push(name);
  1280. });
  1281. });
  1282. const mappings = new Mappings(options.hires);
  1283. if (this.intro) {
  1284. mappings.advance(this.intro);
  1285. }
  1286. this.sources.forEach((source, i) => {
  1287. if (i > 0) {
  1288. mappings.advance(this.separator);
  1289. }
  1290. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1291. const magicString = source.content;
  1292. const locate = getLocator(magicString.original);
  1293. if (magicString.intro) {
  1294. mappings.advance(magicString.intro);
  1295. }
  1296. magicString.firstChunk.eachNext((chunk) => {
  1297. const loc = locate(chunk.start);
  1298. if (chunk.intro.length) mappings.advance(chunk.intro);
  1299. if (source.filename) {
  1300. if (chunk.edited) {
  1301. mappings.addEdit(
  1302. sourceIndex,
  1303. chunk.content,
  1304. loc,
  1305. chunk.storeName ? names.indexOf(chunk.original) : -1,
  1306. );
  1307. } else {
  1308. mappings.addUneditedChunk(
  1309. sourceIndex,
  1310. chunk,
  1311. magicString.original,
  1312. loc,
  1313. magicString.sourcemapLocations,
  1314. );
  1315. }
  1316. } else {
  1317. mappings.advance(chunk.content);
  1318. }
  1319. if (chunk.outro.length) mappings.advance(chunk.outro);
  1320. });
  1321. if (magicString.outro) {
  1322. mappings.advance(magicString.outro);
  1323. }
  1324. if (source.ignoreList && sourceIndex !== -1) {
  1325. if (x_google_ignoreList === undefined) {
  1326. x_google_ignoreList = [];
  1327. }
  1328. x_google_ignoreList.push(sourceIndex);
  1329. }
  1330. });
  1331. return {
  1332. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  1333. sources: this.uniqueSources.map((source) => {
  1334. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1335. }),
  1336. sourcesContent: this.uniqueSources.map((source) => {
  1337. return options.includeContent ? source.content : null;
  1338. }),
  1339. names,
  1340. mappings: mappings.raw,
  1341. x_google_ignoreList,
  1342. };
  1343. }
  1344. generateMap(options) {
  1345. return new SourceMap(this.generateDecodedMap(options));
  1346. }
  1347. getIndentString() {
  1348. const indentStringCounts = {};
  1349. this.sources.forEach((source) => {
  1350. const indentStr = source.content._getRawIndentString();
  1351. if (indentStr === null) return;
  1352. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1353. indentStringCounts[indentStr] += 1;
  1354. });
  1355. return (
  1356. Object.keys(indentStringCounts).sort((a, b) => {
  1357. return indentStringCounts[a] - indentStringCounts[b];
  1358. })[0] || '\t'
  1359. );
  1360. }
  1361. indent(indentStr) {
  1362. if (!arguments.length) {
  1363. indentStr = this.getIndentString();
  1364. }
  1365. if (indentStr === '') return this; // noop
  1366. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1367. this.sources.forEach((source, i) => {
  1368. const separator = source.separator !== undefined ? source.separator : this.separator;
  1369. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1370. source.content.indent(indentStr, {
  1371. exclude: source.indentExclusionRanges,
  1372. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1373. });
  1374. trailingNewline = source.content.lastChar() === '\n';
  1375. });
  1376. if (this.intro) {
  1377. this.intro =
  1378. indentStr +
  1379. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1380. return index > 0 ? indentStr + match : match;
  1381. });
  1382. }
  1383. return this;
  1384. }
  1385. prepend(str) {
  1386. this.intro = str + this.intro;
  1387. return this;
  1388. }
  1389. toString() {
  1390. const body = this.sources
  1391. .map((source, i) => {
  1392. const separator = source.separator !== undefined ? source.separator : this.separator;
  1393. const str = (i > 0 ? separator : '') + source.content.toString();
  1394. return str;
  1395. })
  1396. .join('');
  1397. return this.intro + body;
  1398. }
  1399. isEmpty() {
  1400. if (this.intro.length && this.intro.trim()) return false;
  1401. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1402. return true;
  1403. }
  1404. length() {
  1405. return this.sources.reduce(
  1406. (length, source) => length + source.content.length(),
  1407. this.intro.length,
  1408. );
  1409. }
  1410. trimLines() {
  1411. return this.trim('[\\r\\n]');
  1412. }
  1413. trim(charType) {
  1414. return this.trimStart(charType).trimEnd(charType);
  1415. }
  1416. trimStart(charType) {
  1417. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1418. this.intro = this.intro.replace(rx, '');
  1419. if (!this.intro) {
  1420. let source;
  1421. let i = 0;
  1422. do {
  1423. source = this.sources[i++];
  1424. if (!source) {
  1425. break;
  1426. }
  1427. } while (!source.content.trimStartAborted(charType));
  1428. }
  1429. return this;
  1430. }
  1431. trimEnd(charType) {
  1432. const rx = new RegExp((charType || '\\s') + '+$');
  1433. let source;
  1434. let i = this.sources.length - 1;
  1435. do {
  1436. source = this.sources[i--];
  1437. if (!source) {
  1438. this.intro = this.intro.replace(rx, '');
  1439. break;
  1440. }
  1441. } while (!source.content.trimEndAborted(charType));
  1442. return this;
  1443. }
  1444. };
  1445. function treeshakeNode(node, code, start, end) {
  1446. code.remove(start, end);
  1447. node.removeAnnotations(code);
  1448. }
  1449. const NO_SEMICOLON = { isNoStatement: true };
  1450. // This assumes there are only white-space and comments between start and the string we are looking for
  1451. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  1452. let searchPos, charCodeAfterSlash;
  1453. searchPos = code.indexOf(searchString, start);
  1454. while (true) {
  1455. start = code.indexOf('/', start);
  1456. if (start === -1 || start >= searchPos)
  1457. return searchPos;
  1458. charCodeAfterSlash = code.charCodeAt(++start);
  1459. ++start;
  1460. // With our assumption, '/' always starts a comment. Determine comment type:
  1461. start =
  1462. charCodeAfterSlash === 47 /*"/"*/
  1463. ? code.indexOf('\n', start) + 1
  1464. : code.indexOf('*/', start) + 2;
  1465. if (start > searchPos) {
  1466. searchPos = code.indexOf(searchString, start);
  1467. }
  1468. }
  1469. }
  1470. const NON_WHITESPACE = /\S/g;
  1471. function findNonWhiteSpace(code, index) {
  1472. NON_WHITESPACE.lastIndex = index;
  1473. const result = NON_WHITESPACE.exec(code);
  1474. return result.index;
  1475. }
  1476. const WHITESPACE = /\s/;
  1477. function findLastWhiteSpaceReverse(code, start, end) {
  1478. while (true) {
  1479. if (start >= end) {
  1480. return end;
  1481. }
  1482. if (WHITESPACE.test(code[end - 1])) {
  1483. end--;
  1484. }
  1485. else {
  1486. return end;
  1487. }
  1488. }
  1489. }
  1490. // This assumes "code" only contains white-space and comments
  1491. // Returns position of line-comment if applicable
  1492. function findFirstLineBreakOutsideComment(code) {
  1493. let lineBreakPos, charCodeAfterSlash, start = 0;
  1494. lineBreakPos = code.indexOf('\n', start);
  1495. while (true) {
  1496. start = code.indexOf('/', start);
  1497. if (start === -1 || start > lineBreakPos)
  1498. return [lineBreakPos, lineBreakPos + 1];
  1499. // With our assumption, '/' always starts a comment. Determine comment type:
  1500. charCodeAfterSlash = code.charCodeAt(start + 1);
  1501. if (charCodeAfterSlash === 47 /*"/"*/)
  1502. return [start, lineBreakPos + 1];
  1503. start = code.indexOf('*/', start + 2) + 2;
  1504. if (start > lineBreakPos) {
  1505. lineBreakPos = code.indexOf('\n', start);
  1506. }
  1507. }
  1508. }
  1509. function renderStatementList(statements, code, start, end, options) {
  1510. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  1511. let nextNode = statements[0];
  1512. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  1513. if (nextNodeNeedsBoundaries) {
  1514. nextNodeStart =
  1515. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  1516. }
  1517. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  1518. currentNode = nextNode;
  1519. currentNodeStart = nextNodeStart;
  1520. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  1521. nextNode = statements[nextIndex];
  1522. nextNodeNeedsBoundaries =
  1523. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  1524. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  1525. nextNodeStart =
  1526. currentNode.end +
  1527. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  1528. if (currentNode.included) {
  1529. if (currentNodeNeedsBoundaries) {
  1530. currentNode.render(code, options, {
  1531. end: nextNodeStart,
  1532. start: currentNodeStart
  1533. });
  1534. }
  1535. else {
  1536. currentNode.render(code, options);
  1537. }
  1538. }
  1539. else {
  1540. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  1541. }
  1542. }
  1543. else {
  1544. currentNode.render(code, options);
  1545. }
  1546. }
  1547. }
  1548. // This assumes that the first character is not part of the first node
  1549. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  1550. const splitUpNodes = [];
  1551. let node, nextNodeStart, contentEnd, char;
  1552. let separator = start - 1;
  1553. for (const nextNode of nodes) {
  1554. if (node !== undefined) {
  1555. separator =
  1556. node.end +
  1557. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  1558. }
  1559. nextNodeStart = contentEnd =
  1560. separator +
  1561. 1 +
  1562. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  1563. while (((char = code.original.charCodeAt(nextNodeStart)),
  1564. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  1565. nextNodeStart++;
  1566. if (node !== undefined) {
  1567. splitUpNodes.push({
  1568. contentEnd,
  1569. end: nextNodeStart,
  1570. node,
  1571. separator,
  1572. start
  1573. });
  1574. }
  1575. node = nextNode;
  1576. start = nextNodeStart;
  1577. }
  1578. splitUpNodes.push({
  1579. contentEnd: end,
  1580. end,
  1581. node: node,
  1582. separator: null,
  1583. start
  1584. });
  1585. return splitUpNodes;
  1586. }
  1587. // This assumes there are only white-space and comments between start and end
  1588. function removeLineBreaks(code, start, end) {
  1589. while (true) {
  1590. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  1591. if (removeStart === -1) {
  1592. break;
  1593. }
  1594. code.remove(start + removeStart, (start += removeEnd));
  1595. }
  1596. }
  1597. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  1598. if (exportedVariables.length === 1 &&
  1599. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  1600. const variable = exportedVariables[0];
  1601. return `exports(${JSON.stringify(exportNamesByVariable.get(variable)[0])},${_}${variable.getName(getPropertyAccess)}${modifier})`;
  1602. }
  1603. else {
  1604. const fields = [];
  1605. for (const variable of exportedVariables) {
  1606. for (const exportName of exportNamesByVariable.get(variable)) {
  1607. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  1608. }
  1609. }
  1610. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  1611. }
  1612. }
  1613. // This is only invoked if there is exactly one export name
  1614. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  1615. code.prependRight(expressionStart, `exports(${JSON.stringify(exportNamesByVariable.get(exportedVariable)[0])},${_}`);
  1616. code.appendLeft(expressionEnd, ')');
  1617. }
  1618. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  1619. const { _, getDirectReturnIifeLeft } = options.snippets;
  1620. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  1621. code.appendLeft(expressionEnd, ')');
  1622. }
  1623. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  1624. const { _, getPropertyAccess } = options.snippets;
  1625. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  1626. if (needsParens) {
  1627. code.prependRight(expressionStart, '(');
  1628. code.appendLeft(expressionEnd, ')');
  1629. }
  1630. }
  1631. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  1632. const { _ } = options.snippets;
  1633. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  1634. if (needsParens) {
  1635. code.prependRight(expressionStart, '(');
  1636. code.appendLeft(expressionEnd, ')');
  1637. }
  1638. }
  1639. function getOrCreate(map, key, init) {
  1640. const existing = map.get(key);
  1641. if (existing !== undefined) {
  1642. return existing;
  1643. }
  1644. const value = init();
  1645. map.set(key, value);
  1646. return value;
  1647. }
  1648. function getNewSet() {
  1649. return new Set();
  1650. }
  1651. function getNewArray() {
  1652. return [];
  1653. }
  1654. const UnknownKey = Symbol('Unknown Key');
  1655. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  1656. const UnknownInteger = Symbol('Unknown Integer');
  1657. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  1658. const EMPTY_PATH = [];
  1659. const UNKNOWN_PATH = [UnknownKey];
  1660. // For deoptimizations, this means we are modifying an unknown property but did
  1661. // not lose track of the object or are creating a setter/getter;
  1662. // For assignment effects it means we do not check for setter/getter effects
  1663. // but only if something is mutated that is included, which is relevant for
  1664. // Object.defineProperty
  1665. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1666. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1667. const EntitiesKey = Symbol('Entities');
  1668. class EntityPathTracker {
  1669. constructor() {
  1670. this.entityPaths = Object.create(null, {
  1671. [EntitiesKey]: { value: new Set() }
  1672. });
  1673. }
  1674. trackEntityAtPathAndGetIfTracked(path, entity) {
  1675. const trackedEntities = this.getEntities(path);
  1676. if (trackedEntities.has(entity))
  1677. return true;
  1678. trackedEntities.add(entity);
  1679. return false;
  1680. }
  1681. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1682. const trackedEntities = this.getEntities(path);
  1683. if (trackedEntities.has(entity))
  1684. return returnIfTracked;
  1685. trackedEntities.add(entity);
  1686. const result = onUntracked();
  1687. trackedEntities.delete(entity);
  1688. return result;
  1689. }
  1690. getEntities(path) {
  1691. let currentPaths = this.entityPaths;
  1692. for (const pathSegment of path) {
  1693. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  1694. [EntitiesKey]: { value: new Set() }
  1695. });
  1696. }
  1697. return currentPaths[EntitiesKey];
  1698. }
  1699. }
  1700. const SHARED_RECURSION_TRACKER = new EntityPathTracker();
  1701. class DiscriminatedPathTracker {
  1702. constructor() {
  1703. this.entityPaths = Object.create(null, {
  1704. [EntitiesKey]: { value: new Map() }
  1705. });
  1706. }
  1707. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1708. let currentPaths = this.entityPaths;
  1709. for (const pathSegment of path) {
  1710. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  1711. [EntitiesKey]: { value: new Map() }
  1712. });
  1713. }
  1714. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  1715. if (trackedEntities.has(entity))
  1716. return true;
  1717. trackedEntities.add(entity);
  1718. return false;
  1719. }
  1720. }
  1721. const UNKNOWN_INCLUDED_PATH = Object.freeze({ [UnknownKey]: EMPTY_OBJECT });
  1722. class IncludedFullPathTracker {
  1723. constructor() {
  1724. this.includedPaths = null;
  1725. }
  1726. includePathAndGetIfIncluded(path) {
  1727. let included = true;
  1728. let parent = this;
  1729. let parentSegment = 'includedPaths';
  1730. let currentPaths = (this.includedPaths ||=
  1731. ((included = false), Object.create(null)));
  1732. for (const pathSegment of path) {
  1733. // This means from here, all paths are included
  1734. if (currentPaths[UnknownKey]) {
  1735. return true;
  1736. }
  1737. // Including UnknownKey automatically includes all nested paths.
  1738. // From above, we know that UnknownKey is not included yet.
  1739. if (typeof pathSegment === 'symbol') {
  1740. // Hopefully, this saves some memory over just setting
  1741. // currentPaths[UnknownKey] = EMPTY_OBJECT
  1742. parent[parentSegment] = UNKNOWN_INCLUDED_PATH;
  1743. return false;
  1744. }
  1745. parent = currentPaths;
  1746. parentSegment = pathSegment;
  1747. currentPaths = currentPaths[pathSegment] ||= ((included = false), Object.create(null));
  1748. }
  1749. return included;
  1750. }
  1751. }
  1752. const UNKNOWN_INCLUDED_TOP_LEVEL_PATH = Object.freeze({
  1753. [UnknownKey]: true
  1754. });
  1755. class IncludedTopLevelPathTracker {
  1756. constructor() {
  1757. this.includedPaths = null;
  1758. }
  1759. includePathAndGetIfIncluded(path) {
  1760. let included = true;
  1761. const includedPaths = (this.includedPaths ||=
  1762. ((included = false), Object.create(null)));
  1763. if (includedPaths[UnknownKey]) {
  1764. return true;
  1765. }
  1766. const [firstPathSegment, secondPathSegment] = path;
  1767. if (!firstPathSegment) {
  1768. return included;
  1769. }
  1770. if (typeof firstPathSegment === 'symbol') {
  1771. this.includedPaths = UNKNOWN_INCLUDED_TOP_LEVEL_PATH;
  1772. return false;
  1773. }
  1774. if (secondPathSegment) {
  1775. if (includedPaths[firstPathSegment] === UnknownKey) {
  1776. return true;
  1777. }
  1778. includedPaths[firstPathSegment] = UnknownKey;
  1779. return false;
  1780. }
  1781. if (includedPaths[firstPathSegment]) {
  1782. return true;
  1783. }
  1784. includedPaths[firstPathSegment] = true;
  1785. return false;
  1786. }
  1787. includeAllPaths(entity, context, basePath) {
  1788. const { includedPaths } = this;
  1789. if (includedPaths) {
  1790. if (includedPaths[UnknownKey]) {
  1791. entity.includePath([...basePath, UnknownKey], context);
  1792. }
  1793. else {
  1794. const inclusionEntries = Object.entries(includedPaths);
  1795. if (inclusionEntries.length === 0) {
  1796. entity.includePath(basePath, context);
  1797. }
  1798. else {
  1799. for (const [key, value] of inclusionEntries) {
  1800. entity.includePath(value === UnknownKey ? [...basePath, key, UnknownKey] : [...basePath, key], context);
  1801. }
  1802. }
  1803. }
  1804. }
  1805. }
  1806. }
  1807. /** @import { Node } from 'estree' */
  1808. /**
  1809. * @param {Node} node
  1810. * @param {Node} parent
  1811. * @returns {boolean}
  1812. */
  1813. function is_reference(node, parent) {
  1814. if (node.type === 'MemberExpression') {
  1815. return !node.computed && is_reference(node.object, node);
  1816. }
  1817. if (node.type !== 'Identifier') return false;
  1818. switch (parent?.type) {
  1819. // disregard `bar` in `foo.bar`
  1820. case 'MemberExpression':
  1821. return parent.computed || node === parent.object;
  1822. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  1823. case 'MethodDefinition':
  1824. return parent.computed;
  1825. // disregard the `meta` in `import.meta`
  1826. case 'MetaProperty':
  1827. return parent.meta === node;
  1828. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  1829. case 'PropertyDefinition':
  1830. return parent.computed || node === parent.value;
  1831. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  1832. case 'Property':
  1833. return parent.computed || node === parent.value;
  1834. // disregard the `bar` in `export { foo as bar }` or
  1835. // the foo in `import { foo as bar }`
  1836. case 'ExportSpecifier':
  1837. case 'ImportSpecifier':
  1838. return node === parent.local;
  1839. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  1840. case 'LabeledStatement':
  1841. case 'BreakStatement':
  1842. case 'ContinueStatement':
  1843. return false;
  1844. default:
  1845. return true;
  1846. }
  1847. }
  1848. function createInclusionContext() {
  1849. return {
  1850. brokenFlow: false,
  1851. hasBreak: false,
  1852. hasContinue: false,
  1853. includedCallArguments: new Set(),
  1854. includedLabels: new Set()
  1855. };
  1856. }
  1857. function createHasEffectsContext() {
  1858. return {
  1859. accessed: new EntityPathTracker(),
  1860. assigned: new EntityPathTracker(),
  1861. brokenFlow: false,
  1862. called: new DiscriminatedPathTracker(),
  1863. hasBreak: false,
  1864. hasContinue: false,
  1865. ignore: {
  1866. breaks: false,
  1867. continues: false,
  1868. labels: new Set(),
  1869. returnYield: false,
  1870. this: false
  1871. },
  1872. includedLabels: new Set(),
  1873. instantiated: new DiscriminatedPathTracker(),
  1874. replacedVariableInits: new Map()
  1875. };
  1876. }
  1877. function isFlagSet(flags, flag) {
  1878. return (flags & flag) !== 0;
  1879. }
  1880. function setFlag(flags, flag, value) {
  1881. return (flags & ~flag) | (-value & flag);
  1882. }
  1883. const UnknownValue = Symbol('Unknown Value');
  1884. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1885. const UnknownFalsyValue = Symbol('Unknown Falsy Value');
  1886. class ExpressionEntity {
  1887. constructor() {
  1888. this.flags = 0;
  1889. }
  1890. get included() {
  1891. return isFlagSet(this.flags, 1 /* Flag.included */);
  1892. }
  1893. set included(value) {
  1894. this.flags = setFlag(this.flags, 1 /* Flag.included */, value);
  1895. }
  1896. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  1897. deoptimizeInteraction(interaction);
  1898. }
  1899. deoptimizePath(_path) { }
  1900. /**
  1901. * If possible it returns a stringifyable literal value for this node that
  1902. * can be used for inlining or comparing values. Otherwise, it should return
  1903. * UnknownValue.
  1904. */
  1905. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1906. return UnknownValue;
  1907. }
  1908. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1909. return UNKNOWN_RETURN_EXPRESSION;
  1910. }
  1911. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1912. return true;
  1913. }
  1914. include(context, _includeChildrenRecursively, _options) {
  1915. if (!this.included)
  1916. this.includeNode(context);
  1917. }
  1918. includeNode(_context) {
  1919. this.included = true;
  1920. }
  1921. includePath(_path, context) {
  1922. if (!this.included)
  1923. this.includeNode(context);
  1924. }
  1925. /* We are both including and including an unknown path here as the former
  1926. * ensures that nested nodes are included while the latter ensures that all
  1927. * paths of the expression are included.
  1928. * */
  1929. includeCallArguments(interaction, context) {
  1930. includeInteraction(interaction, context);
  1931. }
  1932. shouldBeIncluded(_context) {
  1933. return true;
  1934. }
  1935. }
  1936. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1937. })();
  1938. const UNKNOWN_RETURN_EXPRESSION = [
  1939. UNKNOWN_EXPRESSION,
  1940. false
  1941. ];
  1942. const deoptimizeInteraction = (interaction) => {
  1943. for (const argument of interaction.args) {
  1944. argument?.deoptimizePath(UNKNOWN_PATH);
  1945. }
  1946. };
  1947. const includeInteraction = (interaction, context) => {
  1948. // We do not re-include the "this" argument as we expect this is already
  1949. // re-included at the call site
  1950. interaction.args[0]?.includePath(UNKNOWN_PATH, context);
  1951. includeInteractionWithoutThis(interaction, context);
  1952. };
  1953. const includeInteractionWithoutThis = ({ args }, context) => {
  1954. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  1955. const argument = args[argumentIndex];
  1956. if (argument) {
  1957. argument.includePath(UNKNOWN_PATH, context);
  1958. argument.include(context, false);
  1959. }
  1960. }
  1961. };
  1962. const INTERACTION_ACCESSED = 0;
  1963. const INTERACTION_ASSIGNED = 1;
  1964. const INTERACTION_CALLED = 2;
  1965. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1966. args: [null],
  1967. type: INTERACTION_ACCESSED
  1968. };
  1969. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  1970. args: [null, UNKNOWN_EXPRESSION],
  1971. type: INTERACTION_ASSIGNED
  1972. };
  1973. // While this is technically a call without arguments, we can compare against
  1974. // this reference in places where precise values or this argument would make a
  1975. // difference
  1976. const NODE_INTERACTION_UNKNOWN_CALL = {
  1977. args: [null],
  1978. type: INTERACTION_CALLED,
  1979. withNew: false
  1980. };
  1981. const PureFunctionKey = Symbol('PureFunction');
  1982. const getPureFunctions = ({ treeshake }) => {
  1983. const pureFunctions = Object.create(null);
  1984. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  1985. let currentFunctions = pureFunctions;
  1986. for (const pathSegment of functionName.split('.')) {
  1987. currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
  1988. }
  1989. currentFunctions[PureFunctionKey] = true;
  1990. }
  1991. return pureFunctions;
  1992. };
  1993. class Variable extends ExpressionEntity {
  1994. markReassigned() {
  1995. this.isReassigned = true;
  1996. }
  1997. constructor(name) {
  1998. super();
  1999. this.name = name;
  2000. this.alwaysRendered = false;
  2001. this.forbiddenNames = null;
  2002. this.globalName = null;
  2003. this.initReached = false;
  2004. this.isId = false;
  2005. this.kind = null;
  2006. this.renderBaseName = null;
  2007. this.renderName = null;
  2008. this.isReassigned = false;
  2009. this.onlyFunctionCallUsed = true;
  2010. }
  2011. /**
  2012. * Binds identifiers that reference this variable to this variable.
  2013. * Necessary to be able to change variable names.
  2014. */
  2015. addReference(_identifier) { }
  2016. /**
  2017. * Check if the identifier variable is only used as function call
  2018. * @returns true if the variable is only used as function call
  2019. */
  2020. getOnlyFunctionCallUsed() {
  2021. return this.onlyFunctionCallUsed;
  2022. }
  2023. /**
  2024. * Collect the places where the identifier variable is used
  2025. * @param usedPlace Where the variable is used
  2026. */
  2027. addUsedPlace(usedPlace) {
  2028. const isFunctionCall = usedPlace.parent.type === CallExpression$1 &&
  2029. usedPlace.parent.callee === usedPlace;
  2030. if (!isFunctionCall && usedPlace.parent.type !== ExportDefaultDeclaration$1) {
  2031. this.onlyFunctionCallUsed = false;
  2032. }
  2033. }
  2034. /**
  2035. * Prevent this variable from being renamed to this name to avoid name
  2036. * collisions
  2037. */
  2038. forbidName(name) {
  2039. (this.forbiddenNames ||= new Set()).add(name);
  2040. }
  2041. getBaseVariableName() {
  2042. return (this.renderedLikeHoisted?.getBaseVariableName() ||
  2043. this.renderBaseName ||
  2044. this.renderName ||
  2045. this.name);
  2046. }
  2047. getName(getPropertyAccess, useOriginalName) {
  2048. if (this.globalName) {
  2049. return this.globalName;
  2050. }
  2051. if (useOriginalName?.(this)) {
  2052. return this.name;
  2053. }
  2054. if (this.renderedLikeHoisted) {
  2055. return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
  2056. }
  2057. const name = this.renderName || this.name;
  2058. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  2059. }
  2060. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  2061. return type !== INTERACTION_ACCESSED || path.length > 0;
  2062. }
  2063. /**
  2064. * Marks this variable as being part of the bundle, which is usually the case
  2065. * when one of its identifiers becomes part of the bundle. Returns true if it
  2066. * has not been included previously. Once a variable is included, it should
  2067. * take care all its declarations are included.
  2068. */
  2069. includePath(path, context) {
  2070. this.included = true;
  2071. this.renderedLikeHoisted?.includePath(path, context);
  2072. }
  2073. /**
  2074. * Links the rendered name of this variable to another variable and includes
  2075. * this variable if the other variable is included.
  2076. */
  2077. renderLikeHoisted(variable) {
  2078. this.renderedLikeHoisted = variable;
  2079. }
  2080. markCalledFromTryStatement() { }
  2081. setRenderNames(baseName, name) {
  2082. this.renderBaseName = baseName;
  2083. this.renderName = name;
  2084. }
  2085. }
  2086. class ExternalVariable extends Variable {
  2087. constructor(module, name) {
  2088. super(name);
  2089. this.referenced = false;
  2090. this.module = module;
  2091. this.isNamespace = name === '*';
  2092. }
  2093. addReference(identifier) {
  2094. this.referenced = true;
  2095. if (this.name === 'default' || this.name === '*') {
  2096. this.module.suggestName(identifier.name);
  2097. }
  2098. }
  2099. hasEffectsOnInteractionAtPath(path, { type }) {
  2100. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  2101. }
  2102. includePath(path, context) {
  2103. super.includePath(path, context);
  2104. this.module.used = true;
  2105. }
  2106. }
  2107. function cacheObjectGetters(object, getterProperties) {
  2108. for (const property of getterProperties) {
  2109. const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
  2110. Object.defineProperty(object, property, {
  2111. get() {
  2112. const value = propertyGetter.call(object);
  2113. // This replaces the getter with a fixed value for subsequent calls
  2114. Object.defineProperty(object, property, { value });
  2115. return value;
  2116. }
  2117. });
  2118. }
  2119. }
  2120. const RESERVED_NAMES = new Set([
  2121. 'await',
  2122. 'break',
  2123. 'case',
  2124. 'catch',
  2125. 'class',
  2126. 'const',
  2127. 'continue',
  2128. 'debugger',
  2129. 'default',
  2130. 'delete',
  2131. 'do',
  2132. 'else',
  2133. 'enum',
  2134. 'eval',
  2135. 'export',
  2136. 'extends',
  2137. 'false',
  2138. 'finally',
  2139. 'for',
  2140. 'function',
  2141. 'if',
  2142. 'implements',
  2143. 'import',
  2144. 'in',
  2145. 'instanceof',
  2146. 'interface',
  2147. 'let',
  2148. 'NaN',
  2149. 'new',
  2150. 'null',
  2151. 'package',
  2152. 'private',
  2153. 'protected',
  2154. 'public',
  2155. 'return',
  2156. 'static',
  2157. 'super',
  2158. 'switch',
  2159. 'this',
  2160. 'throw',
  2161. 'true',
  2162. 'try',
  2163. 'typeof',
  2164. 'undefined',
  2165. 'var',
  2166. 'void',
  2167. 'while',
  2168. 'with',
  2169. 'yield'
  2170. ]);
  2171. const illegalCharacters = /[^\w$]/g;
  2172. const startsWithDigit = (value) => /\d/.test(value[0]);
  2173. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES.has(value) || value === 'arguments';
  2174. function isLegal(value) {
  2175. if (needsEscape(value)) {
  2176. return false;
  2177. }
  2178. return !illegalCharacters.test(value);
  2179. }
  2180. function makeLegal(value) {
  2181. value = value
  2182. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  2183. .replace(illegalCharacters, '_');
  2184. if (needsEscape(value))
  2185. value = `_${value}`;
  2186. return value || '_';
  2187. }
  2188. const VALID_IDENTIFIER_REGEXP = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
  2189. const NUMBER_REGEXP = /^(?:0|[1-9]\d*)$/;
  2190. function stringifyObjectKeyIfNeeded(key) {
  2191. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  2192. return key === '__proto__' ? '["__proto__"]' : key;
  2193. }
  2194. if (NUMBER_REGEXP.test(key) && +key <= Number.MAX_SAFE_INTEGER) {
  2195. return key;
  2196. }
  2197. return JSON.stringify(key);
  2198. }
  2199. function stringifyIdentifierIfNeeded(key) {
  2200. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  2201. return key;
  2202. }
  2203. return JSON.stringify(key);
  2204. }
  2205. class ExternalModule {
  2206. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
  2207. this.options = options;
  2208. this.id = id;
  2209. this.renormalizeRenderPath = renormalizeRenderPath;
  2210. this.dynamicImporters = [];
  2211. this.execIndex = Infinity;
  2212. this.exportedVariables = new Map();
  2213. this.importers = [];
  2214. this.reexported = false;
  2215. this.used = false;
  2216. this.declarations = new Map();
  2217. this.mostCommonSuggestion = 0;
  2218. this.nameSuggestions = new Map();
  2219. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  2220. const { importers, dynamicImporters } = this;
  2221. this.info = {
  2222. ast: null,
  2223. attributes,
  2224. code: null,
  2225. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2226. dynamicallyImportedIds: EMPTY_ARRAY,
  2227. get dynamicImporters() {
  2228. return dynamicImporters.sort();
  2229. },
  2230. exportedBindings: null,
  2231. exports: null,
  2232. hasDefaultExport: null,
  2233. id,
  2234. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2235. implicitlyLoadedBefore: EMPTY_ARRAY,
  2236. importedIdResolutions: EMPTY_ARRAY,
  2237. importedIds: EMPTY_ARRAY,
  2238. get importers() {
  2239. return importers.sort();
  2240. },
  2241. isEntry: false,
  2242. isExternal: true,
  2243. isIncluded: null,
  2244. meta,
  2245. moduleSideEffects,
  2246. syntheticNamedExports: false
  2247. };
  2248. }
  2249. cacheInfoGetters() {
  2250. cacheObjectGetters(this.info, ['dynamicImporters', 'importers']);
  2251. }
  2252. getVariableForExportName(name) {
  2253. const declaration = this.declarations.get(name);
  2254. if (declaration)
  2255. return [declaration];
  2256. const externalVariable = new ExternalVariable(this, name);
  2257. this.declarations.set(name, externalVariable);
  2258. this.exportedVariables.set(externalVariable, name);
  2259. return [externalVariable];
  2260. }
  2261. suggestName(name) {
  2262. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  2263. this.nameSuggestions.set(name, value);
  2264. if (value > this.mostCommonSuggestion) {
  2265. this.mostCommonSuggestion = value;
  2266. this.suggestedVariableName = name;
  2267. }
  2268. }
  2269. warnUnusedImports() {
  2270. const unused = [...this.declarations]
  2271. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2272. .map(([name]) => name);
  2273. if (unused.length === 0)
  2274. return;
  2275. const importersSet = new Set();
  2276. for (const name of unused) {
  2277. for (const importer of this.declarations.get(name).module.importers) {
  2278. importersSet.add(importer);
  2279. }
  2280. }
  2281. const importersArray = [...importersSet];
  2282. this.options.onLog(LOGLEVEL_WARN, logUnusedExternalImports(this.id, unused, importersArray));
  2283. }
  2284. }
  2285. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  2286. baseModule.isExecuted = true;
  2287. const modules = [baseModule];
  2288. const visitedModules = new Set();
  2289. for (const module of modules) {
  2290. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  2291. if (!(dependency instanceof ExternalModule) &&
  2292. !dependency.isExecuted &&
  2293. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  2294. !visitedModules.has(dependency.id)) {
  2295. dependency.isExecuted = true;
  2296. visitedModules.add(dependency.id);
  2297. modules.push(dependency);
  2298. }
  2299. }
  2300. }
  2301. }
  2302. const doNothing = () => { };
  2303. // This file is generated by scripts/generate-child-node-keys.js.
  2304. // Do not edit this file directly.
  2305. const childNodeKeys = {
  2306. ArrayExpression: ['elements'],
  2307. ArrayPattern: ['elements'],
  2308. ArrowFunctionExpression: ['params', 'body'],
  2309. AssignmentExpression: ['left', 'right'],
  2310. AssignmentPattern: ['left', 'right'],
  2311. AwaitExpression: ['argument'],
  2312. BinaryExpression: ['left', 'right'],
  2313. BlockStatement: ['body'],
  2314. BreakStatement: ['label'],
  2315. CallExpression: ['callee', 'arguments'],
  2316. CatchClause: ['param', 'body'],
  2317. ChainExpression: ['expression'],
  2318. ClassBody: ['body'],
  2319. ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
  2320. ClassExpression: ['decorators', 'id', 'superClass', 'body'],
  2321. ConditionalExpression: ['test', 'consequent', 'alternate'],
  2322. ContinueStatement: ['label'],
  2323. DebuggerStatement: [],
  2324. Decorator: ['expression'],
  2325. DoWhileStatement: ['body', 'test'],
  2326. EmptyStatement: [],
  2327. ExportAllDeclaration: ['exported', 'source', 'attributes'],
  2328. ExportDefaultDeclaration: ['declaration'],
  2329. ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
  2330. ExportSpecifier: ['local', 'exported'],
  2331. ExpressionStatement: ['expression'],
  2332. ForInStatement: ['left', 'right', 'body'],
  2333. ForOfStatement: ['left', 'right', 'body'],
  2334. ForStatement: ['init', 'test', 'update', 'body'],
  2335. FunctionDeclaration: ['id', 'params', 'body'],
  2336. FunctionExpression: ['id', 'params', 'body'],
  2337. Identifier: [],
  2338. IfStatement: ['test', 'consequent', 'alternate'],
  2339. ImportAttribute: ['key', 'value'],
  2340. ImportDeclaration: ['specifiers', 'source', 'attributes'],
  2341. ImportDefaultSpecifier: ['local'],
  2342. ImportExpression: ['source', 'options'],
  2343. ImportNamespaceSpecifier: ['local'],
  2344. ImportSpecifier: ['imported', 'local'],
  2345. JSXAttribute: ['name', 'value'],
  2346. JSXClosingElement: ['name'],
  2347. JSXClosingFragment: [],
  2348. JSXElement: ['openingElement', 'children', 'closingElement'],
  2349. JSXEmptyExpression: [],
  2350. JSXExpressionContainer: ['expression'],
  2351. JSXFragment: ['openingFragment', 'children', 'closingFragment'],
  2352. JSXIdentifier: [],
  2353. JSXMemberExpression: ['object', 'property'],
  2354. JSXNamespacedName: ['namespace', 'name'],
  2355. JSXOpeningElement: ['name', 'attributes'],
  2356. JSXOpeningFragment: [],
  2357. JSXSpreadAttribute: ['argument'],
  2358. JSXSpreadChild: ['expression'],
  2359. JSXText: [],
  2360. LabeledStatement: ['label', 'body'],
  2361. Literal: [],
  2362. LogicalExpression: ['left', 'right'],
  2363. MemberExpression: ['object', 'property'],
  2364. MetaProperty: ['meta', 'property'],
  2365. MethodDefinition: ['decorators', 'key', 'value'],
  2366. NewExpression: ['callee', 'arguments'],
  2367. ObjectExpression: ['properties'],
  2368. ObjectPattern: ['properties'],
  2369. PanicError: [],
  2370. ParseError: [],
  2371. PrivateIdentifier: [],
  2372. Program: ['body'],
  2373. Property: ['key', 'value'],
  2374. PropertyDefinition: ['decorators', 'key', 'value'],
  2375. RestElement: ['argument'],
  2376. ReturnStatement: ['argument'],
  2377. SequenceExpression: ['expressions'],
  2378. SpreadElement: ['argument'],
  2379. StaticBlock: ['body'],
  2380. Super: [],
  2381. SwitchCase: ['test', 'consequent'],
  2382. SwitchStatement: ['discriminant', 'cases'],
  2383. TaggedTemplateExpression: ['tag', 'quasi'],
  2384. TemplateElement: [],
  2385. TemplateLiteral: ['quasis', 'expressions'],
  2386. ThisExpression: [],
  2387. ThrowStatement: ['argument'],
  2388. TryStatement: ['block', 'handler', 'finalizer'],
  2389. UnaryExpression: ['argument'],
  2390. UpdateExpression: ['argument'],
  2391. VariableDeclaration: ['declarations'],
  2392. VariableDeclarator: ['id', 'init'],
  2393. WhileStatement: ['test', 'body'],
  2394. YieldExpression: ['argument']
  2395. };
  2396. const INCLUDE_PARAMETERS = 'variables';
  2397. const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
  2398. class NodeBase extends ExpressionEntity {
  2399. /**
  2400. * Nodes can apply custom deoptimizations once they become part of the
  2401. * executed code. To do this, they must initialize this as false, implement
  2402. * applyDeoptimizations and call this from include and hasEffects if they have
  2403. * custom handlers
  2404. */
  2405. get deoptimized() {
  2406. return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
  2407. }
  2408. set deoptimized(value) {
  2409. this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
  2410. }
  2411. constructor(parent, parentScope) {
  2412. super();
  2413. this.parent = parent;
  2414. this.scope = parentScope;
  2415. this.createScope(parentScope);
  2416. }
  2417. addExportedVariables(_variables, _exportNamesByVariable) { }
  2418. /**
  2419. * Override this to bind assignments to variables and do any initialisations
  2420. * that require the scopes to be populated with variables.
  2421. */
  2422. bind() {
  2423. for (const key of childNodeKeys[this.type]) {
  2424. const value = this[key];
  2425. if (Array.isArray(value)) {
  2426. for (const child of value) {
  2427. child?.bind();
  2428. }
  2429. }
  2430. else if (value) {
  2431. value.bind();
  2432. }
  2433. }
  2434. }
  2435. /**
  2436. * Override if this node should receive a different scope than the parent
  2437. * scope.
  2438. */
  2439. createScope(parentScope) {
  2440. this.scope = parentScope;
  2441. }
  2442. hasEffects(context) {
  2443. if (!this.deoptimized)
  2444. this.applyDeoptimizations();
  2445. for (const key of childNodeKeys[this.type]) {
  2446. const value = this[key];
  2447. if (value === null)
  2448. continue;
  2449. if (Array.isArray(value)) {
  2450. for (const child of value) {
  2451. if (child?.hasEffects(context))
  2452. return true;
  2453. }
  2454. }
  2455. else if (value.hasEffects(context))
  2456. return true;
  2457. }
  2458. return false;
  2459. }
  2460. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  2461. return (this.hasEffects(context) ||
  2462. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  2463. }
  2464. include(context, includeChildrenRecursively, _options) {
  2465. if (!this.included)
  2466. this.includeNode(context);
  2467. for (const key of childNodeKeys[this.type]) {
  2468. const value = this[key];
  2469. if (value === null)
  2470. continue;
  2471. if (Array.isArray(value)) {
  2472. for (const child of value) {
  2473. child?.include(context, includeChildrenRecursively);
  2474. }
  2475. }
  2476. else {
  2477. value.include(context, includeChildrenRecursively);
  2478. }
  2479. }
  2480. }
  2481. includeNode(context) {
  2482. this.included = true;
  2483. if (!this.deoptimized)
  2484. this.applyDeoptimizations();
  2485. for (const key of childNodeKeys[this.type]) {
  2486. const value = this[key];
  2487. if (value === null)
  2488. continue;
  2489. if (Array.isArray(value)) {
  2490. for (const child of value) {
  2491. child?.includePath(UNKNOWN_PATH, context);
  2492. }
  2493. }
  2494. else {
  2495. value.includePath(UNKNOWN_PATH, context);
  2496. }
  2497. }
  2498. }
  2499. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  2500. this.include(context, includeChildrenRecursively);
  2501. }
  2502. /**
  2503. * Override to perform special initialisation steps after the scope is
  2504. * initialised
  2505. */
  2506. initialise() {
  2507. this.scope.context.magicString.addSourcemapLocation(this.start);
  2508. this.scope.context.magicString.addSourcemapLocation(this.end);
  2509. }
  2510. parseNode(esTreeNode) {
  2511. for (const [key, value] of Object.entries(esTreeNode)) {
  2512. // Skip properties defined on the class already.
  2513. // This way, we can override this function to add custom initialisation and then call super.parseNode
  2514. // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
  2515. // in bitfields. Those are still assigned from the value in the esTreeNode.
  2516. if (this.hasOwnProperty(key))
  2517. continue;
  2518. if (key.charCodeAt(0) === 95 /* _ */) {
  2519. if (key === ANNOTATION_KEY) {
  2520. this.annotations = value;
  2521. }
  2522. else if (key === INVALID_ANNOTATION_KEY) {
  2523. this.invalidAnnotations = value;
  2524. }
  2525. }
  2526. else if (typeof value !== 'object' || value === null) {
  2527. this[key] = value;
  2528. }
  2529. else if (Array.isArray(value)) {
  2530. this[key] = new Array(value.length);
  2531. let index = 0;
  2532. for (const child of value) {
  2533. this[key][index++] =
  2534. child === null
  2535. ? null
  2536. : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child);
  2537. }
  2538. }
  2539. else {
  2540. this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
  2541. }
  2542. }
  2543. // extend child keys for unknown node types
  2544. childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
  2545. this.initialise();
  2546. return this;
  2547. }
  2548. removeAnnotations(code) {
  2549. if (this.annotations) {
  2550. for (const annotation of this.annotations) {
  2551. code.remove(annotation.start, annotation.end);
  2552. }
  2553. }
  2554. }
  2555. render(code, options) {
  2556. for (const key of childNodeKeys[this.type]) {
  2557. const value = this[key];
  2558. if (value === null)
  2559. continue;
  2560. if (Array.isArray(value)) {
  2561. for (const child of value) {
  2562. child?.render(code, options);
  2563. }
  2564. }
  2565. else {
  2566. value.render(code, options);
  2567. }
  2568. }
  2569. }
  2570. setAssignedValue(value) {
  2571. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  2572. }
  2573. shouldBeIncluded(context) {
  2574. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  2575. }
  2576. /**
  2577. * Just deoptimize everything by default so that when e.g. we do not track
  2578. * something properly, it is deoptimized.
  2579. * @protected
  2580. */
  2581. applyDeoptimizations() {
  2582. this.deoptimized = true;
  2583. for (const key of childNodeKeys[this.type]) {
  2584. const value = this[key];
  2585. if (value === null)
  2586. continue;
  2587. if (Array.isArray(value)) {
  2588. for (const child of value) {
  2589. child?.deoptimizePath(UNKNOWN_PATH);
  2590. }
  2591. }
  2592. else {
  2593. value.deoptimizePath(UNKNOWN_PATH);
  2594. }
  2595. }
  2596. this.scope.context.requestTreeshakingPass();
  2597. }
  2598. }
  2599. function createChildNodeKeysForNode(esTreeNode) {
  2600. return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  2601. }
  2602. function onlyIncludeSelf() {
  2603. this.included = true;
  2604. if (!this.deoptimized)
  2605. this.applyDeoptimizations();
  2606. }
  2607. function onlyIncludeSelfNoDeoptimize() {
  2608. this.included = true;
  2609. }
  2610. function doNotDeoptimize() {
  2611. this.deoptimized = true;
  2612. }
  2613. function isObjectExpressionNode(node) {
  2614. return node instanceof NodeBase && node.type === ObjectExpression$1;
  2615. }
  2616. function isPropertyNode(node) {
  2617. return node instanceof NodeBase && node.type === Property$1;
  2618. }
  2619. function isArrowFunctionExpressionNode(node) {
  2620. return node instanceof NodeBase && node.type === ArrowFunctionExpression$1;
  2621. }
  2622. function isCallExpressionNode(node) {
  2623. return node instanceof NodeBase && node.type === CallExpression$1;
  2624. }
  2625. function isMemberExpressionNode(node) {
  2626. return node instanceof NodeBase && node.type === MemberExpression$1;
  2627. }
  2628. function isImportExpressionNode(node) {
  2629. return node instanceof NodeBase && node.type === ImportExpression$1;
  2630. }
  2631. function isAwaitExpressionNode(node) {
  2632. return node instanceof NodeBase && node.type === AwaitExpression$1;
  2633. }
  2634. function isIdentifierNode(node) {
  2635. return node instanceof NodeBase && node.type === Identifier$1;
  2636. }
  2637. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  2638. return Object.create(inheritedDescriptions, memberDescriptions);
  2639. }
  2640. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  2641. getLiteralValueAtPath(path) {
  2642. return path.length > 0 ? UnknownValue : undefined;
  2643. }
  2644. })();
  2645. const returnsUnknown = {
  2646. value: {
  2647. hasEffectsWhenCalled: null,
  2648. returns: UNKNOWN_EXPRESSION
  2649. }
  2650. };
  2651. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  2652. getReturnExpressionWhenCalledAtPath(path) {
  2653. if (path.length === 1) {
  2654. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  2655. }
  2656. return UNKNOWN_RETURN_EXPRESSION;
  2657. }
  2658. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2659. if (interaction.type === INTERACTION_ACCESSED) {
  2660. return path.length > 1;
  2661. }
  2662. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2663. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  2664. }
  2665. return true;
  2666. }
  2667. })();
  2668. const returnsBoolean = {
  2669. value: {
  2670. hasEffectsWhenCalled: null,
  2671. returns: UNKNOWN_LITERAL_BOOLEAN
  2672. }
  2673. };
  2674. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  2675. getReturnExpressionWhenCalledAtPath(path) {
  2676. if (path.length === 1) {
  2677. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  2678. }
  2679. return UNKNOWN_RETURN_EXPRESSION;
  2680. }
  2681. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2682. if (interaction.type === INTERACTION_ACCESSED) {
  2683. return path.length > 1;
  2684. }
  2685. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2686. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  2687. }
  2688. return true;
  2689. }
  2690. })();
  2691. const returnsNumber = {
  2692. value: {
  2693. hasEffectsWhenCalled: null,
  2694. returns: UNKNOWN_LITERAL_NUMBER
  2695. }
  2696. };
  2697. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  2698. getReturnExpressionWhenCalledAtPath(path) {
  2699. if (path.length === 1) {
  2700. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  2701. }
  2702. return UNKNOWN_RETURN_EXPRESSION;
  2703. }
  2704. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2705. if (interaction.type === INTERACTION_ACCESSED) {
  2706. return path.length > 1;
  2707. }
  2708. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2709. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  2710. }
  2711. return true;
  2712. }
  2713. })();
  2714. const returnsString = {
  2715. value: {
  2716. hasEffectsWhenCalled: null,
  2717. returns: UNKNOWN_LITERAL_STRING
  2718. }
  2719. };
  2720. const stringReplace = {
  2721. value: {
  2722. hasEffectsWhenCalled({ args }, context) {
  2723. const argument1 = args[2];
  2724. return (args.length < 3 ||
  2725. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  2726. deoptimizeCache() { }
  2727. }) === 'symbol' &&
  2728. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  2729. },
  2730. returns: UNKNOWN_LITERAL_STRING
  2731. }
  2732. };
  2733. const objectMembers = assembleMemberDescriptions({
  2734. hasOwnProperty: returnsBoolean,
  2735. isPrototypeOf: returnsBoolean,
  2736. propertyIsEnumerable: returnsBoolean,
  2737. toLocaleString: returnsString,
  2738. toString: returnsString,
  2739. valueOf: returnsUnknown
  2740. });
  2741. const literalBooleanMembers = assembleMemberDescriptions({
  2742. valueOf: returnsBoolean
  2743. }, objectMembers);
  2744. const literalNumberMembers = assembleMemberDescriptions({
  2745. toExponential: returnsString,
  2746. toFixed: returnsString,
  2747. toLocaleString: returnsString,
  2748. toPrecision: returnsString,
  2749. valueOf: returnsNumber
  2750. }, objectMembers);
  2751. /**
  2752. * RegExp are stateful when they have the global or sticky flags set.
  2753. * But if we actually don't use them, the side effect does not matter.
  2754. * the check logic in `hasEffectsOnInteractionAtPath`.
  2755. */
  2756. const literalRegExpMembers = assembleMemberDescriptions({
  2757. exec: returnsUnknown,
  2758. test: returnsBoolean
  2759. }, objectMembers);
  2760. const literalStringMembers = assembleMemberDescriptions({
  2761. anchor: returnsString,
  2762. at: returnsUnknown,
  2763. big: returnsString,
  2764. blink: returnsString,
  2765. bold: returnsString,
  2766. charAt: returnsString,
  2767. charCodeAt: returnsNumber,
  2768. codePointAt: returnsUnknown,
  2769. concat: returnsString,
  2770. endsWith: returnsBoolean,
  2771. fixed: returnsString,
  2772. fontcolor: returnsString,
  2773. fontsize: returnsString,
  2774. includes: returnsBoolean,
  2775. indexOf: returnsNumber,
  2776. italics: returnsString,
  2777. lastIndexOf: returnsNumber,
  2778. link: returnsString,
  2779. localeCompare: returnsNumber,
  2780. match: returnsUnknown,
  2781. matchAll: returnsUnknown,
  2782. normalize: returnsString,
  2783. padEnd: returnsString,
  2784. padStart: returnsString,
  2785. repeat: returnsString,
  2786. replace: stringReplace,
  2787. replaceAll: stringReplace,
  2788. search: returnsNumber,
  2789. slice: returnsString,
  2790. small: returnsString,
  2791. split: returnsUnknown,
  2792. startsWith: returnsBoolean,
  2793. strike: returnsString,
  2794. sub: returnsString,
  2795. substr: returnsString,
  2796. substring: returnsString,
  2797. sup: returnsString,
  2798. toLocaleLowerCase: returnsString,
  2799. toLocaleUpperCase: returnsString,
  2800. toLowerCase: returnsString,
  2801. toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
  2802. toUpperCase: returnsString,
  2803. trim: returnsString,
  2804. trimEnd: returnsString,
  2805. trimLeft: returnsString,
  2806. trimRight: returnsString,
  2807. trimStart: returnsString,
  2808. valueOf: returnsString
  2809. }, objectMembers);
  2810. function getLiteralMembersForValue(value) {
  2811. if (value instanceof RegExp) {
  2812. return literalRegExpMembers;
  2813. }
  2814. switch (typeof value) {
  2815. case 'boolean': {
  2816. return literalBooleanMembers;
  2817. }
  2818. case 'number': {
  2819. return literalNumberMembers;
  2820. }
  2821. case 'string': {
  2822. return literalStringMembers;
  2823. }
  2824. }
  2825. return Object.create(null);
  2826. }
  2827. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  2828. if (typeof memberName !== 'string' || !members[memberName]) {
  2829. return true;
  2830. }
  2831. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  2832. }
  2833. function getMemberReturnExpressionWhenCalled(members, memberName) {
  2834. if (typeof memberName !== 'string' || !members[memberName])
  2835. return UNKNOWN_RETURN_EXPRESSION;
  2836. return [members[memberName].returns, false];
  2837. }
  2838. class Method extends ExpressionEntity {
  2839. constructor(description) {
  2840. super();
  2841. this.description = description;
  2842. }
  2843. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  2844. if (type === INTERACTION_CALLED && path.length === 0) {
  2845. if (this.description.mutatesSelfAsArray) {
  2846. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  2847. }
  2848. if (this.description.mutatesArgs) {
  2849. for (let index = 1; index < args.length; index++) {
  2850. args[index].deoptimizePath(UNKNOWN_PATH);
  2851. }
  2852. }
  2853. }
  2854. }
  2855. getReturnExpressionWhenCalledAtPath(path, { args }) {
  2856. if (path.length > 0) {
  2857. return UNKNOWN_RETURN_EXPRESSION;
  2858. }
  2859. return [
  2860. this.description.returnsPrimitive ||
  2861. (this.description.returns === 'self'
  2862. ? args[0] || UNKNOWN_EXPRESSION
  2863. : this.description.returns()),
  2864. false
  2865. ];
  2866. }
  2867. hasEffectsOnInteractionAtPath(path, { args, type }, context) {
  2868. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  2869. return true;
  2870. }
  2871. if (type === INTERACTION_CALLED) {
  2872. if (this.description.mutatesSelfAsArray === true &&
  2873. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  2874. return true;
  2875. }
  2876. if (this.description.callsArgs) {
  2877. for (const argumentIndex of this.description.callsArgs) {
  2878. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  2879. return true;
  2880. }
  2881. }
  2882. }
  2883. }
  2884. return false;
  2885. }
  2886. }
  2887. const METHOD_RETURNS_BOOLEAN = [
  2888. new Method({
  2889. callsArgs: null,
  2890. mutatesArgs: false,
  2891. mutatesSelfAsArray: false,
  2892. returns: null,
  2893. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  2894. })
  2895. ];
  2896. const METHOD_RETURNS_STRING = [
  2897. new Method({
  2898. callsArgs: null,
  2899. mutatesArgs: false,
  2900. mutatesSelfAsArray: false,
  2901. returns: null,
  2902. returnsPrimitive: UNKNOWN_LITERAL_STRING
  2903. })
  2904. ];
  2905. const METHOD_RETURNS_NUMBER = [
  2906. new Method({
  2907. callsArgs: null,
  2908. mutatesArgs: false,
  2909. mutatesSelfAsArray: false,
  2910. returns: null,
  2911. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  2912. })
  2913. ];
  2914. const METHOD_RETURNS_UNKNOWN = [
  2915. new Method({
  2916. callsArgs: null,
  2917. mutatesArgs: false,
  2918. mutatesSelfAsArray: false,
  2919. returns: null,
  2920. returnsPrimitive: UNKNOWN_EXPRESSION
  2921. })
  2922. ];
  2923. const INTEGER_REG_EXP = /^\d+$/;
  2924. class ObjectEntity extends ExpressionEntity {
  2925. get hasLostTrack() {
  2926. return isFlagSet(this.flags, 2048 /* Flag.hasLostTrack */);
  2927. }
  2928. set hasLostTrack(value) {
  2929. this.flags = setFlag(this.flags, 2048 /* Flag.hasLostTrack */, value);
  2930. }
  2931. get hasUnknownDeoptimizedInteger() {
  2932. return isFlagSet(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */);
  2933. }
  2934. set hasUnknownDeoptimizedInteger(value) {
  2935. this.flags = setFlag(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */, value);
  2936. }
  2937. get hasUnknownDeoptimizedProperty() {
  2938. return isFlagSet(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */);
  2939. }
  2940. set hasUnknownDeoptimizedProperty(value) {
  2941. this.flags = setFlag(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */, value);
  2942. }
  2943. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  2944. // and we assume there are no setters or getters
  2945. constructor(properties, prototypeExpression, immutable = false) {
  2946. super();
  2947. this.prototypeExpression = prototypeExpression;
  2948. this.immutable = immutable;
  2949. this.additionalExpressionsToBeDeoptimized = new Set();
  2950. this.allProperties = [];
  2951. this.deoptimizedPaths = Object.create(null);
  2952. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  2953. this.gettersByKey = Object.create(null);
  2954. this.propertiesAndGettersByKey = Object.create(null);
  2955. this.propertiesAndSettersByKey = Object.create(null);
  2956. this.settersByKey = Object.create(null);
  2957. this.unknownIntegerProps = [];
  2958. this.unmatchableGetters = [];
  2959. this.unmatchablePropertiesAndGetters = [];
  2960. this.unmatchablePropertiesAndSetters = [];
  2961. this.unmatchableSetters = [];
  2962. if (Array.isArray(properties)) {
  2963. this.buildPropertyMaps(properties);
  2964. }
  2965. else {
  2966. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  2967. for (const propertiesForKey of Object.values(properties)) {
  2968. this.allProperties.push(...propertiesForKey);
  2969. }
  2970. }
  2971. }
  2972. deoptimizeAllProperties(noAccessors) {
  2973. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  2974. if (noAccessors) {
  2975. this.hasUnknownDeoptimizedProperty = true;
  2976. }
  2977. else {
  2978. this.hasLostTrack = true;
  2979. }
  2980. if (isDeoptimized) {
  2981. return;
  2982. }
  2983. for (const properties of [
  2984. ...Object.values(this.propertiesAndGettersByKey),
  2985. ...Object.values(this.settersByKey)
  2986. ]) {
  2987. for (const property of properties) {
  2988. property.deoptimizePath(UNKNOWN_PATH);
  2989. }
  2990. }
  2991. // While the prototype itself cannot be mutated, each property can
  2992. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  2993. this.deoptimizeCachedEntities();
  2994. }
  2995. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  2996. const [key, ...subPath] = path;
  2997. const { args, type } = interaction;
  2998. if (this.hasLostTrack ||
  2999. // single paths that are deoptimized will not become getters or setters
  3000. ((type === INTERACTION_CALLED || path.length > 1) &&
  3001. (this.hasUnknownDeoptimizedProperty ||
  3002. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  3003. deoptimizeInteraction(interaction);
  3004. return;
  3005. }
  3006. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  3007. ? [
  3008. this.propertiesAndGettersByKey,
  3009. this.propertiesAndGettersByKey,
  3010. this.unmatchablePropertiesAndGetters
  3011. ]
  3012. : type === INTERACTION_ACCESSED
  3013. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  3014. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  3015. if (typeof key === 'string') {
  3016. if (propertiesForExactMatchByKey[key]) {
  3017. const properties = relevantPropertiesByKey[key];
  3018. if (properties) {
  3019. for (const property of properties) {
  3020. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3021. }
  3022. }
  3023. if (!this.immutable) {
  3024. for (const argument of args) {
  3025. if (argument) {
  3026. this.additionalExpressionsToBeDeoptimized.add(argument);
  3027. }
  3028. }
  3029. }
  3030. return;
  3031. }
  3032. for (const property of relevantUnmatchableProperties) {
  3033. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3034. }
  3035. if (INTEGER_REG_EXP.test(key)) {
  3036. for (const property of this.unknownIntegerProps) {
  3037. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3038. }
  3039. }
  3040. }
  3041. else {
  3042. for (const properties of [
  3043. ...Object.values(relevantPropertiesByKey),
  3044. relevantUnmatchableProperties
  3045. ]) {
  3046. for (const property of properties) {
  3047. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3048. }
  3049. }
  3050. for (const property of this.unknownIntegerProps) {
  3051. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3052. }
  3053. }
  3054. if (!this.immutable) {
  3055. for (const argument of args) {
  3056. if (argument) {
  3057. this.additionalExpressionsToBeDeoptimized.add(argument);
  3058. }
  3059. }
  3060. }
  3061. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  3062. }
  3063. deoptimizeIntegerProperties() {
  3064. if (this.hasLostTrack ||
  3065. this.hasUnknownDeoptimizedProperty ||
  3066. this.hasUnknownDeoptimizedInteger) {
  3067. return;
  3068. }
  3069. this.hasUnknownDeoptimizedInteger = true;
  3070. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  3071. if (INTEGER_REG_EXP.test(key)) {
  3072. for (const property of propertiesAndGetters) {
  3073. property.deoptimizePath(UNKNOWN_PATH);
  3074. }
  3075. }
  3076. }
  3077. this.deoptimizeCachedIntegerEntities();
  3078. }
  3079. // Assumption: If only a specific path is deoptimized, no accessors are created
  3080. deoptimizePath(path) {
  3081. if (this.hasLostTrack || this.immutable) {
  3082. return;
  3083. }
  3084. const key = path[0];
  3085. if (path.length === 1) {
  3086. if (key === UnknownInteger) {
  3087. return this.deoptimizeIntegerProperties();
  3088. }
  3089. else if (typeof key !== 'string') {
  3090. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  3091. }
  3092. if (!this.deoptimizedPaths[key]) {
  3093. this.deoptimizedPaths[key] = true;
  3094. // we only deoptimizeCache exact matches as in all other cases,
  3095. // we do not return a literal value or return expression
  3096. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  3097. if (expressionsToBeDeoptimized) {
  3098. for (const expression of expressionsToBeDeoptimized) {
  3099. expression.deoptimizeCache();
  3100. }
  3101. }
  3102. }
  3103. }
  3104. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  3105. for (const property of typeof key === 'string'
  3106. ? [
  3107. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  3108. ...(this.settersByKey[key] || this.unmatchableSetters)
  3109. ]
  3110. : this.allProperties) {
  3111. property.deoptimizePath(subPath);
  3112. }
  3113. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [path[0], UnknownKey] : path);
  3114. }
  3115. getLiteralValueAtPath(path, recursionTracker, origin) {
  3116. if (path.length === 0) {
  3117. // This should actually be "UnknownTruthyValue". However, this currently
  3118. // causes an issue with TypeScript enums in files with moduleSideEffects:
  3119. // false because we cannot properly track whether a "var" has been
  3120. // initialized. This should be reverted once we can properly track this.
  3121. // return UnknownTruthyValue;
  3122. return UnknownValue;
  3123. }
  3124. const key = path[0];
  3125. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  3126. if (expressionAtPath) {
  3127. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  3128. }
  3129. if (this.prototypeExpression) {
  3130. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  3131. }
  3132. if (path.length === 1) {
  3133. return undefined;
  3134. }
  3135. return UnknownValue;
  3136. }
  3137. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  3138. if (path.length === 0) {
  3139. return UNKNOWN_RETURN_EXPRESSION;
  3140. }
  3141. const [key, ...subPath] = path;
  3142. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  3143. if (expressionAtPath) {
  3144. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  3145. }
  3146. if (this.prototypeExpression) {
  3147. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  3148. }
  3149. return UNKNOWN_RETURN_EXPRESSION;
  3150. }
  3151. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3152. const [key, ...subPath] = path;
  3153. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  3154. const expressionAtPath = this.getMemberExpression(key);
  3155. if (expressionAtPath) {
  3156. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  3157. }
  3158. if (this.prototypeExpression) {
  3159. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  3160. }
  3161. return true;
  3162. }
  3163. if (key === UnknownNonAccessorKey)
  3164. return false;
  3165. if (this.hasLostTrack)
  3166. return true;
  3167. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  3168. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  3169. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  3170. if (typeof key === 'string') {
  3171. if (propertiesAndAccessorsByKey[key]) {
  3172. const accessors = accessorsByKey[key];
  3173. if (accessors) {
  3174. for (const accessor of accessors) {
  3175. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  3176. return true;
  3177. }
  3178. }
  3179. return false;
  3180. }
  3181. for (const accessor of unmatchableAccessors) {
  3182. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  3183. return true;
  3184. }
  3185. }
  3186. }
  3187. else {
  3188. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  3189. for (const accessor of accessors) {
  3190. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  3191. return true;
  3192. }
  3193. }
  3194. }
  3195. if (this.prototypeExpression) {
  3196. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  3197. }
  3198. return false;
  3199. }
  3200. include(context, includeChildrenRecursively) {
  3201. this.included = true;
  3202. for (const property of this.allProperties) {
  3203. if (includeChildrenRecursively || property.shouldBeIncluded(context)) {
  3204. property.include(context, includeChildrenRecursively);
  3205. }
  3206. }
  3207. this.prototypeExpression?.include(context, includeChildrenRecursively);
  3208. }
  3209. includePath(path, context) {
  3210. this.included = true;
  3211. if (path.length === 0)
  3212. return;
  3213. const [key, ...subPath] = path;
  3214. const [includedMembers, includedPath] = typeof key === 'string'
  3215. ? [
  3216. new Set([
  3217. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  3218. ...(this.propertiesAndSettersByKey[key] || this.unmatchablePropertiesAndSetters)
  3219. ]),
  3220. subPath
  3221. ]
  3222. : [this.allProperties, UNKNOWN_PATH];
  3223. for (const property of includedMembers) {
  3224. property.includePath(includedPath, context);
  3225. }
  3226. this.prototypeExpression?.includePath(path, context);
  3227. }
  3228. buildPropertyMaps(properties) {
  3229. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchablePropertiesAndSetters, unmatchableGetters, unmatchableSetters } = this;
  3230. for (let index = properties.length - 1; index >= 0; index--) {
  3231. const { key, kind, property } = properties[index];
  3232. allProperties.push(property);
  3233. if (typeof key === 'string') {
  3234. if (kind === 'set') {
  3235. if (!propertiesAndSettersByKey[key]) {
  3236. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  3237. settersByKey[key] = [property, ...unmatchableSetters];
  3238. }
  3239. }
  3240. else if (kind === 'get') {
  3241. if (!propertiesAndGettersByKey[key]) {
  3242. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  3243. gettersByKey[key] = [property, ...unmatchableGetters];
  3244. }
  3245. }
  3246. else {
  3247. if (!propertiesAndSettersByKey[key]) {
  3248. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  3249. }
  3250. if (!propertiesAndGettersByKey[key]) {
  3251. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  3252. }
  3253. }
  3254. }
  3255. else {
  3256. if (key === UnknownInteger) {
  3257. unknownIntegerProps.push(property);
  3258. continue;
  3259. }
  3260. if (kind === 'set')
  3261. unmatchableSetters.push(property);
  3262. if (kind === 'get')
  3263. unmatchableGetters.push(property);
  3264. if (kind !== 'get')
  3265. unmatchablePropertiesAndSetters.push(property);
  3266. if (kind !== 'set')
  3267. unmatchablePropertiesAndGetters.push(property);
  3268. }
  3269. }
  3270. }
  3271. deoptimizeCachedEntities() {
  3272. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  3273. for (const expression of expressionsToBeDeoptimized) {
  3274. expression.deoptimizeCache();
  3275. }
  3276. }
  3277. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  3278. expression.deoptimizePath(UNKNOWN_PATH);
  3279. }
  3280. }
  3281. deoptimizeCachedIntegerEntities() {
  3282. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  3283. if (INTEGER_REG_EXP.test(key)) {
  3284. for (const expression of expressionsToBeDeoptimized) {
  3285. expression.deoptimizeCache();
  3286. }
  3287. }
  3288. }
  3289. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  3290. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  3291. }
  3292. }
  3293. getMemberExpression(key) {
  3294. if (this.hasLostTrack ||
  3295. this.hasUnknownDeoptimizedProperty ||
  3296. typeof key !== 'string' ||
  3297. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  3298. this.deoptimizedPaths[key]) {
  3299. return UNKNOWN_EXPRESSION;
  3300. }
  3301. const properties = this.propertiesAndGettersByKey[key];
  3302. if (properties?.length === 1) {
  3303. return properties[0];
  3304. }
  3305. if (properties ||
  3306. this.unmatchablePropertiesAndGetters.length > 0 ||
  3307. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  3308. return UNKNOWN_EXPRESSION;
  3309. }
  3310. return null;
  3311. }
  3312. getMemberExpressionAndTrackDeopt(key, origin) {
  3313. if (typeof key !== 'string') {
  3314. return UNKNOWN_EXPRESSION;
  3315. }
  3316. const expression = this.getMemberExpression(key);
  3317. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  3318. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  3319. this.expressionsToBeDeoptimizedByKey[key] || []);
  3320. expressionsToBeDeoptimized.push(origin);
  3321. }
  3322. return expression;
  3323. }
  3324. }
  3325. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  3326. // This makes sure unknown properties are not handled as "undefined" but as
  3327. // "unknown" but without access side effects. An exception is done for numeric
  3328. // properties as we do not expect new builtin properties to be numbers, this
  3329. // will improve tree-shaking for out-of-bounds array properties
  3330. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  3331. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  3332. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  3333. deoptimizeInteraction(interaction);
  3334. }
  3335. }
  3336. getLiteralValueAtPath(path) {
  3337. // We ignore number properties as we do not expect new properties to be
  3338. // numbers and also want to keep handling out-of-bound array elements as
  3339. // "undefined"
  3340. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  3341. }
  3342. hasEffectsOnInteractionAtPath(path, { type }) {
  3343. return path.length > 1 || type === INTERACTION_CALLED;
  3344. }
  3345. })();
  3346. const OBJECT_PROTOTYPE = new ObjectEntity({
  3347. __proto__: null,
  3348. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  3349. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  3350. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  3351. toLocaleString: METHOD_RETURNS_STRING,
  3352. toString: METHOD_RETURNS_STRING,
  3353. valueOf: METHOD_RETURNS_UNKNOWN
  3354. }, OBJECT_PROTOTYPE_FALLBACK, true);
  3355. const NEW_ARRAY_PROPERTIES = [
  3356. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  3357. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  3358. ];
  3359. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  3360. new Method({
  3361. callsArgs: [0],
  3362. mutatesArgs: false,
  3363. mutatesSelfAsArray: 'deopt-only',
  3364. returns: null,
  3365. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  3366. })
  3367. ];
  3368. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  3369. new Method({
  3370. callsArgs: [0],
  3371. mutatesArgs: false,
  3372. mutatesSelfAsArray: 'deopt-only',
  3373. returns: null,
  3374. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  3375. })
  3376. ];
  3377. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  3378. new Method({
  3379. callsArgs: null,
  3380. mutatesArgs: false,
  3381. mutatesSelfAsArray: true,
  3382. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3383. returnsPrimitive: null
  3384. })
  3385. ];
  3386. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  3387. new Method({
  3388. callsArgs: null,
  3389. mutatesArgs: false,
  3390. mutatesSelfAsArray: 'deopt-only',
  3391. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3392. returnsPrimitive: null
  3393. })
  3394. ];
  3395. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  3396. new Method({
  3397. callsArgs: [0],
  3398. mutatesArgs: false,
  3399. mutatesSelfAsArray: 'deopt-only',
  3400. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3401. returnsPrimitive: null
  3402. })
  3403. ];
  3404. const METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER = [
  3405. new Method({
  3406. callsArgs: null,
  3407. mutatesArgs: true,
  3408. mutatesSelfAsArray: true,
  3409. returns: null,
  3410. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  3411. })
  3412. ];
  3413. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  3414. new Method({
  3415. callsArgs: null,
  3416. mutatesArgs: false,
  3417. mutatesSelfAsArray: true,
  3418. returns: null,
  3419. returnsPrimitive: UNKNOWN_EXPRESSION
  3420. })
  3421. ];
  3422. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  3423. new Method({
  3424. callsArgs: null,
  3425. mutatesArgs: false,
  3426. mutatesSelfAsArray: 'deopt-only',
  3427. returns: null,
  3428. returnsPrimitive: UNKNOWN_EXPRESSION
  3429. })
  3430. ];
  3431. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  3432. new Method({
  3433. callsArgs: [0],
  3434. mutatesArgs: false,
  3435. mutatesSelfAsArray: 'deopt-only',
  3436. returns: null,
  3437. returnsPrimitive: UNKNOWN_EXPRESSION
  3438. })
  3439. ];
  3440. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  3441. new Method({
  3442. callsArgs: null,
  3443. mutatesArgs: false,
  3444. mutatesSelfAsArray: true,
  3445. returns: 'self',
  3446. returnsPrimitive: null
  3447. })
  3448. ];
  3449. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  3450. new Method({
  3451. callsArgs: [0],
  3452. mutatesArgs: false,
  3453. mutatesSelfAsArray: true,
  3454. returns: 'self',
  3455. returnsPrimitive: null
  3456. })
  3457. ];
  3458. const ARRAY_PROTOTYPE = new ObjectEntity({
  3459. __proto__: null,
  3460. // We assume that accessors have effects as we do not track the accessed value afterwards
  3461. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  3462. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3463. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  3464. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3465. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  3466. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  3467. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3468. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3469. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  3470. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3471. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  3472. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3473. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3474. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3475. includes: METHOD_RETURNS_BOOLEAN,
  3476. indexOf: METHOD_RETURNS_NUMBER,
  3477. join: METHOD_RETURNS_STRING,
  3478. keys: METHOD_RETURNS_UNKNOWN,
  3479. lastIndexOf: METHOD_RETURNS_NUMBER,
  3480. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3481. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  3482. push: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  3483. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3484. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3485. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  3486. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  3487. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3488. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  3489. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  3490. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  3491. toLocaleString: METHOD_RETURNS_STRING,
  3492. toString: METHOD_RETURNS_STRING,
  3493. unshift: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  3494. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  3495. }, OBJECT_PROTOTYPE, true);
  3496. class SpreadElement extends NodeBase {
  3497. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  3498. if (path.length > 0) {
  3499. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, UNKNOWN_PATH, recursionTracker);
  3500. }
  3501. }
  3502. hasEffects(context) {
  3503. if (!this.deoptimized)
  3504. this.applyDeoptimizations();
  3505. const { propertyReadSideEffects } = this.scope.context.options
  3506. .treeshake;
  3507. return (this.argument.hasEffects(context) ||
  3508. (propertyReadSideEffects &&
  3509. (propertyReadSideEffects === 'always' ||
  3510. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  3511. }
  3512. includeNode(context) {
  3513. this.included = true;
  3514. if (!this.deoptimized)
  3515. this.applyDeoptimizations();
  3516. this.argument.includePath(UNKNOWN_PATH, context);
  3517. }
  3518. applyDeoptimizations() {
  3519. this.deoptimized = true;
  3520. // Only properties of properties of the argument could become subject to reassignment
  3521. // This will also reassign the return values of iterators
  3522. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  3523. this.scope.context.requestTreeshakingPass();
  3524. }
  3525. }
  3526. class ArrayExpression extends NodeBase {
  3527. constructor() {
  3528. super(...arguments);
  3529. this.objectEntity = null;
  3530. }
  3531. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  3532. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  3533. }
  3534. deoptimizePath(path) {
  3535. this.getObjectEntity().deoptimizePath(path);
  3536. }
  3537. getLiteralValueAtPath(path, recursionTracker, origin) {
  3538. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  3539. }
  3540. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  3541. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  3542. }
  3543. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3544. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  3545. }
  3546. includeNode(context) {
  3547. this.included = true;
  3548. if (!this.deoptimized)
  3549. this.applyDeoptimizations();
  3550. for (const element of this.elements) {
  3551. if (element) {
  3552. element?.includePath(UNKNOWN_PATH, context);
  3553. }
  3554. }
  3555. }
  3556. applyDeoptimizations() {
  3557. this.deoptimized = true;
  3558. let hasSpread = false;
  3559. for (let index = 0; index < this.elements.length; index++) {
  3560. const element = this.elements[index];
  3561. if (element && (hasSpread || element instanceof SpreadElement)) {
  3562. hasSpread = true;
  3563. element.deoptimizePath(UNKNOWN_PATH);
  3564. }
  3565. }
  3566. this.scope.context.requestTreeshakingPass();
  3567. }
  3568. getObjectEntity() {
  3569. if (this.objectEntity !== null) {
  3570. return this.objectEntity;
  3571. }
  3572. const properties = [
  3573. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  3574. ];
  3575. let hasSpread = false;
  3576. for (let index = 0; index < this.elements.length; index++) {
  3577. const element = this.elements[index];
  3578. if (hasSpread || element instanceof SpreadElement) {
  3579. if (element) {
  3580. hasSpread = true;
  3581. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  3582. }
  3583. }
  3584. else if (element) {
  3585. properties.push({ key: String(index), kind: 'init', property: element });
  3586. }
  3587. else {
  3588. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  3589. }
  3590. }
  3591. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  3592. }
  3593. }
  3594. /* eslint sort-keys: "off" */
  3595. const ValueProperties = Symbol('Value Properties');
  3596. const getUnknownValue = () => UnknownValue;
  3597. const returnFalse = () => false;
  3598. const returnTrue = () => true;
  3599. const PURE = {
  3600. deoptimizeArgumentsOnCall: doNothing,
  3601. getLiteralValue: getUnknownValue,
  3602. hasEffectsWhenCalled: returnFalse
  3603. };
  3604. const IMPURE = {
  3605. deoptimizeArgumentsOnCall: doNothing,
  3606. getLiteralValue: getUnknownValue,
  3607. hasEffectsWhenCalled: returnTrue
  3608. };
  3609. const PURE_WITH_ARRAY = {
  3610. deoptimizeArgumentsOnCall: doNothing,
  3611. getLiteralValue: getUnknownValue,
  3612. hasEffectsWhenCalled({ args }) {
  3613. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  3614. }
  3615. };
  3616. const GETTER_ACCESS = {
  3617. deoptimizeArgumentsOnCall: doNothing,
  3618. getLiteralValue: getUnknownValue,
  3619. hasEffectsWhenCalled({ args }, context) {
  3620. const [_thisArgument, firstArgument] = args;
  3621. return (!(firstArgument instanceof ExpressionEntity) ||
  3622. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  3623. }
  3624. };
  3625. // We use shortened variables to reduce file size here
  3626. /* OBJECT */
  3627. const O = {
  3628. __proto__: null,
  3629. [ValueProperties]: IMPURE
  3630. };
  3631. /* PURE FUNCTION */
  3632. const PF = {
  3633. __proto__: null,
  3634. [ValueProperties]: PURE
  3635. };
  3636. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  3637. const PF_NO_GETTER = {
  3638. __proto__: null,
  3639. [ValueProperties]: GETTER_ACCESS
  3640. };
  3641. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  3642. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  3643. __proto__: null,
  3644. [ValueProperties]: {
  3645. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  3646. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  3647. },
  3648. getLiteralValue: getUnknownValue,
  3649. hasEffectsWhenCalled({ args }, context) {
  3650. return (args.length <= 1 ||
  3651. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  3652. }
  3653. }
  3654. };
  3655. /* CONSTRUCTOR */
  3656. const C = {
  3657. __proto__: null,
  3658. [ValueProperties]: IMPURE,
  3659. prototype: O
  3660. };
  3661. /* PURE CONSTRUCTOR */
  3662. const PC = {
  3663. __proto__: null,
  3664. [ValueProperties]: PURE,
  3665. prototype: O
  3666. };
  3667. const PC_WITH_ARRAY = {
  3668. __proto__: null,
  3669. [ValueProperties]: PURE_WITH_ARRAY,
  3670. prototype: O
  3671. };
  3672. const ARRAY_TYPE = {
  3673. __proto__: null,
  3674. [ValueProperties]: PURE,
  3675. from: O,
  3676. of: PF,
  3677. prototype: O
  3678. };
  3679. const INTL_MEMBER = {
  3680. __proto__: null,
  3681. [ValueProperties]: PURE,
  3682. supportedLocalesOf: PC
  3683. };
  3684. const knownGlobals = {
  3685. // Placeholders for global objects to avoid shape mutations
  3686. global: O,
  3687. globalThis: O,
  3688. self: O,
  3689. window: O,
  3690. // Common globals
  3691. __proto__: null,
  3692. [ValueProperties]: IMPURE,
  3693. Array: {
  3694. __proto__: null,
  3695. [ValueProperties]: IMPURE,
  3696. from: O,
  3697. isArray: PF,
  3698. of: PF,
  3699. prototype: O
  3700. },
  3701. ArrayBuffer: {
  3702. __proto__: null,
  3703. [ValueProperties]: PURE,
  3704. isView: PF,
  3705. prototype: O
  3706. },
  3707. AggregateError: PC_WITH_ARRAY,
  3708. Atomics: O,
  3709. BigInt: C,
  3710. BigInt64Array: C,
  3711. BigUint64Array: C,
  3712. Boolean: PC,
  3713. constructor: C,
  3714. DataView: PC,
  3715. Date: {
  3716. __proto__: null,
  3717. [ValueProperties]: PURE,
  3718. now: PF,
  3719. parse: PF,
  3720. prototype: O,
  3721. UTC: PF
  3722. },
  3723. decodeURI: PF,
  3724. decodeURIComponent: PF,
  3725. encodeURI: PF,
  3726. encodeURIComponent: PF,
  3727. Error: PC,
  3728. escape: PF,
  3729. eval: O,
  3730. EvalError: PC,
  3731. FinalizationRegistry: C,
  3732. Float32Array: ARRAY_TYPE,
  3733. Float64Array: ARRAY_TYPE,
  3734. Function: C,
  3735. hasOwnProperty: O,
  3736. Infinity: O,
  3737. Int16Array: ARRAY_TYPE,
  3738. Int32Array: ARRAY_TYPE,
  3739. Int8Array: ARRAY_TYPE,
  3740. isFinite: PF,
  3741. isNaN: PF,
  3742. isPrototypeOf: O,
  3743. JSON: O,
  3744. Map: PC_WITH_ARRAY,
  3745. Math: {
  3746. __proto__: null,
  3747. [ValueProperties]: IMPURE,
  3748. abs: PF,
  3749. acos: PF,
  3750. acosh: PF,
  3751. asin: PF,
  3752. asinh: PF,
  3753. atan: PF,
  3754. atan2: PF,
  3755. atanh: PF,
  3756. cbrt: PF,
  3757. ceil: PF,
  3758. clz32: PF,
  3759. cos: PF,
  3760. cosh: PF,
  3761. exp: PF,
  3762. expm1: PF,
  3763. floor: PF,
  3764. fround: PF,
  3765. hypot: PF,
  3766. imul: PF,
  3767. log: PF,
  3768. log10: PF,
  3769. log1p: PF,
  3770. log2: PF,
  3771. max: PF,
  3772. min: PF,
  3773. pow: PF,
  3774. random: PF,
  3775. round: PF,
  3776. sign: PF,
  3777. sin: PF,
  3778. sinh: PF,
  3779. sqrt: PF,
  3780. tan: PF,
  3781. tanh: PF,
  3782. trunc: PF
  3783. },
  3784. NaN: O,
  3785. Number: {
  3786. __proto__: null,
  3787. [ValueProperties]: PURE,
  3788. isFinite: PF,
  3789. isInteger: PF,
  3790. isNaN: PF,
  3791. isSafeInteger: PF,
  3792. parseFloat: PF,
  3793. parseInt: PF,
  3794. prototype: O
  3795. },
  3796. Object: {
  3797. __proto__: null,
  3798. [ValueProperties]: PURE,
  3799. create: PF,
  3800. // Technically those can throw in certain situations, but we ignore this as
  3801. // code that relies on this will hopefully wrap this in a try-catch, which
  3802. // deoptimizes everything anyway
  3803. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  3804. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  3805. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  3806. getOwnPropertyDescriptor: PF,
  3807. getOwnPropertyDescriptors: PF,
  3808. getOwnPropertyNames: PF,
  3809. getOwnPropertySymbols: PF,
  3810. getPrototypeOf: PF,
  3811. hasOwn: PF,
  3812. is: PF,
  3813. isExtensible: PF,
  3814. isFrozen: PF,
  3815. isSealed: PF,
  3816. keys: PF,
  3817. fromEntries: O,
  3818. entries: PF_NO_GETTER,
  3819. values: PF_NO_GETTER,
  3820. prototype: O
  3821. },
  3822. parseFloat: PF,
  3823. parseInt: PF,
  3824. Promise: {
  3825. __proto__: null,
  3826. [ValueProperties]: IMPURE,
  3827. all: O,
  3828. allSettled: O,
  3829. any: O,
  3830. prototype: O,
  3831. race: O,
  3832. reject: O,
  3833. resolve: O
  3834. },
  3835. propertyIsEnumerable: O,
  3836. Proxy: {
  3837. __proto__: null,
  3838. [ValueProperties]: {
  3839. deoptimizeArgumentsOnCall: ({ args: [, target, parameter] }) => {
  3840. if (isObjectExpressionNode(parameter)) {
  3841. const hasSpreadElement = parameter.properties.some(property => !isPropertyNode(property));
  3842. if (!hasSpreadElement) {
  3843. for (const property of parameter.properties) {
  3844. property.deoptimizeArgumentsOnInteractionAtPath({
  3845. args: [null, target],
  3846. type: INTERACTION_CALLED,
  3847. withNew: false
  3848. }, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  3849. }
  3850. return;
  3851. }
  3852. }
  3853. target.deoptimizePath(UNKNOWN_PATH);
  3854. },
  3855. getLiteralValue: getUnknownValue,
  3856. hasEffectsWhenCalled: returnTrue
  3857. }
  3858. },
  3859. RangeError: PC,
  3860. ReferenceError: PC,
  3861. Reflect: O,
  3862. RegExp: PC,
  3863. Set: PC_WITH_ARRAY,
  3864. SharedArrayBuffer: C,
  3865. String: {
  3866. __proto__: null,
  3867. [ValueProperties]: PURE,
  3868. fromCharCode: PF,
  3869. fromCodePoint: PF,
  3870. prototype: O,
  3871. raw: PF
  3872. },
  3873. Symbol: {
  3874. __proto__: null,
  3875. [ValueProperties]: PURE,
  3876. for: PF,
  3877. keyFor: PF,
  3878. prototype: O,
  3879. toStringTag: {
  3880. __proto__: null,
  3881. [ValueProperties]: {
  3882. deoptimizeArgumentsOnCall: doNothing,
  3883. getLiteralValue() {
  3884. return SymbolToStringTag;
  3885. },
  3886. hasEffectsWhenCalled: returnTrue
  3887. }
  3888. }
  3889. },
  3890. SyntaxError: PC,
  3891. toLocaleString: O,
  3892. toString: O,
  3893. TypeError: PC,
  3894. Uint16Array: ARRAY_TYPE,
  3895. Uint32Array: ARRAY_TYPE,
  3896. Uint8Array: ARRAY_TYPE,
  3897. Uint8ClampedArray: ARRAY_TYPE,
  3898. // Technically, this is a global, but it needs special handling
  3899. // undefined: ?,
  3900. unescape: PF,
  3901. URIError: PC,
  3902. valueOf: O,
  3903. WeakMap: PC_WITH_ARRAY,
  3904. WeakRef: C,
  3905. WeakSet: PC_WITH_ARRAY,
  3906. // Additional globals shared by Node and Browser that are not strictly part of the language
  3907. clearInterval: C,
  3908. clearTimeout: C,
  3909. console: {
  3910. __proto__: null,
  3911. [ValueProperties]: IMPURE,
  3912. assert: C,
  3913. clear: C,
  3914. count: C,
  3915. countReset: C,
  3916. debug: C,
  3917. dir: C,
  3918. dirxml: C,
  3919. error: C,
  3920. exception: C,
  3921. group: C,
  3922. groupCollapsed: C,
  3923. groupEnd: C,
  3924. info: C,
  3925. log: C,
  3926. table: C,
  3927. time: C,
  3928. timeEnd: C,
  3929. timeLog: C,
  3930. trace: C,
  3931. warn: C
  3932. },
  3933. Intl: {
  3934. __proto__: null,
  3935. [ValueProperties]: IMPURE,
  3936. Collator: INTL_MEMBER,
  3937. DateTimeFormat: INTL_MEMBER,
  3938. DisplayNames: INTL_MEMBER,
  3939. ListFormat: INTL_MEMBER,
  3940. Locale: INTL_MEMBER,
  3941. NumberFormat: INTL_MEMBER,
  3942. PluralRules: INTL_MEMBER,
  3943. RelativeTimeFormat: INTL_MEMBER,
  3944. Segmenter: INTL_MEMBER
  3945. },
  3946. setInterval: C,
  3947. setTimeout: C,
  3948. TextDecoder: C,
  3949. TextEncoder: C,
  3950. URL: {
  3951. __proto__: null,
  3952. [ValueProperties]: IMPURE,
  3953. prototype: O,
  3954. canParse: PF
  3955. },
  3956. URLSearchParams: C,
  3957. // Browser specific globals
  3958. AbortController: C,
  3959. AbortSignal: C,
  3960. addEventListener: O,
  3961. alert: O,
  3962. AnalyserNode: C,
  3963. Animation: C,
  3964. AnimationEvent: C,
  3965. applicationCache: O,
  3966. ApplicationCache: C,
  3967. ApplicationCacheErrorEvent: C,
  3968. atob: O,
  3969. Attr: C,
  3970. Audio: C,
  3971. AudioBuffer: C,
  3972. AudioBufferSourceNode: C,
  3973. AudioContext: C,
  3974. AudioDestinationNode: C,
  3975. AudioListener: C,
  3976. AudioNode: C,
  3977. AudioParam: C,
  3978. AudioProcessingEvent: C,
  3979. AudioScheduledSourceNode: C,
  3980. AudioWorkletNode: C,
  3981. BarProp: C,
  3982. BaseAudioContext: C,
  3983. BatteryManager: C,
  3984. BeforeUnloadEvent: C,
  3985. BiquadFilterNode: C,
  3986. Blob: C,
  3987. BlobEvent: C,
  3988. blur: O,
  3989. BroadcastChannel: C,
  3990. btoa: O,
  3991. ByteLengthQueuingStrategy: C,
  3992. Cache: C,
  3993. caches: O,
  3994. CacheStorage: C,
  3995. cancelAnimationFrame: O,
  3996. cancelIdleCallback: O,
  3997. CanvasCaptureMediaStreamTrack: C,
  3998. CanvasGradient: C,
  3999. CanvasPattern: C,
  4000. CanvasRenderingContext2D: C,
  4001. ChannelMergerNode: C,
  4002. ChannelSplitterNode: C,
  4003. CharacterData: C,
  4004. clientInformation: O,
  4005. ClipboardEvent: C,
  4006. close: O,
  4007. closed: O,
  4008. CloseEvent: C,
  4009. Comment: C,
  4010. CompositionEvent: C,
  4011. confirm: O,
  4012. ConstantSourceNode: C,
  4013. ConvolverNode: C,
  4014. CountQueuingStrategy: C,
  4015. createImageBitmap: O,
  4016. Credential: C,
  4017. CredentialsContainer: C,
  4018. crypto: O,
  4019. Crypto: C,
  4020. CryptoKey: C,
  4021. CSS: C,
  4022. CSSConditionRule: C,
  4023. CSSFontFaceRule: C,
  4024. CSSGroupingRule: C,
  4025. CSSImportRule: C,
  4026. CSSKeyframeRule: C,
  4027. CSSKeyframesRule: C,
  4028. CSSMediaRule: C,
  4029. CSSNamespaceRule: C,
  4030. CSSPageRule: C,
  4031. CSSRule: C,
  4032. CSSRuleList: C,
  4033. CSSStyleDeclaration: C,
  4034. CSSStyleRule: C,
  4035. CSSStyleSheet: C,
  4036. CSSSupportsRule: C,
  4037. CustomElementRegistry: C,
  4038. customElements: O,
  4039. CustomEvent: {
  4040. __proto__: null,
  4041. [ValueProperties]: {
  4042. deoptimizeArgumentsOnCall({ args }) {
  4043. args[2]?.deoptimizePath(['detail']);
  4044. },
  4045. getLiteralValue: getUnknownValue,
  4046. hasEffectsWhenCalled: returnFalse
  4047. },
  4048. prototype: O
  4049. },
  4050. DataTransfer: C,
  4051. DataTransferItem: C,
  4052. DataTransferItemList: C,
  4053. defaultstatus: O,
  4054. defaultStatus: O,
  4055. DelayNode: C,
  4056. DeviceMotionEvent: C,
  4057. DeviceOrientationEvent: C,
  4058. devicePixelRatio: O,
  4059. dispatchEvent: O,
  4060. document: O,
  4061. Document: C,
  4062. DocumentFragment: C,
  4063. DocumentType: C,
  4064. DOMError: C,
  4065. DOMException: C,
  4066. DOMImplementation: C,
  4067. DOMMatrix: C,
  4068. DOMMatrixReadOnly: C,
  4069. DOMParser: C,
  4070. DOMPoint: C,
  4071. DOMPointReadOnly: C,
  4072. DOMQuad: C,
  4073. DOMRect: C,
  4074. DOMRectReadOnly: C,
  4075. DOMStringList: C,
  4076. DOMStringMap: C,
  4077. DOMTokenList: C,
  4078. DragEvent: C,
  4079. DynamicsCompressorNode: C,
  4080. Element: C,
  4081. ErrorEvent: C,
  4082. Event: C,
  4083. EventSource: C,
  4084. EventTarget: C,
  4085. external: O,
  4086. fetch: O,
  4087. File: C,
  4088. FileList: C,
  4089. FileReader: C,
  4090. find: O,
  4091. focus: O,
  4092. FocusEvent: C,
  4093. FontFace: C,
  4094. FontFaceSetLoadEvent: C,
  4095. FormData: C,
  4096. frames: O,
  4097. GainNode: C,
  4098. Gamepad: C,
  4099. GamepadButton: C,
  4100. GamepadEvent: C,
  4101. getComputedStyle: O,
  4102. getSelection: O,
  4103. HashChangeEvent: C,
  4104. Headers: C,
  4105. history: O,
  4106. History: C,
  4107. HTMLAllCollection: C,
  4108. HTMLAnchorElement: C,
  4109. HTMLAreaElement: C,
  4110. HTMLAudioElement: C,
  4111. HTMLBaseElement: C,
  4112. HTMLBodyElement: C,
  4113. HTMLBRElement: C,
  4114. HTMLButtonElement: C,
  4115. HTMLCanvasElement: C,
  4116. HTMLCollection: C,
  4117. HTMLContentElement: C,
  4118. HTMLDataElement: C,
  4119. HTMLDataListElement: C,
  4120. HTMLDetailsElement: C,
  4121. HTMLDialogElement: C,
  4122. HTMLDirectoryElement: C,
  4123. HTMLDivElement: C,
  4124. HTMLDListElement: C,
  4125. HTMLDocument: C,
  4126. HTMLElement: C,
  4127. HTMLEmbedElement: C,
  4128. HTMLFieldSetElement: C,
  4129. HTMLFontElement: C,
  4130. HTMLFormControlsCollection: C,
  4131. HTMLFormElement: C,
  4132. HTMLFrameElement: C,
  4133. HTMLFrameSetElement: C,
  4134. HTMLHeadElement: C,
  4135. HTMLHeadingElement: C,
  4136. HTMLHRElement: C,
  4137. HTMLHtmlElement: C,
  4138. HTMLIFrameElement: C,
  4139. HTMLImageElement: C,
  4140. HTMLInputElement: C,
  4141. HTMLLabelElement: C,
  4142. HTMLLegendElement: C,
  4143. HTMLLIElement: C,
  4144. HTMLLinkElement: C,
  4145. HTMLMapElement: C,
  4146. HTMLMarqueeElement: C,
  4147. HTMLMediaElement: C,
  4148. HTMLMenuElement: C,
  4149. HTMLMetaElement: C,
  4150. HTMLMeterElement: C,
  4151. HTMLModElement: C,
  4152. HTMLObjectElement: C,
  4153. HTMLOListElement: C,
  4154. HTMLOptGroupElement: C,
  4155. HTMLOptionElement: C,
  4156. HTMLOptionsCollection: C,
  4157. HTMLOutputElement: C,
  4158. HTMLParagraphElement: C,
  4159. HTMLParamElement: C,
  4160. HTMLPictureElement: C,
  4161. HTMLPreElement: C,
  4162. HTMLProgressElement: C,
  4163. HTMLQuoteElement: C,
  4164. HTMLScriptElement: C,
  4165. HTMLSelectElement: C,
  4166. HTMLShadowElement: C,
  4167. HTMLSlotElement: C,
  4168. HTMLSourceElement: C,
  4169. HTMLSpanElement: C,
  4170. HTMLStyleElement: C,
  4171. HTMLTableCaptionElement: C,
  4172. HTMLTableCellElement: C,
  4173. HTMLTableColElement: C,
  4174. HTMLTableElement: C,
  4175. HTMLTableRowElement: C,
  4176. HTMLTableSectionElement: C,
  4177. HTMLTemplateElement: C,
  4178. HTMLTextAreaElement: C,
  4179. HTMLTimeElement: C,
  4180. HTMLTitleElement: C,
  4181. HTMLTrackElement: C,
  4182. HTMLUListElement: C,
  4183. HTMLUnknownElement: C,
  4184. HTMLVideoElement: C,
  4185. IDBCursor: C,
  4186. IDBCursorWithValue: C,
  4187. IDBDatabase: C,
  4188. IDBFactory: C,
  4189. IDBIndex: C,
  4190. IDBKeyRange: C,
  4191. IDBObjectStore: C,
  4192. IDBOpenDBRequest: C,
  4193. IDBRequest: C,
  4194. IDBTransaction: C,
  4195. IDBVersionChangeEvent: C,
  4196. IdleDeadline: C,
  4197. IIRFilterNode: C,
  4198. Image: C,
  4199. ImageBitmap: C,
  4200. ImageBitmapRenderingContext: C,
  4201. ImageCapture: C,
  4202. ImageData: C,
  4203. indexedDB: O,
  4204. innerHeight: O,
  4205. innerWidth: O,
  4206. InputEvent: C,
  4207. IntersectionObserver: C,
  4208. IntersectionObserverEntry: C,
  4209. isSecureContext: O,
  4210. KeyboardEvent: C,
  4211. KeyframeEffect: C,
  4212. length: O,
  4213. localStorage: O,
  4214. location: O,
  4215. Location: C,
  4216. locationbar: O,
  4217. matchMedia: O,
  4218. MediaDeviceInfo: C,
  4219. MediaDevices: C,
  4220. MediaElementAudioSourceNode: C,
  4221. MediaEncryptedEvent: C,
  4222. MediaError: C,
  4223. MediaKeyMessageEvent: C,
  4224. MediaKeySession: C,
  4225. MediaKeyStatusMap: C,
  4226. MediaKeySystemAccess: C,
  4227. MediaList: C,
  4228. MediaQueryList: C,
  4229. MediaQueryListEvent: C,
  4230. MediaRecorder: C,
  4231. MediaSettingsRange: C,
  4232. MediaSource: C,
  4233. MediaStream: C,
  4234. MediaStreamAudioDestinationNode: C,
  4235. MediaStreamAudioSourceNode: C,
  4236. MediaStreamEvent: C,
  4237. MediaStreamTrack: C,
  4238. MediaStreamTrackEvent: C,
  4239. menubar: O,
  4240. MessageChannel: C,
  4241. MessageEvent: C,
  4242. MessagePort: C,
  4243. MIDIAccess: C,
  4244. MIDIConnectionEvent: C,
  4245. MIDIInput: C,
  4246. MIDIInputMap: C,
  4247. MIDIMessageEvent: C,
  4248. MIDIOutput: C,
  4249. MIDIOutputMap: C,
  4250. MIDIPort: C,
  4251. MimeType: C,
  4252. MimeTypeArray: C,
  4253. MouseEvent: C,
  4254. moveBy: O,
  4255. moveTo: O,
  4256. MutationEvent: C,
  4257. MutationObserver: C,
  4258. MutationRecord: C,
  4259. name: O,
  4260. NamedNodeMap: C,
  4261. NavigationPreloadManager: C,
  4262. navigator: O,
  4263. Navigator: C,
  4264. NetworkInformation: C,
  4265. Node: C,
  4266. NodeFilter: O,
  4267. NodeIterator: C,
  4268. NodeList: C,
  4269. Notification: C,
  4270. OfflineAudioCompletionEvent: C,
  4271. OfflineAudioContext: C,
  4272. offscreenBuffering: O,
  4273. OffscreenCanvas: C,
  4274. open: O,
  4275. openDatabase: O,
  4276. Option: C,
  4277. origin: O,
  4278. OscillatorNode: C,
  4279. outerHeight: O,
  4280. outerWidth: O,
  4281. PageTransitionEvent: C,
  4282. pageXOffset: O,
  4283. pageYOffset: O,
  4284. PannerNode: C,
  4285. parent: O,
  4286. Path2D: C,
  4287. PaymentAddress: C,
  4288. PaymentRequest: C,
  4289. PaymentRequestUpdateEvent: C,
  4290. PaymentResponse: C,
  4291. performance: O,
  4292. Performance: C,
  4293. PerformanceEntry: C,
  4294. PerformanceLongTaskTiming: C,
  4295. PerformanceMark: C,
  4296. PerformanceMeasure: C,
  4297. PerformanceNavigation: C,
  4298. PerformanceNavigationTiming: C,
  4299. PerformanceObserver: C,
  4300. PerformanceObserverEntryList: C,
  4301. PerformancePaintTiming: C,
  4302. PerformanceResourceTiming: C,
  4303. PerformanceTiming: C,
  4304. PeriodicWave: C,
  4305. Permissions: C,
  4306. PermissionStatus: C,
  4307. personalbar: O,
  4308. PhotoCapabilities: C,
  4309. Plugin: C,
  4310. PluginArray: C,
  4311. PointerEvent: C,
  4312. PopStateEvent: C,
  4313. postMessage: O,
  4314. Presentation: C,
  4315. PresentationAvailability: C,
  4316. PresentationConnection: C,
  4317. PresentationConnectionAvailableEvent: C,
  4318. PresentationConnectionCloseEvent: C,
  4319. PresentationConnectionList: C,
  4320. PresentationReceiver: C,
  4321. PresentationRequest: C,
  4322. print: O,
  4323. ProcessingInstruction: C,
  4324. ProgressEvent: C,
  4325. PromiseRejectionEvent: C,
  4326. prompt: O,
  4327. PushManager: C,
  4328. PushSubscription: C,
  4329. PushSubscriptionOptions: C,
  4330. queueMicrotask: O,
  4331. RadioNodeList: C,
  4332. Range: C,
  4333. ReadableStream: C,
  4334. RemotePlayback: C,
  4335. removeEventListener: O,
  4336. Request: C,
  4337. requestAnimationFrame: O,
  4338. requestIdleCallback: O,
  4339. resizeBy: O,
  4340. ResizeObserver: C,
  4341. ResizeObserverEntry: C,
  4342. resizeTo: O,
  4343. Response: C,
  4344. RTCCertificate: C,
  4345. RTCDataChannel: C,
  4346. RTCDataChannelEvent: C,
  4347. RTCDtlsTransport: C,
  4348. RTCIceCandidate: C,
  4349. RTCIceTransport: C,
  4350. RTCPeerConnection: C,
  4351. RTCPeerConnectionIceEvent: C,
  4352. RTCRtpReceiver: C,
  4353. RTCRtpSender: C,
  4354. RTCSctpTransport: C,
  4355. RTCSessionDescription: C,
  4356. RTCStatsReport: C,
  4357. RTCTrackEvent: C,
  4358. screen: O,
  4359. Screen: C,
  4360. screenLeft: O,
  4361. ScreenOrientation: C,
  4362. screenTop: O,
  4363. screenX: O,
  4364. screenY: O,
  4365. ScriptProcessorNode: C,
  4366. scroll: O,
  4367. scrollbars: O,
  4368. scrollBy: O,
  4369. scrollTo: O,
  4370. scrollX: O,
  4371. scrollY: O,
  4372. SecurityPolicyViolationEvent: C,
  4373. Selection: C,
  4374. ServiceWorker: C,
  4375. ServiceWorkerContainer: C,
  4376. ServiceWorkerRegistration: C,
  4377. sessionStorage: O,
  4378. ShadowRoot: C,
  4379. SharedWorker: C,
  4380. SourceBuffer: C,
  4381. SourceBufferList: C,
  4382. speechSynthesis: O,
  4383. SpeechSynthesisEvent: C,
  4384. SpeechSynthesisUtterance: C,
  4385. StaticRange: C,
  4386. status: O,
  4387. statusbar: O,
  4388. StereoPannerNode: C,
  4389. stop: O,
  4390. Storage: C,
  4391. StorageEvent: C,
  4392. StorageManager: C,
  4393. styleMedia: O,
  4394. StyleSheet: C,
  4395. StyleSheetList: C,
  4396. SubtleCrypto: C,
  4397. SVGAElement: C,
  4398. SVGAngle: C,
  4399. SVGAnimatedAngle: C,
  4400. SVGAnimatedBoolean: C,
  4401. SVGAnimatedEnumeration: C,
  4402. SVGAnimatedInteger: C,
  4403. SVGAnimatedLength: C,
  4404. SVGAnimatedLengthList: C,
  4405. SVGAnimatedNumber: C,
  4406. SVGAnimatedNumberList: C,
  4407. SVGAnimatedPreserveAspectRatio: C,
  4408. SVGAnimatedRect: C,
  4409. SVGAnimatedString: C,
  4410. SVGAnimatedTransformList: C,
  4411. SVGAnimateElement: C,
  4412. SVGAnimateMotionElement: C,
  4413. SVGAnimateTransformElement: C,
  4414. SVGAnimationElement: C,
  4415. SVGCircleElement: C,
  4416. SVGClipPathElement: C,
  4417. SVGComponentTransferFunctionElement: C,
  4418. SVGDefsElement: C,
  4419. SVGDescElement: C,
  4420. SVGDiscardElement: C,
  4421. SVGElement: C,
  4422. SVGEllipseElement: C,
  4423. SVGFEBlendElement: C,
  4424. SVGFEColorMatrixElement: C,
  4425. SVGFEComponentTransferElement: C,
  4426. SVGFECompositeElement: C,
  4427. SVGFEConvolveMatrixElement: C,
  4428. SVGFEDiffuseLightingElement: C,
  4429. SVGFEDisplacementMapElement: C,
  4430. SVGFEDistantLightElement: C,
  4431. SVGFEDropShadowElement: C,
  4432. SVGFEFloodElement: C,
  4433. SVGFEFuncAElement: C,
  4434. SVGFEFuncBElement: C,
  4435. SVGFEFuncGElement: C,
  4436. SVGFEFuncRElement: C,
  4437. SVGFEGaussianBlurElement: C,
  4438. SVGFEImageElement: C,
  4439. SVGFEMergeElement: C,
  4440. SVGFEMergeNodeElement: C,
  4441. SVGFEMorphologyElement: C,
  4442. SVGFEOffsetElement: C,
  4443. SVGFEPointLightElement: C,
  4444. SVGFESpecularLightingElement: C,
  4445. SVGFESpotLightElement: C,
  4446. SVGFETileElement: C,
  4447. SVGFETurbulenceElement: C,
  4448. SVGFilterElement: C,
  4449. SVGForeignObjectElement: C,
  4450. SVGGElement: C,
  4451. SVGGeometryElement: C,
  4452. SVGGradientElement: C,
  4453. SVGGraphicsElement: C,
  4454. SVGImageElement: C,
  4455. SVGLength: C,
  4456. SVGLengthList: C,
  4457. SVGLinearGradientElement: C,
  4458. SVGLineElement: C,
  4459. SVGMarkerElement: C,
  4460. SVGMaskElement: C,
  4461. SVGMatrix: C,
  4462. SVGMetadataElement: C,
  4463. SVGMPathElement: C,
  4464. SVGNumber: C,
  4465. SVGNumberList: C,
  4466. SVGPathElement: C,
  4467. SVGPatternElement: C,
  4468. SVGPoint: C,
  4469. SVGPointList: C,
  4470. SVGPolygonElement: C,
  4471. SVGPolylineElement: C,
  4472. SVGPreserveAspectRatio: C,
  4473. SVGRadialGradientElement: C,
  4474. SVGRect: C,
  4475. SVGRectElement: C,
  4476. SVGScriptElement: C,
  4477. SVGSetElement: C,
  4478. SVGStopElement: C,
  4479. SVGStringList: C,
  4480. SVGStyleElement: C,
  4481. SVGSVGElement: C,
  4482. SVGSwitchElement: C,
  4483. SVGSymbolElement: C,
  4484. SVGTextContentElement: C,
  4485. SVGTextElement: C,
  4486. SVGTextPathElement: C,
  4487. SVGTextPositioningElement: C,
  4488. SVGTitleElement: C,
  4489. SVGTransform: C,
  4490. SVGTransformList: C,
  4491. SVGTSpanElement: C,
  4492. SVGUnitTypes: C,
  4493. SVGUseElement: C,
  4494. SVGViewElement: C,
  4495. TaskAttributionTiming: C,
  4496. Text: C,
  4497. TextEvent: C,
  4498. TextMetrics: C,
  4499. TextTrack: C,
  4500. TextTrackCue: C,
  4501. TextTrackCueList: C,
  4502. TextTrackList: C,
  4503. TimeRanges: C,
  4504. toolbar: O,
  4505. top: O,
  4506. Touch: C,
  4507. TouchEvent: C,
  4508. TouchList: C,
  4509. TrackEvent: C,
  4510. TransitionEvent: C,
  4511. TreeWalker: C,
  4512. UIEvent: C,
  4513. ValidityState: C,
  4514. visualViewport: O,
  4515. VisualViewport: C,
  4516. VTTCue: C,
  4517. WaveShaperNode: C,
  4518. WebAssembly: O,
  4519. WebGL2RenderingContext: C,
  4520. WebGLActiveInfo: C,
  4521. WebGLBuffer: C,
  4522. WebGLContextEvent: C,
  4523. WebGLFramebuffer: C,
  4524. WebGLProgram: C,
  4525. WebGLQuery: C,
  4526. WebGLRenderbuffer: C,
  4527. WebGLRenderingContext: C,
  4528. WebGLSampler: C,
  4529. WebGLShader: C,
  4530. WebGLShaderPrecisionFormat: C,
  4531. WebGLSync: C,
  4532. WebGLTexture: C,
  4533. WebGLTransformFeedback: C,
  4534. WebGLUniformLocation: C,
  4535. WebGLVertexArrayObject: C,
  4536. WebSocket: C,
  4537. WheelEvent: C,
  4538. Window: C,
  4539. Worker: C,
  4540. WritableStream: C,
  4541. XMLDocument: C,
  4542. XMLHttpRequest: C,
  4543. XMLHttpRequestEventTarget: C,
  4544. XMLHttpRequestUpload: C,
  4545. XMLSerializer: C,
  4546. XPathEvaluator: C,
  4547. XPathExpression: C,
  4548. XPathResult: C,
  4549. XSLTProcessor: C
  4550. };
  4551. for (const global of ['window', 'global', 'self', 'globalThis']) {
  4552. knownGlobals[global] = knownGlobals;
  4553. }
  4554. function getGlobalAtPath(path) {
  4555. let currentGlobal = knownGlobals;
  4556. for (const pathSegment of path) {
  4557. if (typeof pathSegment !== 'string') {
  4558. return null;
  4559. }
  4560. currentGlobal = currentGlobal[pathSegment];
  4561. if (!currentGlobal) {
  4562. return null;
  4563. }
  4564. }
  4565. return currentGlobal[ValueProperties];
  4566. }
  4567. class GlobalVariable extends Variable {
  4568. constructor(name) {
  4569. super(name);
  4570. // Ensure we use live-bindings for globals as we do not know if they have
  4571. // been reassigned
  4572. this.markReassigned();
  4573. }
  4574. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4575. switch (interaction.type) {
  4576. // While there is no point in testing these cases as at the moment, they
  4577. // are also covered via other means, we keep them for completeness
  4578. case INTERACTION_ACCESSED:
  4579. case INTERACTION_ASSIGNED: {
  4580. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  4581. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4582. }
  4583. return;
  4584. }
  4585. case INTERACTION_CALLED: {
  4586. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4587. if (globalAtPath) {
  4588. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  4589. }
  4590. else {
  4591. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4592. }
  4593. return;
  4594. }
  4595. }
  4596. }
  4597. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  4598. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4599. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  4600. }
  4601. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4602. switch (interaction.type) {
  4603. case INTERACTION_ACCESSED: {
  4604. if (path.length === 0) {
  4605. // Technically, "undefined" is a global variable of sorts
  4606. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  4607. }
  4608. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  4609. }
  4610. case INTERACTION_ASSIGNED: {
  4611. return true;
  4612. }
  4613. case INTERACTION_CALLED: {
  4614. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4615. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  4616. }
  4617. }
  4618. }
  4619. }
  4620. // To avoid infinite recursions
  4621. const MAX_PATH_DEPTH = 6;
  4622. // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
  4623. // most MAX_PATH_DEPTH long. The last element is always UnknownKey
  4624. const limitConcatenatedPathDepth = (path1, path2) => {
  4625. const { length: length1 } = path1;
  4626. const { length: length2 } = path2;
  4627. return length1 === 0
  4628. ? path2
  4629. : length2 === 0
  4630. ? path1
  4631. : length1 + length2 > MAX_PATH_DEPTH
  4632. ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
  4633. : [...path1, ...path2];
  4634. };
  4635. class LocalVariable extends Variable {
  4636. constructor(name, declarator, init,
  4637. /** if this is non-empty, the actual init is this path of this.init */
  4638. initPath, context, kind) {
  4639. super(name);
  4640. this.init = init;
  4641. this.initPath = initPath;
  4642. this.kind = kind;
  4643. this.calledFromTryStatement = false;
  4644. this.additionalInitializers = null;
  4645. this.includedPathTracker = new IncludedFullPathTracker();
  4646. this.expressionsToBeDeoptimized = [];
  4647. this.declarations = declarator ? [declarator] : [];
  4648. this.deoptimizationTracker = context.deoptimizationTracker;
  4649. this.module = context.module;
  4650. }
  4651. addDeclaration(identifier, init) {
  4652. this.declarations.push(identifier);
  4653. this.markInitializersForDeoptimization().push(init);
  4654. }
  4655. consolidateInitializers() {
  4656. if (this.additionalInitializers) {
  4657. for (const initializer of this.additionalInitializers) {
  4658. initializer.deoptimizePath(UNKNOWN_PATH);
  4659. }
  4660. }
  4661. }
  4662. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4663. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4664. deoptimizeInteraction(interaction);
  4665. return;
  4666. }
  4667. recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4668. this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], recursionTracker);
  4669. }, undefined);
  4670. }
  4671. deoptimizePath(path) {
  4672. if (this.isReassigned ||
  4673. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  4674. return;
  4675. }
  4676. if (path.length === 0) {
  4677. this.markReassigned();
  4678. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  4679. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  4680. for (const expression of expressionsToBeDeoptimized) {
  4681. expression.deoptimizeCache();
  4682. }
  4683. this.init.deoptimizePath([...this.initPath, UnknownKey]);
  4684. }
  4685. else {
  4686. this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
  4687. }
  4688. }
  4689. getLiteralValueAtPath(path, recursionTracker, origin) {
  4690. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4691. return UnknownValue;
  4692. }
  4693. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4694. this.expressionsToBeDeoptimized.push(origin);
  4695. return this.init.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin);
  4696. }, UnknownValue);
  4697. }
  4698. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4699. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4700. return UNKNOWN_RETURN_EXPRESSION;
  4701. }
  4702. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4703. this.expressionsToBeDeoptimized.push(origin);
  4704. return this.init.getReturnExpressionWhenCalledAtPath([...this.initPath, ...path], interaction, recursionTracker, origin);
  4705. }, UNKNOWN_RETURN_EXPRESSION);
  4706. }
  4707. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4708. if (path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4709. return true;
  4710. }
  4711. switch (interaction.type) {
  4712. case INTERACTION_ACCESSED: {
  4713. if (this.isReassigned)
  4714. return true;
  4715. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  4716. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4717. }
  4718. case INTERACTION_ASSIGNED: {
  4719. if (this.included)
  4720. return true;
  4721. if (path.length === 0)
  4722. return false;
  4723. if (this.isReassigned)
  4724. return true;
  4725. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  4726. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4727. }
  4728. case INTERACTION_CALLED: {
  4729. if (this.isReassigned)
  4730. return true;
  4731. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  4732. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4733. }
  4734. }
  4735. }
  4736. includePath(path, context) {
  4737. if (!this.includedPathTracker.includePathAndGetIfIncluded(path)) {
  4738. this.module.scope.context.requestTreeshakingPass();
  4739. if (!this.included) {
  4740. // This will reduce the number of tree-shaking passes by eagerly
  4741. // including inits. By pushing this here instead of directly including
  4742. // we avoid deep call stacks.
  4743. this.module.scope.context.newlyIncludedVariableInits.add(this.init);
  4744. }
  4745. super.includePath(path, context);
  4746. for (const declaration of this.declarations) {
  4747. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  4748. if (!declaration.included)
  4749. declaration.include(context, false);
  4750. let node = declaration.parent;
  4751. while (!node.included) {
  4752. // We do not want to properly include parents in case they are part of a dead branch
  4753. // in which case .include() might pull in more dead code
  4754. node.includeNode(context);
  4755. if (node.type === Program$1)
  4756. break;
  4757. node = node.parent;
  4758. }
  4759. /**
  4760. * import('foo').then(m => {
  4761. * console.log(m.foo)
  4762. * })
  4763. */
  4764. if (this.kind === 'parameter' &&
  4765. isArrowFunctionExpressionNode(declaration.parent) &&
  4766. isCallExpressionNode(declaration.parent.parent) &&
  4767. isMemberExpressionNode(declaration.parent.parent.callee) &&
  4768. isIdentifierNode(declaration.parent.parent.callee.property) &&
  4769. declaration.parent.parent.callee.property.name === 'then' &&
  4770. isImportExpressionNode(declaration.parent.parent.callee.object)) {
  4771. declaration.parent.parent.callee.object.includePath(path);
  4772. }
  4773. }
  4774. // We need to make sure we include the correct path of the init
  4775. if (path.length > 0) {
  4776. this.init.includePath(limitConcatenatedPathDepth(this.initPath, path), context);
  4777. this.additionalInitializers?.forEach(initializer => initializer.includePath(UNKNOWN_PATH, context));
  4778. }
  4779. }
  4780. }
  4781. includeCallArguments(interaction, context) {
  4782. if (this.isReassigned ||
  4783. context.includedCallArguments.has(this.init) ||
  4784. // This can be removed again once we can include arguments when called at
  4785. // a specific path
  4786. this.initPath.length > 0) {
  4787. includeInteraction(interaction, context);
  4788. }
  4789. else {
  4790. context.includedCallArguments.add(this.init);
  4791. this.init.includeCallArguments(interaction, context);
  4792. context.includedCallArguments.delete(this.init);
  4793. }
  4794. }
  4795. markCalledFromTryStatement() {
  4796. this.calledFromTryStatement = true;
  4797. }
  4798. markInitializersForDeoptimization() {
  4799. if (this.additionalInitializers === null) {
  4800. this.additionalInitializers = [this.init];
  4801. this.init = UNKNOWN_EXPRESSION;
  4802. this.markReassigned();
  4803. }
  4804. return this.additionalInitializers;
  4805. }
  4806. }
  4807. const tdzVariableKinds = new Set(['class', 'const', 'let', 'var', 'using', 'await using']);
  4808. class IdentifierBase extends NodeBase {
  4809. constructor() {
  4810. super(...arguments);
  4811. this.variable = null;
  4812. this.isVariableReference = false;
  4813. }
  4814. get isTDZAccess() {
  4815. if (!isFlagSet(this.flags, 4 /* Flag.tdzAccessDefined */)) {
  4816. return null;
  4817. }
  4818. return isFlagSet(this.flags, 8 /* Flag.tdzAccess */);
  4819. }
  4820. set isTDZAccess(value) {
  4821. this.flags = setFlag(this.flags, 4 /* Flag.tdzAccessDefined */, true);
  4822. this.flags = setFlag(this.flags, 8 /* Flag.tdzAccess */, value);
  4823. }
  4824. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4825. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4826. }
  4827. deoptimizePath(path) {
  4828. if (path.length === 0 && !this.scope.contains(this.name)) {
  4829. this.disallowImportReassignment();
  4830. }
  4831. // We keep conditional chaining because an unknown Node could have an
  4832. // Identifier as property that might be deoptimized by default
  4833. this.variable?.deoptimizePath(path);
  4834. }
  4835. getLiteralValueAtPath(path, recursionTracker, origin) {
  4836. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  4837. }
  4838. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4839. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4840. return [expression, isPure || this.isPureFunction(path)];
  4841. }
  4842. hasEffects(context) {
  4843. if (!this.deoptimized)
  4844. this.applyDeoptimizations();
  4845. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  4846. return true;
  4847. }
  4848. return (this.scope.context.options.treeshake
  4849. .unknownGlobalSideEffects &&
  4850. this.variable instanceof GlobalVariable &&
  4851. !this.isPureFunction(EMPTY_PATH) &&
  4852. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  4853. }
  4854. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4855. switch (interaction.type) {
  4856. case INTERACTION_ACCESSED: {
  4857. return (this.variable !== null &&
  4858. !this.isPureFunction(path) &&
  4859. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  4860. }
  4861. case INTERACTION_ASSIGNED: {
  4862. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  4863. }
  4864. case INTERACTION_CALLED: {
  4865. return (!this.isPureFunction(path) &&
  4866. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  4867. }
  4868. }
  4869. }
  4870. include(context, includeChildrenRecursively) {
  4871. if (!this.included)
  4872. this.includeNode(context);
  4873. if (includeChildrenRecursively) {
  4874. this.variable?.includePath(UNKNOWN_PATH, context);
  4875. }
  4876. }
  4877. includeNode(context) {
  4878. this.included = true;
  4879. if (!this.deoptimized)
  4880. this.applyDeoptimizations();
  4881. if (this.variable !== null) {
  4882. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  4883. }
  4884. }
  4885. includePath(path, context) {
  4886. if (!this.included) {
  4887. this.included = true;
  4888. if (!this.deoptimized)
  4889. this.applyDeoptimizations();
  4890. if (this.variable !== null) {
  4891. this.scope.context.includeVariableInModule(this.variable, path, context);
  4892. }
  4893. }
  4894. else if (path.length > 0) {
  4895. this.variable?.includePath(path, context);
  4896. }
  4897. }
  4898. includeCallArguments(interaction, context) {
  4899. this.variable.includeCallArguments(interaction, context);
  4900. }
  4901. isPossibleTDZ() {
  4902. // return cached value to avoid issues with the next tree-shaking pass
  4903. const cachedTdzAccess = this.isTDZAccess;
  4904. if (cachedTdzAccess !== null)
  4905. return cachedTdzAccess;
  4906. if (!(this.variable instanceof LocalVariable &&
  4907. this.variable.kind &&
  4908. tdzVariableKinds.has(this.variable.kind) &&
  4909. // We ignore modules that did not receive a treeshaking pass yet as that
  4910. // causes many false positives due to circular dependencies or disabled
  4911. // moduleSideEffects.
  4912. this.variable.module.hasTreeShakingPassStarted)) {
  4913. return (this.isTDZAccess = false);
  4914. }
  4915. let decl_id;
  4916. if (this.variable.declarations &&
  4917. this.variable.declarations.length === 1 &&
  4918. (decl_id = this.variable.declarations[0]) &&
  4919. this.start < decl_id.start &&
  4920. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  4921. // a variable accessed before its declaration
  4922. // in the same function or at top level of module
  4923. return (this.isTDZAccess = true);
  4924. }
  4925. if (!this.variable.initReached) {
  4926. // Either a const/let TDZ violation or
  4927. // var use before declaration was encountered.
  4928. return (this.isTDZAccess = true);
  4929. }
  4930. return (this.isTDZAccess = false);
  4931. }
  4932. applyDeoptimizations() {
  4933. this.deoptimized = true;
  4934. if (this.variable instanceof LocalVariable) {
  4935. // When accessing a variable from a module without side effects, this
  4936. // means we use an export of that module and therefore need to potentially
  4937. // include it in the bundle.
  4938. if (!this.variable.module.isExecuted) {
  4939. markModuleAndImpureDependenciesAsExecuted(this.variable.module);
  4940. }
  4941. this.variable.consolidateInitializers();
  4942. this.scope.context.requestTreeshakingPass();
  4943. }
  4944. if (this.isVariableReference) {
  4945. this.variable.addUsedPlace(this);
  4946. this.scope.context.requestTreeshakingPass();
  4947. }
  4948. }
  4949. disallowImportReassignment() {
  4950. return this.scope.context.error(logIllegalImportReassignment(this.name, this.scope.context.module.id), this.start);
  4951. }
  4952. getVariableRespectingTDZ() {
  4953. if (this.isPossibleTDZ()) {
  4954. return UNKNOWN_EXPRESSION;
  4955. }
  4956. return this.variable;
  4957. }
  4958. isPureFunction(path) {
  4959. let currentPureFunction = this.scope.context.manualPureFunctions[this.name];
  4960. for (const segment of path) {
  4961. if (currentPureFunction) {
  4962. if (currentPureFunction[PureFunctionKey]) {
  4963. return true;
  4964. }
  4965. currentPureFunction = currentPureFunction[segment];
  4966. }
  4967. else {
  4968. return false;
  4969. }
  4970. }
  4971. return currentPureFunction?.[PureFunctionKey];
  4972. }
  4973. }
  4974. function closestParentFunctionOrProgram(node) {
  4975. while (node && !/^Program|Function/.test(node.type)) {
  4976. node = node.parent;
  4977. }
  4978. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  4979. return node;
  4980. }
  4981. class ObjectMember extends ExpressionEntity {
  4982. constructor(object, path) {
  4983. super();
  4984. this.object = object;
  4985. this.path = path;
  4986. }
  4987. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4988. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.path, ...path], recursionTracker);
  4989. }
  4990. deoptimizePath(path) {
  4991. this.object.deoptimizePath([...this.path, ...path]);
  4992. }
  4993. getLiteralValueAtPath(path, recursionTracker, origin) {
  4994. return this.object.getLiteralValueAtPath([...this.path, ...path], recursionTracker, origin);
  4995. }
  4996. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4997. return this.object.getReturnExpressionWhenCalledAtPath([...this.path, ...path], interaction, recursionTracker, origin);
  4998. }
  4999. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5000. return this.object.hasEffectsOnInteractionAtPath([...this.path, ...path], interaction, context);
  5001. }
  5002. }
  5003. class Identifier extends IdentifierBase {
  5004. constructor() {
  5005. super(...arguments);
  5006. this.variable = null;
  5007. }
  5008. get isDestructuringDeoptimized() {
  5009. return isFlagSet(this.flags, 16777216 /* Flag.destructuringDeoptimized */);
  5010. }
  5011. set isDestructuringDeoptimized(value) {
  5012. this.flags = setFlag(this.flags, 16777216 /* Flag.destructuringDeoptimized */, value);
  5013. }
  5014. addExportedVariables(variables, exportNamesByVariable) {
  5015. if (exportNamesByVariable.has(this.variable)) {
  5016. variables.push(this.variable);
  5017. }
  5018. }
  5019. bind() {
  5020. if (!this.variable && is_reference(this, this.parent)) {
  5021. this.variable = this.scope.findVariable(this.name);
  5022. this.variable.addReference(this);
  5023. this.isVariableReference = true;
  5024. }
  5025. }
  5026. declare(kind, destructuredInitPath, init) {
  5027. let variable;
  5028. const { treeshake } = this.scope.context.options;
  5029. if (kind === 'parameter') {
  5030. variable = this.scope.addParameterDeclaration(this, destructuredInitPath);
  5031. }
  5032. else {
  5033. variable = this.scope.addDeclaration(this, this.scope.context, init, destructuredInitPath, kind);
  5034. if (kind === 'var' && treeshake && treeshake.correctVarValueBeforeDeclaration) {
  5035. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  5036. variable.markInitializersForDeoptimization();
  5037. }
  5038. }
  5039. return [(this.variable = variable)];
  5040. }
  5041. deoptimizeAssignment(destructuredInitPath, init) {
  5042. this.deoptimizePath(EMPTY_PATH);
  5043. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  5044. }
  5045. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  5046. return (destructuredInitPath.length > 0 &&
  5047. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  5048. }
  5049. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  5050. if (destructuredInitPath.length > 0 && !this.isDestructuringDeoptimized) {
  5051. this.isDestructuringDeoptimized = true;
  5052. init.deoptimizeArgumentsOnInteractionAtPath({
  5053. args: [new ObjectMember(init, destructuredInitPath.slice(0, -1))],
  5054. type: INTERACTION_ACCESSED
  5055. }, destructuredInitPath, SHARED_RECURSION_TRACKER);
  5056. }
  5057. const { propertyReadSideEffects } = this.scope.context.options
  5058. .treeshake;
  5059. if ((this.included ||=
  5060. destructuredInitPath.length > 0 &&
  5061. !context.brokenFlow &&
  5062. propertyReadSideEffects &&
  5063. (propertyReadSideEffects === 'always' ||
  5064. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext())))) {
  5065. if (this.variable && !this.variable.included) {
  5066. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  5067. }
  5068. init.includePath(destructuredInitPath, context);
  5069. return true;
  5070. }
  5071. return false;
  5072. }
  5073. markDeclarationReached() {
  5074. this.variable.initReached = true;
  5075. }
  5076. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  5077. if (this.variable) {
  5078. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  5079. if (name !== this.name) {
  5080. code.overwrite(this.start, this.end, name, {
  5081. contentOnly: true,
  5082. storeName: true
  5083. });
  5084. if (isShorthandProperty) {
  5085. code.prependRight(this.start, `${this.name}: `);
  5086. }
  5087. }
  5088. // In strict mode, any variable named "eval" must be the actual "eval" function
  5089. if (name === 'eval' &&
  5090. renderedParentType === CallExpression$1 &&
  5091. isCalleeOfRenderedParent) {
  5092. code.appendRight(this.start, '0, ');
  5093. }
  5094. }
  5095. }
  5096. }
  5097. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  5098. const base = 64;
  5099. function toBase64(value) {
  5100. let outString = '';
  5101. do {
  5102. const currentDigit = value % base;
  5103. value = (value / base) | 0;
  5104. outString = chars[currentDigit] + outString;
  5105. } while (value !== 0);
  5106. return outString;
  5107. }
  5108. function getSafeName(baseName, usedNames, forbiddenNames) {
  5109. let safeName = baseName;
  5110. let count = 1;
  5111. while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
  5112. safeName = `${baseName}$${toBase64(count++)}`;
  5113. }
  5114. usedNames.add(safeName);
  5115. return safeName;
  5116. }
  5117. class Scope {
  5118. constructor() {
  5119. this.children = [];
  5120. this.variables = new Map();
  5121. }
  5122. /*
  5123. Redeclaration rules:
  5124. - var can redeclare var
  5125. - in function scopes, function and var can redeclare function and var
  5126. - var is hoisted across scopes, function remains in the scope it is declared
  5127. - var and function can redeclare function parameters, but parameters cannot redeclare parameters
  5128. - function cannot redeclare catch scope parameters
  5129. - var can redeclare catch scope parameters in a way
  5130. - if the parameter is an identifier and not a pattern
  5131. - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
  5132. - const, let, class, and function except in the cases above cannot redeclare anything
  5133. */
  5134. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5135. const name = identifier.name;
  5136. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5137. if (existingVariable) {
  5138. if (kind === 'var' && existingVariable.kind === 'var') {
  5139. existingVariable.addDeclaration(identifier, init);
  5140. return existingVariable;
  5141. }
  5142. context.error(logRedeclarationError(name), identifier.start);
  5143. }
  5144. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  5145. this.variables.set(name, newVariable);
  5146. return newVariable;
  5147. }
  5148. addHoistedVariable(name, variable) {
  5149. (this.hoistedVariables ||= new Map()).set(name, variable);
  5150. }
  5151. contains(name) {
  5152. return this.variables.has(name);
  5153. }
  5154. findVariable(_name) {
  5155. /* istanbul ignore next */
  5156. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  5157. }
  5158. }
  5159. class ChildScope extends Scope {
  5160. constructor(parent, context) {
  5161. super();
  5162. this.parent = parent;
  5163. this.context = context;
  5164. this.accessedOutsideVariables = new Map();
  5165. parent.children.push(this);
  5166. }
  5167. addAccessedDynamicImport(importExpression) {
  5168. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  5169. if (this.parent instanceof ChildScope) {
  5170. this.parent.addAccessedDynamicImport(importExpression);
  5171. }
  5172. }
  5173. addAccessedGlobals(globals, accessedGlobalsByScope) {
  5174. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  5175. for (const name of globals) {
  5176. accessedGlobals.add(name);
  5177. }
  5178. accessedGlobalsByScope.set(this, accessedGlobals);
  5179. if (this.parent instanceof ChildScope) {
  5180. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  5181. }
  5182. }
  5183. addNamespaceMemberAccess(name, variable) {
  5184. this.accessedOutsideVariables.set(name, variable);
  5185. this.parent.addNamespaceMemberAccess(name, variable);
  5186. }
  5187. addReturnExpression(expression) {
  5188. if (this.parent instanceof ChildScope) {
  5189. this.parent.addReturnExpression(expression);
  5190. }
  5191. }
  5192. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  5193. for (const variable of this.accessedOutsideVariables.values()) {
  5194. if (variable.included) {
  5195. usedNames.add(variable.getBaseVariableName());
  5196. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5197. usedNames.add('exports');
  5198. }
  5199. }
  5200. }
  5201. const accessedGlobals = accessedGlobalsByScope.get(this);
  5202. if (accessedGlobals) {
  5203. for (const name of accessedGlobals) {
  5204. usedNames.add(name);
  5205. }
  5206. }
  5207. }
  5208. contains(name) {
  5209. return this.variables.has(name) || this.parent.contains(name);
  5210. }
  5211. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  5212. const usedNames = new Set();
  5213. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  5214. if (this.accessedDynamicImports) {
  5215. for (const importExpression of this.accessedDynamicImports) {
  5216. if (importExpression.inlineNamespace) {
  5217. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  5218. }
  5219. }
  5220. }
  5221. for (const [name, variable] of this.variables) {
  5222. if (variable.included || variable.alwaysRendered) {
  5223. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  5224. }
  5225. }
  5226. for (const scope of this.children) {
  5227. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  5228. }
  5229. }
  5230. findLexicalBoundary() {
  5231. return this.parent.findLexicalBoundary();
  5232. }
  5233. findGlobal(name) {
  5234. const variable = this.parent.findVariable(name);
  5235. this.accessedOutsideVariables.set(name, variable);
  5236. return variable;
  5237. }
  5238. findVariable(name) {
  5239. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  5240. if (knownVariable) {
  5241. return knownVariable;
  5242. }
  5243. const variable = this.parent.findVariable(name);
  5244. this.accessedOutsideVariables.set(name, variable);
  5245. return variable;
  5246. }
  5247. }
  5248. function checkEffectForNodes(nodes, context) {
  5249. for (const node of nodes) {
  5250. if (node.hasEffects(context)) {
  5251. return true;
  5252. }
  5253. }
  5254. return false;
  5255. }
  5256. class MethodBase extends NodeBase {
  5257. constructor() {
  5258. super(...arguments);
  5259. this.accessedValue = null;
  5260. }
  5261. get computed() {
  5262. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  5263. }
  5264. set computed(value) {
  5265. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  5266. }
  5267. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5268. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  5269. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  5270. args: interaction.args,
  5271. type: INTERACTION_CALLED,
  5272. withNew: false
  5273. }, EMPTY_PATH, recursionTracker);
  5274. }
  5275. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  5276. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  5277. args: interaction.args,
  5278. type: INTERACTION_CALLED,
  5279. withNew: false
  5280. }, EMPTY_PATH, recursionTracker);
  5281. }
  5282. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5283. }
  5284. // As getter properties directly receive their values from fixed function
  5285. // expressions, there is no known situation where a getter is deoptimized.
  5286. deoptimizeCache() { }
  5287. deoptimizePath(path) {
  5288. this.getAccessedValue()[0].deoptimizePath(path);
  5289. }
  5290. getLiteralValueAtPath(path, recursionTracker, origin) {
  5291. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  5292. }
  5293. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5294. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5295. }
  5296. hasEffects(context) {
  5297. return this.key.hasEffects(context);
  5298. }
  5299. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5300. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  5301. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  5302. args: interaction.args,
  5303. type: INTERACTION_CALLED,
  5304. withNew: false
  5305. }, context);
  5306. }
  5307. // setters are only called for empty paths
  5308. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  5309. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  5310. args: interaction.args,
  5311. type: INTERACTION_CALLED,
  5312. withNew: false
  5313. }, context);
  5314. }
  5315. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  5316. }
  5317. getAccessedValue() {
  5318. if (this.accessedValue === null) {
  5319. if (this.kind === 'get') {
  5320. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  5321. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  5322. }
  5323. else {
  5324. return (this.accessedValue = [this.value, false]);
  5325. }
  5326. }
  5327. return this.accessedValue;
  5328. }
  5329. }
  5330. MethodBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  5331. MethodBase.prototype.applyDeoptimizations = doNotDeoptimize;
  5332. class MethodDefinition extends MethodBase {
  5333. hasEffects(context) {
  5334. return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  5335. }
  5336. }
  5337. class BlockScope extends ChildScope {
  5338. constructor(parent) {
  5339. super(parent, parent.context);
  5340. }
  5341. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5342. if (kind === 'var') {
  5343. const name = identifier.name;
  5344. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5345. if (existingVariable) {
  5346. if (existingVariable.kind === 'var' ||
  5347. (kind === 'var' && existingVariable.kind === 'parameter')) {
  5348. existingVariable.addDeclaration(identifier, init);
  5349. return existingVariable;
  5350. }
  5351. return context.error(logRedeclarationError(name), identifier.start);
  5352. }
  5353. const declaredVariable = this.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5354. // Necessary to make sure the init is deoptimized for conditional declarations.
  5355. // We cannot call deoptimizePath here.
  5356. declaredVariable.markInitializersForDeoptimization();
  5357. // We add the variable to this and all parent scopes to reliably detect conflicts
  5358. this.addHoistedVariable(name, declaredVariable);
  5359. return declaredVariable;
  5360. }
  5361. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5362. }
  5363. }
  5364. class StaticBlock extends NodeBase {
  5365. createScope(parentScope) {
  5366. this.scope = new BlockScope(parentScope);
  5367. }
  5368. hasEffects(context) {
  5369. for (const node of this.body) {
  5370. if (node.hasEffects(context))
  5371. return true;
  5372. }
  5373. return false;
  5374. }
  5375. include(context, includeChildrenRecursively) {
  5376. this.included = true;
  5377. for (const node of this.body) {
  5378. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  5379. node.include(context, includeChildrenRecursively);
  5380. }
  5381. }
  5382. render(code, options) {
  5383. if (this.body.length > 0) {
  5384. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  5385. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  5386. }
  5387. else {
  5388. super.render(code, options);
  5389. }
  5390. }
  5391. }
  5392. StaticBlock.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  5393. StaticBlock.prototype.applyDeoptimizations = doNotDeoptimize;
  5394. function isStaticBlock(statement) {
  5395. return statement.type === StaticBlock$1;
  5396. }
  5397. class ClassNode extends NodeBase {
  5398. constructor() {
  5399. super(...arguments);
  5400. this.objectEntity = null;
  5401. }
  5402. createScope(parentScope) {
  5403. this.scope = new ChildScope(parentScope, parentScope.context);
  5404. }
  5405. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5406. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5407. }
  5408. deoptimizeCache() {
  5409. this.getObjectEntity().deoptimizeAllProperties();
  5410. }
  5411. deoptimizePath(path) {
  5412. this.getObjectEntity().deoptimizePath(path);
  5413. }
  5414. getLiteralValueAtPath(path, recursionTracker, origin) {
  5415. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5416. }
  5417. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5418. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5419. }
  5420. hasEffects(context) {
  5421. if (!this.deoptimized)
  5422. this.applyDeoptimizations();
  5423. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  5424. this.id?.markDeclarationReached();
  5425. return initEffect || super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  5426. }
  5427. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5428. return interaction.type === INTERACTION_CALLED && path.length === 0
  5429. ? !interaction.withNew ||
  5430. (this.classConstructor === null
  5431. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  5432. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  5433. false
  5434. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5435. }
  5436. include(context, includeChildrenRecursively) {
  5437. if (!this.included)
  5438. this.includeNode(context);
  5439. this.superClass?.include(context, includeChildrenRecursively);
  5440. this.body.include(context, includeChildrenRecursively);
  5441. for (const decorator of this.decorators)
  5442. decorator.include(context, includeChildrenRecursively);
  5443. if (this.id) {
  5444. this.id.markDeclarationReached();
  5445. this.id.include(context, includeChildrenRecursively);
  5446. }
  5447. }
  5448. initialise() {
  5449. super.initialise();
  5450. this.id?.declare('class', EMPTY_PATH, this);
  5451. for (const method of this.body.body) {
  5452. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  5453. this.classConstructor = method;
  5454. return;
  5455. }
  5456. }
  5457. this.classConstructor = null;
  5458. }
  5459. applyDeoptimizations() {
  5460. this.deoptimized = true;
  5461. for (const definition of this.body.body) {
  5462. if (!isStaticBlock(definition) &&
  5463. !(definition.static ||
  5464. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  5465. // Calls to methods are not tracked, ensure that the return value is deoptimized
  5466. definition.deoptimizePath(UNKNOWN_PATH);
  5467. }
  5468. }
  5469. this.scope.context.requestTreeshakingPass();
  5470. }
  5471. getObjectEntity() {
  5472. if (this.objectEntity !== null) {
  5473. return this.objectEntity;
  5474. }
  5475. const staticProperties = [];
  5476. const dynamicMethods = [];
  5477. for (const definition of this.body.body) {
  5478. if (isStaticBlock(definition))
  5479. continue;
  5480. const properties = definition.static ? staticProperties : dynamicMethods;
  5481. const definitionKind = definition.kind;
  5482. // Note that class fields do not end up on the prototype
  5483. if (properties === dynamicMethods && !definitionKind)
  5484. continue;
  5485. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  5486. let key;
  5487. if (definition.computed) {
  5488. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  5489. if (typeof keyValue === 'symbol') {
  5490. properties.push({ key: UnknownKey, kind, property: definition });
  5491. continue;
  5492. }
  5493. else {
  5494. key = String(keyValue);
  5495. }
  5496. }
  5497. else {
  5498. key =
  5499. definition.key instanceof Identifier
  5500. ? definition.key.name
  5501. : String(definition.key.value);
  5502. }
  5503. properties.push({ key, kind, property: definition });
  5504. }
  5505. staticProperties.unshift({
  5506. key: 'prototype',
  5507. kind: 'init',
  5508. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, ['prototype']) : OBJECT_PROTOTYPE)
  5509. });
  5510. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  5511. }
  5512. }
  5513. ClassNode.prototype.includeNode = onlyIncludeSelf;
  5514. class ClassDeclaration extends ClassNode {
  5515. initialise() {
  5516. super.initialise();
  5517. if (this.id !== null) {
  5518. this.id.variable.isId = true;
  5519. }
  5520. }
  5521. parseNode(esTreeNode) {
  5522. if (esTreeNode.id !== null) {
  5523. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  5524. }
  5525. return super.parseNode(esTreeNode);
  5526. }
  5527. render(code, options) {
  5528. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  5529. if (this.id) {
  5530. const { variable, name } = this.id;
  5531. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5532. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  5533. }
  5534. const renderedVariable = variable.getName(getPropertyAccess);
  5535. if (renderedVariable !== name) {
  5536. this.decorators.map(decorator => decorator.render(code, options));
  5537. this.superClass?.render(code, options);
  5538. this.body.render(code, {
  5539. ...options,
  5540. useOriginalName: (_variable) => _variable === variable
  5541. });
  5542. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  5543. code.prependLeft(this.end, ';');
  5544. return;
  5545. }
  5546. }
  5547. super.render(code, options);
  5548. }
  5549. applyDeoptimizations() {
  5550. super.applyDeoptimizations();
  5551. const { id, scope } = this;
  5552. if (id) {
  5553. const { name, variable } = id;
  5554. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  5555. if (accessedVariable !== variable) {
  5556. accessedVariable.forbidName(name);
  5557. }
  5558. }
  5559. }
  5560. }
  5561. }
  5562. class ArgumentsVariable extends LocalVariable {
  5563. constructor(context) {
  5564. super('arguments', null, UNKNOWN_EXPRESSION, EMPTY_PATH, context, 'other');
  5565. }
  5566. addArgumentToBeDeoptimized(_argument) { }
  5567. // Only If there is at least one reference, then we need to track all
  5568. // arguments in order to be able to deoptimize them.
  5569. addReference() {
  5570. this.deoptimizedArguments = [];
  5571. this.addArgumentToBeDeoptimized = addArgumentToBeDeoptimized;
  5572. }
  5573. hasEffectsOnInteractionAtPath(path, { type }) {
  5574. return type !== INTERACTION_ACCESSED || path.length > 1;
  5575. }
  5576. includePath(path, context) {
  5577. super.includePath(path, context);
  5578. for (const argument of this.deoptimizedArguments) {
  5579. argument.deoptimizePath(UNKNOWN_PATH);
  5580. }
  5581. this.deoptimizedArguments.length = 0;
  5582. }
  5583. }
  5584. function addArgumentToBeDeoptimized(argument) {
  5585. if (this.included) {
  5586. argument.deoptimizePath(UNKNOWN_PATH);
  5587. }
  5588. else {
  5589. this.deoptimizedArguments?.push(argument);
  5590. }
  5591. }
  5592. const MAX_TRACKED_INTERACTIONS = 20;
  5593. const NO_INTERACTIONS = EMPTY_ARRAY;
  5594. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  5595. const EMPTY_PATH_TRACKER = new EntityPathTracker();
  5596. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  5597. class ParameterVariable extends LocalVariable {
  5598. constructor(name, declarator, argumentPath, context) {
  5599. super(name, declarator, UNKNOWN_EXPRESSION, argumentPath, context, 'parameter');
  5600. this.includedPathTracker = new IncludedTopLevelPathTracker();
  5601. this.argumentsToBeDeoptimized = new Set();
  5602. this.deoptimizationInteractions = [];
  5603. this.deoptimizations = new EntityPathTracker();
  5604. this.deoptimizedFields = new Set();
  5605. this.expressionsDependingOnKnownValue = [];
  5606. this.knownValue = null;
  5607. this.knownValueLiteral = UnknownValue;
  5608. }
  5609. addArgumentForDeoptimization(entity) {
  5610. this.updateKnownValue(entity);
  5611. if (entity === UNKNOWN_EXPRESSION) {
  5612. // As unknown expressions fully deoptimize all interactions, we can clear
  5613. // the interaction cache at this point provided we keep this optimization
  5614. // in mind when adding new interactions
  5615. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5616. this.argumentsToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  5617. for (const { interaction } of this.deoptimizationInteractions) {
  5618. deoptimizeInteraction(interaction);
  5619. }
  5620. this.deoptimizationInteractions = NO_INTERACTIONS;
  5621. }
  5622. }
  5623. else if (this.deoptimizedFields.has(UnknownKey)) {
  5624. // This means that we already deoptimized all interactions and no longer
  5625. // track them
  5626. entity.deoptimizePath([...this.initPath, UnknownKey]);
  5627. }
  5628. else if (!this.argumentsToBeDeoptimized.has(entity)) {
  5629. this.argumentsToBeDeoptimized.add(entity);
  5630. for (const field of this.deoptimizedFields) {
  5631. entity.deoptimizePath([...this.initPath, field]);
  5632. }
  5633. for (const { interaction, path } of this.deoptimizationInteractions) {
  5634. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  5635. }
  5636. }
  5637. }
  5638. /** This says we should not make assumptions about the value of the parameter.
  5639. * This is different from deoptimization that will also cause argument values
  5640. * to be deoptimized. */
  5641. markReassigned() {
  5642. if (this.isReassigned) {
  5643. return;
  5644. }
  5645. super.markReassigned();
  5646. for (const expression of this.expressionsDependingOnKnownValue) {
  5647. expression.deoptimizeCache();
  5648. }
  5649. this.expressionsDependingOnKnownValue = EMPTY_ARRAY;
  5650. }
  5651. deoptimizeCache() {
  5652. this.markReassigned();
  5653. }
  5654. /**
  5655. * Update the known value of the parameter variable.
  5656. * Must be called for every function call, so it can track all the arguments,
  5657. * and deoptimizeCache itself to mark reassigned if the argument is changed.
  5658. * @param argument The argument of the function call
  5659. */
  5660. updateKnownValue(argument) {
  5661. if (this.isReassigned) {
  5662. return;
  5663. }
  5664. if (this.knownValue === null) {
  5665. this.knownValue = argument;
  5666. this.knownValueLiteral = argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this);
  5667. return;
  5668. }
  5669. // the same literal or identifier, do nothing
  5670. if (this.knownValue === argument ||
  5671. (this.knownValue instanceof Identifier &&
  5672. argument instanceof Identifier &&
  5673. this.knownValue.variable === argument.variable)) {
  5674. return;
  5675. }
  5676. const { knownValueLiteral } = this;
  5677. if (typeof knownValueLiteral === 'symbol' ||
  5678. argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this) !==
  5679. knownValueLiteral) {
  5680. this.markReassigned();
  5681. }
  5682. }
  5683. /**
  5684. * This function freezes the known value of the parameter variable,
  5685. * so the optimization starts with a certain ExpressionEntity.
  5686. * The optimization can be undone by calling `markReassigned`.
  5687. * @returns the frozen value
  5688. */
  5689. getKnownValue() {
  5690. return this.knownValue || UNKNOWN_EXPRESSION;
  5691. }
  5692. getLiteralValueAtPath(path, recursionTracker, origin) {
  5693. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  5694. return UnknownValue;
  5695. }
  5696. const knownValue = this.getKnownValue();
  5697. this.expressionsDependingOnKnownValue.push(origin);
  5698. return recursionTracker.withTrackedEntityAtPath(path, knownValue, () => knownValue.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin), UnknownValue);
  5699. }
  5700. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5701. const { type } = interaction;
  5702. if (this.isReassigned ||
  5703. type === INTERACTION_ASSIGNED ||
  5704. path.length + this.initPath.length > MAX_PATH_DEPTH) {
  5705. return super.hasEffectsOnInteractionAtPath(path, interaction, context);
  5706. }
  5707. return (!(type === INTERACTION_CALLED
  5708. ? (interaction.withNew
  5709. ? context.instantiated
  5710. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)
  5711. : context.accessed.trackEntityAtPathAndGetIfTracked(path, this)) &&
  5712. this.getKnownValue().hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  5713. }
  5714. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  5715. // For performance reasons, we fully deoptimize all deeper interactions
  5716. if (path.length >= 2 ||
  5717. this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  5718. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  5719. (path.length === 1 &&
  5720. (this.deoptimizedFields.has(UnknownKey) ||
  5721. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0])))) ||
  5722. this.initPath.length + path.length > MAX_PATH_DEPTH) {
  5723. deoptimizeInteraction(interaction);
  5724. return;
  5725. }
  5726. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  5727. for (const entity of this.argumentsToBeDeoptimized) {
  5728. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  5729. }
  5730. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5731. this.deoptimizationInteractions.push({
  5732. interaction,
  5733. path
  5734. });
  5735. }
  5736. }
  5737. }
  5738. deoptimizePath(path) {
  5739. if (path.length === 0) {
  5740. this.markReassigned();
  5741. return;
  5742. }
  5743. if (this.deoptimizedFields.has(UnknownKey)) {
  5744. return;
  5745. }
  5746. const key = path[0];
  5747. if (this.deoptimizedFields.has(key)) {
  5748. return;
  5749. }
  5750. this.deoptimizedFields.add(key);
  5751. for (const entity of this.argumentsToBeDeoptimized) {
  5752. // We do not need a recursion tracker here as we already track whether
  5753. // this field is deoptimized
  5754. entity.deoptimizePath([...this.initPath, key]);
  5755. }
  5756. if (key === UnknownKey) {
  5757. // save some memory
  5758. this.deoptimizationInteractions = NO_INTERACTIONS;
  5759. this.deoptimizations = EMPTY_PATH_TRACKER;
  5760. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  5761. this.argumentsToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  5762. }
  5763. }
  5764. getReturnExpressionWhenCalledAtPath(path) {
  5765. // We deoptimize everything that is called as that will trivially deoptimize
  5766. // the corresponding return expressions as well and avoid badly performing
  5767. // and complicated alternatives
  5768. if (path.length === 0) {
  5769. this.deoptimizePath(UNKNOWN_PATH);
  5770. }
  5771. else if (!this.deoptimizedFields.has(path[0])) {
  5772. this.deoptimizePath([path[0]]);
  5773. }
  5774. return UNKNOWN_RETURN_EXPRESSION;
  5775. }
  5776. includeArgumentPaths(entity, context) {
  5777. this.includedPathTracker.includeAllPaths(entity, context, this.initPath);
  5778. }
  5779. }
  5780. class ThisVariable extends ParameterVariable {
  5781. constructor(context) {
  5782. super('this', null, EMPTY_PATH, context);
  5783. }
  5784. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5785. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  5786. }
  5787. }
  5788. class CatchBodyScope extends ChildScope {
  5789. constructor(parent) {
  5790. super(parent, parent.context);
  5791. this.parent = parent;
  5792. }
  5793. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5794. if (kind === 'var') {
  5795. const name = identifier.name;
  5796. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5797. if (existingVariable) {
  5798. const existingKind = existingVariable.kind;
  5799. if (existingKind === 'parameter' &&
  5800. // If this is a destructured parameter, it is forbidden to redeclare
  5801. existingVariable.declarations[0].parent.type === CatchClause$1) {
  5802. // If this is a var with the same name as the catch scope parameter,
  5803. // the assignment actually goes to the parameter and the var is
  5804. // hoisted without assignment. Locally, it is shadowed by the
  5805. // parameter
  5806. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, destructuredInitPath, kind);
  5807. // To avoid the need to rewrite the declaration, we link the variable
  5808. // names. If we ever implement a logic that splits initialization and
  5809. // assignment for hoisted vars, the "renderLikeHoisted" logic can be
  5810. // removed again.
  5811. // We do not need to check whether there already is a linked
  5812. // variable because then declaredVariable would be that linked
  5813. // variable.
  5814. existingVariable.renderLikeHoisted(declaredVariable);
  5815. this.addHoistedVariable(name, declaredVariable);
  5816. return declaredVariable;
  5817. }
  5818. if (existingKind === 'var') {
  5819. existingVariable.addDeclaration(identifier, init);
  5820. return existingVariable;
  5821. }
  5822. return context.error(logRedeclarationError(name), identifier.start);
  5823. }
  5824. // We only add parameters to parameter scopes
  5825. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5826. // Necessary to make sure the init is deoptimized for conditional declarations.
  5827. // We cannot call deoptimizePath here.
  5828. declaredVariable.markInitializersForDeoptimization();
  5829. // We add the variable to this and all parent scopes to reliably detect conflicts
  5830. this.addHoistedVariable(name, declaredVariable);
  5831. return declaredVariable;
  5832. }
  5833. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5834. }
  5835. }
  5836. class FunctionBodyScope extends ChildScope {
  5837. constructor(parent) {
  5838. super(parent, parent.context);
  5839. }
  5840. // There is stuff that is only allowed in function scopes, i.e. functions can
  5841. // be redeclared, functions and var can redeclare each other
  5842. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5843. const name = identifier.name;
  5844. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5845. if (existingVariable) {
  5846. const existingKind = existingVariable.kind;
  5847. if ((kind === 'var' || kind === 'function') &&
  5848. (existingKind === 'var' || existingKind === 'function' || existingKind === 'parameter')) {
  5849. existingVariable.addDeclaration(identifier, init);
  5850. return existingVariable;
  5851. }
  5852. context.error(logRedeclarationError(name), identifier.start);
  5853. }
  5854. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  5855. this.variables.set(name, newVariable);
  5856. return newVariable;
  5857. }
  5858. }
  5859. class ParameterScope extends ChildScope {
  5860. constructor(parent, isCatchScope) {
  5861. super(parent, parent.context);
  5862. this.hasRest = false;
  5863. this.parameters = [];
  5864. this.bodyScope = isCatchScope ? new CatchBodyScope(this) : new FunctionBodyScope(this);
  5865. }
  5866. /**
  5867. * Adds a parameter to this scope. Parameters must be added in the correct
  5868. * order, i.e. from left to right.
  5869. */
  5870. addParameterDeclaration(identifier, argumentPath) {
  5871. const { name, start } = identifier;
  5872. const existingParameter = this.variables.get(name);
  5873. if (existingParameter) {
  5874. return this.context.error(logDuplicateArgumentNameError(name), start);
  5875. }
  5876. const variable = new ParameterVariable(name, identifier, argumentPath, this.context);
  5877. this.variables.set(name, variable);
  5878. // We also add it to the body scope to detect name conflicts with local
  5879. // variables. We still need the intermediate scope, though, as parameter
  5880. // defaults are NOT taken from the body scope but from the parameters or
  5881. // outside scope.
  5882. this.bodyScope.addHoistedVariable(name, variable);
  5883. return variable;
  5884. }
  5885. addParameterVariables(parameters, hasRest) {
  5886. this.parameters = parameters;
  5887. for (const parameterList of parameters) {
  5888. for (const parameter of parameterList) {
  5889. parameter.alwaysRendered = true;
  5890. }
  5891. }
  5892. this.hasRest = hasRest;
  5893. }
  5894. includeCallArguments({ args }, context) {
  5895. let calledFromTryStatement = false;
  5896. let argumentIncluded = false;
  5897. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  5898. let lastExplicitlyIncludedIndex = args.length - 1;
  5899. // If there is a SpreadElement, we need to include all arguments after it
  5900. // because we no longer know which argument corresponds to which parameter.
  5901. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  5902. const argument = args[argumentIndex];
  5903. if (argument instanceof SpreadElement && !argumentIncluded) {
  5904. argumentIncluded = true;
  5905. lastExplicitlyIncludedIndex = argumentIndex - 1;
  5906. }
  5907. if (argumentIncluded) {
  5908. argument.includePath(UNKNOWN_PATH, context);
  5909. argument.include(context, false);
  5910. }
  5911. }
  5912. // Now we go backwards either starting from the last argument or before the
  5913. // first SpreadElement to ensure all arguments before are included as needed
  5914. for (let index = lastExplicitlyIncludedIndex; index >= 1; index--) {
  5915. const parameterVariables = this.parameters[index - 1] || restParameter;
  5916. const argument = args[index];
  5917. if (parameterVariables) {
  5918. calledFromTryStatement = false;
  5919. if (parameterVariables.length === 0) {
  5920. // handle empty destructuring to avoid destructuring undefined
  5921. argumentIncluded = true;
  5922. }
  5923. else {
  5924. for (const parameterVariable of parameterVariables) {
  5925. if (parameterVariable.calledFromTryStatement) {
  5926. calledFromTryStatement = true;
  5927. }
  5928. if (parameterVariable.included) {
  5929. argumentIncluded = true;
  5930. if (calledFromTryStatement) {
  5931. argument.include(context, true);
  5932. }
  5933. else {
  5934. parameterVariable.includeArgumentPaths(argument, context);
  5935. argument.include(context, false);
  5936. }
  5937. }
  5938. }
  5939. }
  5940. }
  5941. if (argumentIncluded || argument.shouldBeIncluded(context)) {
  5942. argumentIncluded = true;
  5943. argument.include(context, calledFromTryStatement);
  5944. }
  5945. }
  5946. }
  5947. }
  5948. class ReturnValueScope extends ParameterScope {
  5949. constructor() {
  5950. super(...arguments);
  5951. this.returnExpression = null;
  5952. this.returnExpressions = [];
  5953. }
  5954. addReturnExpression(expression) {
  5955. this.returnExpressions.push(expression);
  5956. }
  5957. deoptimizeArgumentsOnCall({ args }) {
  5958. const { parameters } = this;
  5959. let position = 0;
  5960. for (; position < args.length - 1; position++) {
  5961. // Only the "this" argument arg[0] can be null
  5962. const argument = args[position + 1];
  5963. if (argument instanceof SpreadElement) {
  5964. // This deoptimizes the current and remaining parameters and arguments
  5965. for (; position < parameters.length; position++) {
  5966. args[position + 1]?.deoptimizePath(UNKNOWN_PATH);
  5967. for (const variable of parameters[position]) {
  5968. variable.markReassigned();
  5969. }
  5970. }
  5971. break;
  5972. }
  5973. if (this.hasRest && position >= parameters.length - 1) {
  5974. argument.deoptimizePath(UNKNOWN_PATH);
  5975. }
  5976. else {
  5977. const variables = parameters[position];
  5978. if (variables) {
  5979. for (const variable of variables) {
  5980. variable.addArgumentForDeoptimization(argument);
  5981. }
  5982. }
  5983. this.addArgumentToBeDeoptimized(argument);
  5984. }
  5985. }
  5986. const nonRestParameterLength = this.hasRest ? parameters.length - 1 : parameters.length;
  5987. for (; position < nonRestParameterLength; position++) {
  5988. for (const variable of parameters[position]) {
  5989. variable.addArgumentForDeoptimization(UNDEFINED_EXPRESSION);
  5990. }
  5991. }
  5992. }
  5993. getReturnExpression() {
  5994. if (this.returnExpression === null)
  5995. this.updateReturnExpression();
  5996. return this.returnExpression;
  5997. }
  5998. deoptimizeAllParameters() {
  5999. for (const parameter of this.parameters) {
  6000. for (const variable of parameter) {
  6001. variable.deoptimizePath(UNKNOWN_PATH);
  6002. variable.markReassigned();
  6003. }
  6004. }
  6005. }
  6006. reassignAllParameters() {
  6007. for (const parameter of this.parameters) {
  6008. for (const variable of parameter) {
  6009. variable.markReassigned();
  6010. }
  6011. }
  6012. }
  6013. addArgumentToBeDeoptimized(_argument) { }
  6014. updateReturnExpression() {
  6015. if (this.returnExpressions.length === 1) {
  6016. this.returnExpression = this.returnExpressions[0];
  6017. }
  6018. else {
  6019. this.returnExpression = UNKNOWN_EXPRESSION;
  6020. for (const expression of this.returnExpressions) {
  6021. expression.deoptimizePath(UNKNOWN_PATH);
  6022. }
  6023. }
  6024. }
  6025. }
  6026. class FunctionScope extends ReturnValueScope {
  6027. constructor(parent, functionNode) {
  6028. super(parent, false);
  6029. this.functionNode = functionNode;
  6030. const { context } = parent;
  6031. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  6032. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  6033. }
  6034. findLexicalBoundary() {
  6035. return this;
  6036. }
  6037. includeCallArguments(interaction, context) {
  6038. super.includeCallArguments(interaction, context);
  6039. if (this.argumentsVariable.included) {
  6040. const { args } = interaction;
  6041. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  6042. const argument = args[argumentIndex];
  6043. if (argument) {
  6044. argument.includePath(UNKNOWN_PATH, context);
  6045. argument.include(context, false);
  6046. }
  6047. }
  6048. }
  6049. }
  6050. addArgumentToBeDeoptimized(argument) {
  6051. this.argumentsVariable.addArgumentToBeDeoptimized(argument);
  6052. }
  6053. }
  6054. class ExpressionStatement extends NodeBase {
  6055. initialise() {
  6056. super.initialise();
  6057. if (this.directive &&
  6058. this.directive !== 'use strict' &&
  6059. this.parent.type === Program$1) {
  6060. this.scope.context.log(LOGLEVEL_WARN,
  6061. // This is necessary, because either way (deleting or not) can lead to errors.
  6062. logModuleLevelDirective(this.directive, this.scope.context.module.id), this.start);
  6063. }
  6064. }
  6065. removeAnnotations(code) {
  6066. this.expression.removeAnnotations(code);
  6067. }
  6068. render(code, options) {
  6069. super.render(code, options);
  6070. if (code.original[this.end - 1] !== ';') {
  6071. code.appendLeft(this.end, ';');
  6072. }
  6073. }
  6074. shouldBeIncluded(context) {
  6075. if (this.directive && this.directive !== 'use strict')
  6076. return this.parent.type !== Program$1;
  6077. return super.shouldBeIncluded(context);
  6078. }
  6079. }
  6080. ExpressionStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6081. ExpressionStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  6082. class BlockStatement extends NodeBase {
  6083. get deoptimizeBody() {
  6084. return isFlagSet(this.flags, 32768 /* Flag.deoptimizeBody */);
  6085. }
  6086. set deoptimizeBody(value) {
  6087. this.flags = setFlag(this.flags, 32768 /* Flag.deoptimizeBody */, value);
  6088. }
  6089. get directlyIncluded() {
  6090. return isFlagSet(this.flags, 16384 /* Flag.directlyIncluded */);
  6091. }
  6092. set directlyIncluded(value) {
  6093. this.flags = setFlag(this.flags, 16384 /* Flag.directlyIncluded */, value);
  6094. }
  6095. addImplicitReturnExpressionToScope() {
  6096. const lastStatement = this.body[this.body.length - 1];
  6097. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  6098. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  6099. }
  6100. }
  6101. createScope(parentScope) {
  6102. this.scope = this.parent.preventChildBlockScope
  6103. ? parentScope
  6104. : new BlockScope(parentScope);
  6105. }
  6106. hasEffects(context) {
  6107. if (this.deoptimizeBody)
  6108. return true;
  6109. for (const node of this.body) {
  6110. if (context.brokenFlow)
  6111. break;
  6112. if (node.hasEffects(context))
  6113. return true;
  6114. }
  6115. return false;
  6116. }
  6117. include(context, includeChildrenRecursively) {
  6118. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  6119. this.included = true;
  6120. this.directlyIncluded = true;
  6121. if (this.deoptimizeBody)
  6122. includeChildrenRecursively = true;
  6123. for (const node of this.body) {
  6124. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  6125. node.include(context, includeChildrenRecursively);
  6126. }
  6127. }
  6128. }
  6129. initialise() {
  6130. super.initialise();
  6131. const firstBodyStatement = this.body[0];
  6132. this.deoptimizeBody =
  6133. firstBodyStatement instanceof ExpressionStatement &&
  6134. firstBodyStatement.directive === 'use asm';
  6135. }
  6136. render(code, options) {
  6137. if (this.body.length > 0) {
  6138. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  6139. }
  6140. else {
  6141. super.render(code, options);
  6142. }
  6143. }
  6144. }
  6145. BlockStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6146. BlockStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  6147. class RestElement extends NodeBase {
  6148. constructor() {
  6149. super(...arguments);
  6150. this.declarationInit = null;
  6151. }
  6152. addExportedVariables(variables, exportNamesByVariable) {
  6153. this.argument.addExportedVariables(variables, exportNamesByVariable);
  6154. }
  6155. declare(kind, destructuredInitPath, init) {
  6156. this.declarationInit = init;
  6157. return this.argument.declare(kind, getIncludedPatternPath$1(destructuredInitPath), init);
  6158. }
  6159. deoptimizeAssignment(destructuredInitPath, init) {
  6160. this.argument.deoptimizeAssignment(getIncludedPatternPath$1(destructuredInitPath), init);
  6161. }
  6162. deoptimizePath(path) {
  6163. if (path.length === 0) {
  6164. this.argument.deoptimizePath(EMPTY_PATH);
  6165. }
  6166. }
  6167. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6168. return (path.length > 0 ||
  6169. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  6170. }
  6171. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  6172. return this.argument.hasEffectsWhenDestructuring(context, getIncludedPatternPath$1(destructuredInitPath), init);
  6173. }
  6174. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  6175. return (this.included =
  6176. this.argument.includeDestructuredIfNecessary(context, getIncludedPatternPath$1(destructuredInitPath), init) || this.included);
  6177. }
  6178. include(context, includeChildrenRecursively) {
  6179. if (!this.included)
  6180. this.includeNode(context);
  6181. // This should just include the identifier, its properties should be
  6182. // included where the variable is used.
  6183. this.argument.include(context, includeChildrenRecursively);
  6184. }
  6185. markDeclarationReached() {
  6186. this.argument.markDeclarationReached();
  6187. }
  6188. applyDeoptimizations() {
  6189. this.deoptimized = true;
  6190. if (this.declarationInit !== null) {
  6191. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  6192. this.scope.context.requestTreeshakingPass();
  6193. }
  6194. }
  6195. }
  6196. RestElement.prototype.includeNode = onlyIncludeSelf;
  6197. const getIncludedPatternPath$1 = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  6198. ? destructuredInitPath
  6199. : [...destructuredInitPath, UnknownKey];
  6200. class FunctionBase extends NodeBase {
  6201. constructor() {
  6202. super(...arguments);
  6203. this.parameterVariableValuesDeoptimized = false;
  6204. this.includeCallArguments = this.scope.includeCallArguments.bind(this.scope);
  6205. }
  6206. get async() {
  6207. return isFlagSet(this.flags, 256 /* Flag.async */);
  6208. }
  6209. set async(value) {
  6210. this.flags = setFlag(this.flags, 256 /* Flag.async */, value);
  6211. }
  6212. get deoptimizedReturn() {
  6213. return isFlagSet(this.flags, 512 /* Flag.deoptimizedReturn */);
  6214. }
  6215. set deoptimizedReturn(value) {
  6216. this.flags = setFlag(this.flags, 512 /* Flag.deoptimizedReturn */, value);
  6217. }
  6218. get generator() {
  6219. return isFlagSet(this.flags, 4194304 /* Flag.generator */);
  6220. }
  6221. set generator(value) {
  6222. this.flags = setFlag(this.flags, 4194304 /* Flag.generator */, value);
  6223. }
  6224. get hasCachedEffects() {
  6225. return isFlagSet(this.flags, 67108864 /* Flag.hasEffects */);
  6226. }
  6227. set hasCachedEffects(value) {
  6228. this.flags = setFlag(this.flags, 67108864 /* Flag.hasEffects */, value);
  6229. }
  6230. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6231. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  6232. this.scope.deoptimizeArgumentsOnCall(interaction);
  6233. }
  6234. else {
  6235. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6236. }
  6237. }
  6238. deoptimizePath(path) {
  6239. this.getObjectEntity().deoptimizePath(path);
  6240. if (path.length === 1 && path[0] === UnknownKey) {
  6241. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  6242. // which means the return expression and parameters need to be reassigned
  6243. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  6244. this.scope.deoptimizeAllParameters();
  6245. }
  6246. }
  6247. getLiteralValueAtPath(path, recursionTracker, origin) {
  6248. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  6249. }
  6250. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6251. if (path.length > 0) {
  6252. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6253. }
  6254. if (this.async) {
  6255. if (!this.deoptimizedReturn) {
  6256. this.deoptimizedReturn = true;
  6257. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  6258. this.scope.context.requestTreeshakingPass();
  6259. }
  6260. return UNKNOWN_RETURN_EXPRESSION;
  6261. }
  6262. return [this.scope.getReturnExpression(), false];
  6263. }
  6264. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6265. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  6266. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  6267. }
  6268. if (this.hasCachedEffects) {
  6269. return true;
  6270. }
  6271. if (this.async) {
  6272. const { propertyReadSideEffects } = this.scope.context.options
  6273. .treeshake;
  6274. const returnExpression = this.scope.getReturnExpression();
  6275. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  6276. (propertyReadSideEffects &&
  6277. (propertyReadSideEffects === 'always' ||
  6278. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  6279. this.hasCachedEffects = true;
  6280. return true;
  6281. }
  6282. }
  6283. const { propertyReadSideEffects } = this.scope.context.options
  6284. .treeshake;
  6285. for (let index = 0; index < this.params.length; index++) {
  6286. const parameter = this.params[index];
  6287. if (parameter.hasEffects(context) ||
  6288. (propertyReadSideEffects &&
  6289. parameter.hasEffectsWhenDestructuring(context, EMPTY_PATH, interaction.args[index + 1] || UNDEFINED_EXPRESSION))) {
  6290. this.hasCachedEffects = true;
  6291. return true;
  6292. }
  6293. }
  6294. return false;
  6295. }
  6296. /**
  6297. * If the function (expression or declaration) is only used as function calls
  6298. */
  6299. onlyFunctionCallUsed() {
  6300. let variable = null;
  6301. if (this.parent.type === VariableDeclarator$1) {
  6302. variable = this.parent.id.variable ?? null;
  6303. }
  6304. if (this.parent.type === ExportDefaultDeclaration$1) {
  6305. variable = this.parent.variable;
  6306. }
  6307. return variable?.getOnlyFunctionCallUsed() ?? false;
  6308. }
  6309. include(context, includeChildrenRecursively) {
  6310. if (!this.included)
  6311. this.includeNode(context);
  6312. if (!(this.parameterVariableValuesDeoptimized || this.onlyFunctionCallUsed())) {
  6313. this.parameterVariableValuesDeoptimized = true;
  6314. this.scope.reassignAllParameters();
  6315. }
  6316. const { brokenFlow } = context;
  6317. context.brokenFlow = false;
  6318. this.body.include(context, includeChildrenRecursively);
  6319. context.brokenFlow = brokenFlow;
  6320. }
  6321. initialise() {
  6322. super.initialise();
  6323. if (this.body instanceof BlockStatement) {
  6324. this.body.addImplicitReturnExpressionToScope();
  6325. }
  6326. else {
  6327. this.scope.addReturnExpression(this.body);
  6328. }
  6329. if (this.annotations &&
  6330. this.scope.context.options.treeshake.annotations) {
  6331. this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
  6332. }
  6333. }
  6334. parseNode(esTreeNode) {
  6335. const { body, params } = esTreeNode;
  6336. const { scope } = this;
  6337. const { bodyScope, context } = scope;
  6338. // We need to ensure that parameters are declared before the body is parsed
  6339. // so that the scope already knows all parameters and can detect conflicts
  6340. // when parsing the body.
  6341. const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
  6342. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  6343. this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
  6344. return super.parseNode(esTreeNode);
  6345. }
  6346. }
  6347. FunctionBase.prototype.preventChildBlockScope = true;
  6348. FunctionBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6349. FunctionBase.prototype.applyDeoptimizations = doNotDeoptimize;
  6350. class FunctionNode extends FunctionBase {
  6351. constructor() {
  6352. super(...arguments);
  6353. this.objectEntity = null;
  6354. }
  6355. createScope(parentScope) {
  6356. this.scope = new FunctionScope(parentScope, this);
  6357. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  6358. // This makes sure that all deoptimizations of "this" are applied to the
  6359. // constructed entity.
  6360. this.scope.thisVariable.addArgumentForDeoptimization(this.constructedEntity);
  6361. }
  6362. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6363. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6364. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  6365. // args[0] is the "this" argument
  6366. this.scope.thisVariable.addArgumentForDeoptimization(interaction.args[0]);
  6367. }
  6368. }
  6369. hasEffects(context) {
  6370. if (this.annotationNoSideEffects) {
  6371. return false;
  6372. }
  6373. return !!this.id?.hasEffects(context);
  6374. }
  6375. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6376. if (this.annotationNoSideEffects &&
  6377. path.length === 0 &&
  6378. interaction.type === INTERACTION_CALLED) {
  6379. return false;
  6380. }
  6381. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  6382. return true;
  6383. }
  6384. if (path.length === 0 && interaction.type === INTERACTION_CALLED) {
  6385. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  6386. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  6387. const { brokenFlow, ignore, replacedVariableInits } = context;
  6388. context.ignore = {
  6389. breaks: false,
  6390. continues: false,
  6391. labels: new Set(),
  6392. returnYield: true,
  6393. this: interaction.withNew
  6394. };
  6395. if (this.body.hasEffects(context)) {
  6396. this.hasCachedEffects = true;
  6397. return true;
  6398. }
  6399. context.brokenFlow = brokenFlow;
  6400. if (thisInit) {
  6401. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  6402. }
  6403. else {
  6404. replacedVariableInits.delete(this.scope.thisVariable);
  6405. }
  6406. context.ignore = ignore;
  6407. }
  6408. return false;
  6409. }
  6410. include(context, includeChildrenRecursively) {
  6411. super.include(context, includeChildrenRecursively);
  6412. this.id?.include(context, includeChildrenRecursively);
  6413. const hasArguments = this.scope.argumentsVariable.included;
  6414. for (const parameter of this.params) {
  6415. if (!(parameter instanceof Identifier) || hasArguments) {
  6416. parameter.include(context, includeChildrenRecursively);
  6417. }
  6418. }
  6419. }
  6420. includeNode(context) {
  6421. this.included = true;
  6422. const hasArguments = this.scope.argumentsVariable.included;
  6423. for (const parameter of this.params) {
  6424. if (!(parameter instanceof Identifier) || hasArguments) {
  6425. parameter.includePath(UNKNOWN_PATH, context);
  6426. }
  6427. }
  6428. }
  6429. initialise() {
  6430. super.initialise();
  6431. this.id?.declare('function', EMPTY_PATH, this);
  6432. }
  6433. getObjectEntity() {
  6434. if (this.objectEntity !== null) {
  6435. return this.objectEntity;
  6436. }
  6437. return (this.objectEntity = new ObjectEntity([
  6438. {
  6439. key: 'prototype',
  6440. kind: 'init',
  6441. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  6442. }
  6443. ], OBJECT_PROTOTYPE));
  6444. }
  6445. }
  6446. class FunctionDeclaration extends FunctionNode {
  6447. initialise() {
  6448. super.initialise();
  6449. if (this.id !== null) {
  6450. this.id.variable.isId = true;
  6451. }
  6452. }
  6453. onlyFunctionCallUsed() {
  6454. // call super.onlyFunctionCallUsed for export default anonymous function
  6455. return this.id?.variable.getOnlyFunctionCallUsed() ?? super.onlyFunctionCallUsed();
  6456. }
  6457. parseNode(esTreeNode) {
  6458. if (esTreeNode.id !== null) {
  6459. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  6460. }
  6461. return super.parseNode(esTreeNode);
  6462. }
  6463. }
  6464. // The header ends at the first non-white-space after "default"
  6465. function getDeclarationStart(code, start) {
  6466. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  6467. }
  6468. function getFunctionIdInsertPosition(code, start) {
  6469. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  6470. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  6471. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  6472. if (generatorStarPos === -1) {
  6473. return declarationEnd;
  6474. }
  6475. return declarationEnd + generatorStarPos + 1;
  6476. }
  6477. class ExportDefaultDeclaration extends NodeBase {
  6478. include(context, includeChildrenRecursively) {
  6479. this.included = true;
  6480. this.declaration.include(context, includeChildrenRecursively);
  6481. if (includeChildrenRecursively) {
  6482. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, context);
  6483. }
  6484. }
  6485. includePath(path, context) {
  6486. this.included = true;
  6487. this.declaration.includePath(path, context);
  6488. }
  6489. initialise() {
  6490. super.initialise();
  6491. const declaration = this.declaration;
  6492. this.declarationName =
  6493. (declaration.id && declaration.id.name) || this.declaration.name;
  6494. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.scope.context.getModuleName(), this, this.scope.context);
  6495. this.scope.context.addExport(this);
  6496. }
  6497. removeAnnotations(code) {
  6498. this.declaration.removeAnnotations(code);
  6499. }
  6500. render(code, options, nodeRenderOptions) {
  6501. const { start, end } = nodeRenderOptions;
  6502. const declarationStart = getDeclarationStart(code.original, this.start);
  6503. if (this.declaration instanceof FunctionDeclaration) {
  6504. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  6505. ? getFunctionIdInsertPosition(code.original, declarationStart)
  6506. : null, options);
  6507. }
  6508. else if (this.declaration instanceof ClassDeclaration) {
  6509. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  6510. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  6511. : null, options);
  6512. }
  6513. else if (this.variable.getOriginalVariable() !== this.variable) {
  6514. // Remove altogether to prevent re-declaring the same variable
  6515. treeshakeNode(this, code, start, end);
  6516. return;
  6517. }
  6518. else if (this.variable.included) {
  6519. this.renderVariableDeclaration(code, declarationStart, options);
  6520. }
  6521. else {
  6522. code.remove(this.start, declarationStart);
  6523. this.declaration.render(code, options, {
  6524. renderedSurroundingElement: ExpressionStatement$1
  6525. });
  6526. if (code.original[this.end - 1] !== ';') {
  6527. code.appendLeft(this.end, ';');
  6528. }
  6529. return;
  6530. }
  6531. this.declaration.render(code, options);
  6532. }
  6533. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  6534. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  6535. const name = this.variable.getName(getPropertyAccess);
  6536. // Remove `export default`
  6537. code.remove(this.start, declarationStart);
  6538. if (idInsertPosition !== null) {
  6539. code.appendLeft(idInsertPosition, ` ${name}`);
  6540. }
  6541. if (format === 'system' &&
  6542. this.declaration instanceof ClassDeclaration &&
  6543. exportNamesByVariable.has(this.variable)) {
  6544. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  6545. }
  6546. }
  6547. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  6548. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  6549. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  6550. if (systemExportNames) {
  6551. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports(${JSON.stringify(systemExportNames[0])}, `);
  6552. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  6553. }
  6554. else {
  6555. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  6556. if (!hasTrailingSemicolon) {
  6557. code.appendLeft(this.end, ';');
  6558. }
  6559. }
  6560. }
  6561. }
  6562. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  6563. ExportDefaultDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6564. ExportDefaultDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  6565. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  6566. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  6567. const backSlashRegEx = /\\/g;
  6568. function escapeId(id) {
  6569. if (!needsEscapeRegEx.test(id))
  6570. return id;
  6571. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  6572. }
  6573. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  6574. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  6575. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  6576. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  6577. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  6578. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  6579. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  6580. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  6581. const defaultInteropHelpersByInteropType = {
  6582. auto: INTEROP_DEFAULT_VARIABLE,
  6583. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  6584. default: null,
  6585. defaultOnly: null,
  6586. esModule: null
  6587. };
  6588. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  6589. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  6590. const namespaceInteropHelpersByInteropType = {
  6591. auto: INTEROP_NAMESPACE_VARIABLE,
  6592. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  6593. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  6594. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  6595. esModule: null
  6596. };
  6597. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  6598. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, symbols) => {
  6599. const usedHelpers = new Set(additionalHelpers);
  6600. for (const variable of HELPER_NAMES) {
  6601. if (accessedGlobals.has(variable)) {
  6602. usedHelpers.add(variable);
  6603. }
  6604. }
  6605. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  6606. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, symbols, usedHelpers)
  6607. : '').join('');
  6608. };
  6609. const HELPER_GENERATORS = {
  6610. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  6611. return `var ${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  6612. },
  6613. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  6614. const { _, getDirectReturnFunction, n } = snippets;
  6615. const [left, right] = getDirectReturnFunction(['e'], {
  6616. functionReturn: true,
  6617. lineBreakIndent: null,
  6618. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  6619. });
  6620. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  6621. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  6622. },
  6623. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  6624. const { _, getDirectReturnFunction, n } = snippets;
  6625. const [left, right] = getDirectReturnFunction(['e'], {
  6626. functionReturn: true,
  6627. lineBreakIndent: null,
  6628. name: INTEROP_DEFAULT_VARIABLE
  6629. });
  6630. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  6631. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  6632. },
  6633. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  6634. const { _, getDirectReturnFunction, n } = snippets;
  6635. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  6636. const [left, right] = getDirectReturnFunction(['e'], {
  6637. functionReturn: true,
  6638. lineBreakIndent: null,
  6639. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  6640. });
  6641. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  6642. }
  6643. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  6644. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  6645. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6646. `}${n}${n}`);
  6647. },
  6648. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, symbols) {
  6649. const { getDirectReturnFunction, getObject, n, _ } = snippets;
  6650. const [left, right] = getDirectReturnFunction(['e'], {
  6651. functionReturn: true,
  6652. lineBreakIndent: null,
  6653. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  6654. });
  6655. return `${left}${getFrozen(freeze, getWithToStringTag(symbols, getObject([
  6656. [null, `__proto__:${_}null`],
  6657. ['default', 'e']
  6658. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  6659. },
  6660. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  6661. const { _, n } = snippets;
  6662. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  6663. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6664. `}${n}${n}`);
  6665. },
  6666. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  6667. const { _, getDirectReturnFunction, n } = snippets;
  6668. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  6669. const [left, right] = getDirectReturnFunction(['e'], {
  6670. functionReturn: true,
  6671. lineBreakIndent: null,
  6672. name: INTEROP_NAMESPACE_VARIABLE
  6673. });
  6674. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  6675. }
  6676. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  6677. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  6678. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6679. `}${n}${n}`);
  6680. },
  6681. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  6682. const { _, cnst, n } = snippets;
  6683. const useForEach = cnst === 'var' && liveBindings;
  6684. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  6685. `${t}${loopOverNamespaces(`{${n}` +
  6686. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  6687. (liveBindings
  6688. ? useForEach
  6689. ? copyOwnPropertyLiveBinding
  6690. : copyPropertyLiveBinding
  6691. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  6692. `${t}${t}${t}}${n}` +
  6693. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  6694. `${t}return ${getFrozen(freeze, getWithToStringTag(symbols, 'n', snippets))};${n}` +
  6695. `}${n}${n}`);
  6696. }
  6697. };
  6698. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  6699. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  6700. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  6701. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, symbols) => {
  6702. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  6703. const copyProperty = `{${n}` +
  6704. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  6705. `${index}${t}}`;
  6706. return (`${index}${cnst} n${_}=${_}Object.create(null${symbols ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` +
  6707. `${index}if${_}(e)${_}{${n}` +
  6708. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  6709. `${index}}${n}` +
  6710. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  6711. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  6712. };
  6713. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  6714. ? `for${_}(${cnst} k in e)${_}${body}`
  6715. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  6716. isAsync: false,
  6717. name: null
  6718. })}${body})${s}`;
  6719. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  6720. if (useForEach) {
  6721. const [left, right] = getDirectReturnFunction(['e'], {
  6722. functionReturn: false,
  6723. lineBreakIndent: { base: t, t },
  6724. name: null
  6725. });
  6726. return (`m.forEach(${left}` +
  6727. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  6728. isAsync: false,
  6729. name: null
  6730. })}${body})${right});`);
  6731. }
  6732. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  6733. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  6734. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  6735. };
  6736. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  6737. const { _, n } = snippets;
  6738. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  6739. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  6740. `${index}}${n}`);
  6741. };
  6742. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  6743. const [left, right] = getDirectReturnFunction([], {
  6744. functionReturn: true,
  6745. lineBreakIndent: null,
  6746. name: null
  6747. });
  6748. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  6749. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  6750. `${index}${t}enumerable:${_}true,${n}` +
  6751. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  6752. `${index}});${n}`);
  6753. };
  6754. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  6755. const [left, right] = getDirectReturnFunction([], {
  6756. functionReturn: true,
  6757. lineBreakIndent: null,
  6758. name: null
  6759. });
  6760. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  6761. `${index}if${_}(d)${_}{${n}` +
  6762. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  6763. `${index}${t}${t}enumerable:${_}true,${n}` +
  6764. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  6765. `${index}${t}});${n}` +
  6766. `${index}}${n}`);
  6767. };
  6768. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  6769. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  6770. const getWithToStringTag = (symbols, fragment, { _, getObject }) => symbols
  6771. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  6772. : fragment;
  6773. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  6774. function getToStringTagValue(getObject) {
  6775. return getObject([['value', "'Module'"]], {
  6776. lineBreakIndent: null
  6777. });
  6778. }
  6779. class Literal extends NodeBase {
  6780. deoptimizeArgumentsOnInteractionAtPath() { }
  6781. getLiteralValueAtPath(path) {
  6782. if (path.length > 0 ||
  6783. // unknown literals can also be null but do not start with an "n"
  6784. (this.value === null && this.scope.context.code.charCodeAt(this.start) !== 110) ||
  6785. typeof this.value === 'bigint' ||
  6786. // to support shims for regular expressions
  6787. this.scope.context.code.charCodeAt(this.start) === 47) {
  6788. return UnknownValue;
  6789. }
  6790. return this.value;
  6791. }
  6792. getReturnExpressionWhenCalledAtPath(path) {
  6793. if (path.length !== 1)
  6794. return UNKNOWN_RETURN_EXPRESSION;
  6795. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  6796. }
  6797. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6798. switch (interaction.type) {
  6799. case INTERACTION_ACCESSED: {
  6800. return path.length > (this.value === null ? 0 : 1);
  6801. }
  6802. case INTERACTION_ASSIGNED: {
  6803. return true;
  6804. }
  6805. case INTERACTION_CALLED: {
  6806. if (this.included &&
  6807. this.value instanceof RegExp &&
  6808. (this.value.global || this.value.sticky)) {
  6809. return true;
  6810. }
  6811. return (path.length !== 1 ||
  6812. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  6813. }
  6814. }
  6815. }
  6816. initialise() {
  6817. super.initialise();
  6818. this.members = getLiteralMembersForValue(this.value);
  6819. }
  6820. parseNode(esTreeNode) {
  6821. this.value = esTreeNode.value;
  6822. this.regex = esTreeNode.regex;
  6823. return super.parseNode(esTreeNode);
  6824. }
  6825. render(code) {
  6826. if (typeof this.value === 'string') {
  6827. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  6828. }
  6829. }
  6830. }
  6831. Literal.prototype.includeNode = onlyIncludeSelf;
  6832. function getChainElementLiteralValueAtPath(element, object, path, recursionTracker, origin) {
  6833. if ('getLiteralValueAtPathAsChainElement' in object) {
  6834. const calleeValue = object.getLiteralValueAtPathAsChainElement(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin);
  6835. if (calleeValue === IS_SKIPPED_CHAIN || (element.optional && calleeValue == null)) {
  6836. return IS_SKIPPED_CHAIN;
  6837. }
  6838. }
  6839. else if (element.optional &&
  6840. object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null) {
  6841. return IS_SKIPPED_CHAIN;
  6842. }
  6843. return element.getLiteralValueAtPath(path, recursionTracker, origin);
  6844. }
  6845. function getResolvablePropertyKey(memberExpression) {
  6846. return memberExpression.computed
  6847. ? getResolvableComputedPropertyKey(memberExpression.property)
  6848. : memberExpression.property.name;
  6849. }
  6850. function getResolvableComputedPropertyKey(propertyKey) {
  6851. if (propertyKey instanceof Literal) {
  6852. return String(propertyKey.value);
  6853. }
  6854. return null;
  6855. }
  6856. function getPathIfNotComputed(memberExpression) {
  6857. const nextPathKey = memberExpression.propertyKey;
  6858. const object = memberExpression.object;
  6859. if (typeof nextPathKey === 'string') {
  6860. if (object instanceof Identifier) {
  6861. return [
  6862. { key: object.name, pos: object.start },
  6863. { key: nextPathKey, pos: memberExpression.property.start }
  6864. ];
  6865. }
  6866. if (object instanceof MemberExpression) {
  6867. const parentPath = getPathIfNotComputed(object);
  6868. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  6869. }
  6870. }
  6871. return null;
  6872. }
  6873. function getStringFromPath(path) {
  6874. let pathString = path[0].key;
  6875. for (let index = 1; index < path.length; index++) {
  6876. pathString += '.' + path[index].key;
  6877. }
  6878. return pathString;
  6879. }
  6880. class MemberExpression extends NodeBase {
  6881. constructor() {
  6882. super(...arguments);
  6883. this.variable = null;
  6884. this.expressionsToBeDeoptimized = [];
  6885. }
  6886. get computed() {
  6887. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  6888. }
  6889. set computed(value) {
  6890. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  6891. }
  6892. get optional() {
  6893. return isFlagSet(this.flags, 128 /* Flag.optional */);
  6894. }
  6895. set optional(value) {
  6896. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  6897. }
  6898. get assignmentDeoptimized() {
  6899. return isFlagSet(this.flags, 16 /* Flag.assignmentDeoptimized */);
  6900. }
  6901. set assignmentDeoptimized(value) {
  6902. this.flags = setFlag(this.flags, 16 /* Flag.assignmentDeoptimized */, value);
  6903. }
  6904. get bound() {
  6905. return isFlagSet(this.flags, 32 /* Flag.bound */);
  6906. }
  6907. set bound(value) {
  6908. this.flags = setFlag(this.flags, 32 /* Flag.bound */, value);
  6909. }
  6910. get isUndefined() {
  6911. return isFlagSet(this.flags, 64 /* Flag.isUndefined */);
  6912. }
  6913. set isUndefined(value) {
  6914. this.flags = setFlag(this.flags, 64 /* Flag.isUndefined */, value);
  6915. }
  6916. bind() {
  6917. this.bound = true;
  6918. const path = getPathIfNotComputed(this);
  6919. const baseVariable = path && this.scope.findVariable(path[0].key);
  6920. if (baseVariable?.isNamespace) {
  6921. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.scope.context);
  6922. if (!resolvedVariable) {
  6923. super.bind();
  6924. }
  6925. else if (resolvedVariable === 'undefined') {
  6926. this.isUndefined = true;
  6927. }
  6928. else {
  6929. this.variable = resolvedVariable;
  6930. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  6931. }
  6932. }
  6933. else {
  6934. super.bind();
  6935. }
  6936. }
  6937. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6938. if (this.variable) {
  6939. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6940. }
  6941. else if (!this.isUndefined) {
  6942. if (path.length < MAX_PATH_DEPTH) {
  6943. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, this.propertyKey === UnknownKey ? UNKNOWN_PATH : [this.propertyKey, ...path], recursionTracker);
  6944. }
  6945. else {
  6946. deoptimizeInteraction(interaction);
  6947. }
  6948. }
  6949. }
  6950. deoptimizeAssignment(destructuredInitPath, init) {
  6951. this.deoptimizePath(EMPTY_PATH);
  6952. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  6953. }
  6954. deoptimizeCache() {
  6955. if (this.propertyKey === this.dynamicPropertyKey)
  6956. return;
  6957. const { expressionsToBeDeoptimized, object } = this;
  6958. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  6959. this.dynamicPropertyKey = this.propertyKey;
  6960. object.deoptimizePath(UNKNOWN_PATH);
  6961. if (this.included) {
  6962. object.includePath(UNKNOWN_PATH, createInclusionContext());
  6963. }
  6964. for (const expression of expressionsToBeDeoptimized) {
  6965. expression.deoptimizeCache();
  6966. }
  6967. }
  6968. deoptimizePath(path) {
  6969. if (path.length === 0)
  6970. this.disallowNamespaceReassignment();
  6971. if (this.variable) {
  6972. this.variable.deoptimizePath(path);
  6973. }
  6974. else if (!this.isUndefined) {
  6975. const { propertyKey } = this;
  6976. this.object.deoptimizePath([
  6977. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  6978. ...(path.length < MAX_PATH_DEPTH
  6979. ? path
  6980. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  6981. ]);
  6982. }
  6983. }
  6984. getLiteralValueAtPath(path, recursionTracker, origin) {
  6985. if (this.variable) {
  6986. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  6987. }
  6988. if (this.isUndefined) {
  6989. return undefined;
  6990. }
  6991. const propertyKey = this.getDynamicPropertyKey();
  6992. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  6993. if (propertyKey !== this.propertyKey)
  6994. this.expressionsToBeDeoptimized.push(origin);
  6995. return this.object.getLiteralValueAtPath([propertyKey, ...path], recursionTracker, origin);
  6996. }
  6997. return UnknownValue;
  6998. }
  6999. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  7000. if (this.variable) {
  7001. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  7002. }
  7003. if (this.isUndefined) {
  7004. return undefined;
  7005. }
  7006. return getChainElementLiteralValueAtPath(this, this.object, path, recursionTracker, origin);
  7007. }
  7008. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7009. if (this.variable) {
  7010. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7011. }
  7012. if (this.isUndefined) {
  7013. return [UNDEFINED_EXPRESSION, false];
  7014. }
  7015. const propertyKey = this.getDynamicPropertyKey();
  7016. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  7017. if (propertyKey !== this.propertyKey)
  7018. this.expressionsToBeDeoptimized.push(origin);
  7019. return this.object.getReturnExpressionWhenCalledAtPath([propertyKey, ...path], interaction, recursionTracker, origin);
  7020. }
  7021. return UNKNOWN_RETURN_EXPRESSION;
  7022. }
  7023. hasEffects(context) {
  7024. if (!this.deoptimized)
  7025. this.applyDeoptimizations();
  7026. return (this.property.hasEffects(context) ||
  7027. this.object.hasEffects(context) ||
  7028. this.hasAccessEffect(context));
  7029. }
  7030. hasEffectsAsChainElement(context) {
  7031. if (this.variable || this.isUndefined)
  7032. return this.hasEffects(context);
  7033. const objectHasEffects = 'hasEffectsAsChainElement' in this.object
  7034. ? this.object.hasEffectsAsChainElement(context)
  7035. : this.object.hasEffects(context);
  7036. if (objectHasEffects === IS_SKIPPED_CHAIN)
  7037. return IS_SKIPPED_CHAIN;
  7038. if (this.optional &&
  7039. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  7040. return objectHasEffects || IS_SKIPPED_CHAIN;
  7041. }
  7042. // We only apply deoptimizations lazily once we know we are not skipping
  7043. if (!this.deoptimized)
  7044. this.applyDeoptimizations();
  7045. return objectHasEffects || this.property.hasEffects(context) || this.hasAccessEffect(context);
  7046. }
  7047. hasEffectsAsAssignmentTarget(context, checkAccess) {
  7048. if (checkAccess && !this.deoptimized)
  7049. this.applyDeoptimizations();
  7050. if (!this.assignmentDeoptimized)
  7051. this.applyAssignmentDeoptimization();
  7052. return (this.property.hasEffects(context) ||
  7053. this.object.hasEffects(context) ||
  7054. (checkAccess && this.hasAccessEffect(context)) ||
  7055. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  7056. }
  7057. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7058. if (this.variable) {
  7059. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  7060. }
  7061. if (this.isUndefined) {
  7062. return true;
  7063. }
  7064. if (path.length < MAX_PATH_DEPTH) {
  7065. return this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey(), ...path], interaction, context);
  7066. }
  7067. return true;
  7068. }
  7069. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  7070. return (destructuredInitPath.length > 0 &&
  7071. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  7072. }
  7073. include(context, includeChildrenRecursively) {
  7074. if (!this.included)
  7075. this.includeNode(context);
  7076. this.object.include(context, includeChildrenRecursively);
  7077. this.property.include(context, includeChildrenRecursively);
  7078. }
  7079. includeNode(context) {
  7080. this.included = true;
  7081. if (!this.deoptimized)
  7082. this.applyDeoptimizations();
  7083. if (this.variable) {
  7084. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  7085. }
  7086. else if (!this.isUndefined) {
  7087. this.object.includePath([this.propertyKey], context);
  7088. }
  7089. }
  7090. includeNodeAsAssignmentTarget(context) {
  7091. this.included = true;
  7092. if (!this.assignmentDeoptimized)
  7093. this.applyAssignmentDeoptimization();
  7094. if (this.variable) {
  7095. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  7096. }
  7097. else if (!this.isUndefined) {
  7098. this.object.includePath([this.propertyKey], context);
  7099. }
  7100. }
  7101. includePath(path, context) {
  7102. if (!this.included)
  7103. this.includeNode(context);
  7104. if (this.variable) {
  7105. this.variable?.includePath(path, context);
  7106. }
  7107. else if (!this.isUndefined) {
  7108. this.object.includePath([
  7109. this.propertyKey,
  7110. ...(path.length < MAX_PATH_DEPTH
  7111. ? path
  7112. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  7113. ], context);
  7114. }
  7115. }
  7116. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  7117. if (!this.included)
  7118. this.includeNodeAsAssignmentTarget(context);
  7119. if (deoptimizeAccess && !this.deoptimized)
  7120. this.applyDeoptimizations();
  7121. this.object.include(context, includeChildrenRecursively);
  7122. this.property.include(context, includeChildrenRecursively);
  7123. }
  7124. includeCallArguments(interaction, context) {
  7125. if (this.variable) {
  7126. this.variable.includeCallArguments(interaction, context);
  7127. }
  7128. else {
  7129. if (isImportExpressionNode(this.object) ||
  7130. /**
  7131. * const c = await import('foo')
  7132. * c.foo();
  7133. */
  7134. (this.object.variable &&
  7135. !this.object.variable.isReassigned &&
  7136. this.object.variable instanceof LocalVariable &&
  7137. isAwaitExpressionNode(this.object.variable.init) &&
  7138. isImportExpressionNode(this.object.variable.init.argument))) {
  7139. includeInteractionWithoutThis(interaction, context);
  7140. }
  7141. else {
  7142. includeInteraction(interaction, context);
  7143. }
  7144. }
  7145. }
  7146. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  7147. if ((this.included ||=
  7148. destructuredInitPath.length > 0 &&
  7149. !context.brokenFlow &&
  7150. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext()))) {
  7151. init.include(context, false);
  7152. return true;
  7153. }
  7154. return false;
  7155. }
  7156. initialise() {
  7157. super.initialise();
  7158. this.dynamicPropertyKey = getResolvablePropertyKey(this);
  7159. this.propertyKey = this.dynamicPropertyKey === null ? UnknownKey : this.dynamicPropertyKey;
  7160. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  7161. }
  7162. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  7163. if (this.variable || this.isUndefined) {
  7164. const { snippets: { getPropertyAccess } } = options;
  7165. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  7166. if (renderedParentType && isCalleeOfRenderedParent)
  7167. replacement = '0, ' + replacement;
  7168. code.overwrite(this.start, this.end, replacement, {
  7169. contentOnly: true,
  7170. storeName: true
  7171. });
  7172. }
  7173. else {
  7174. if (renderedParentType && isCalleeOfRenderedParent) {
  7175. code.appendRight(this.start, '0, ');
  7176. }
  7177. this.object.render(code, options, { renderedSurroundingElement });
  7178. this.property.render(code, options);
  7179. }
  7180. }
  7181. setAssignedValue(value) {
  7182. this.assignmentInteraction = {
  7183. args: [this.object, value],
  7184. type: INTERACTION_ASSIGNED
  7185. };
  7186. }
  7187. applyDeoptimizations() {
  7188. this.deoptimized = true;
  7189. const { propertyReadSideEffects } = this.scope.context.options
  7190. .treeshake;
  7191. if (
  7192. // Namespaces are not bound and should not be deoptimized
  7193. this.bound &&
  7194. propertyReadSideEffects &&
  7195. !(this.variable || this.isUndefined)) {
  7196. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  7197. this.scope.context.requestTreeshakingPass();
  7198. }
  7199. if (this.variable) {
  7200. this.variable.addUsedPlace(this);
  7201. this.scope.context.requestTreeshakingPass();
  7202. }
  7203. }
  7204. applyAssignmentDeoptimization() {
  7205. this.assignmentDeoptimized = true;
  7206. const { propertyReadSideEffects } = this.scope.context.options
  7207. .treeshake;
  7208. if (
  7209. // Namespaces are not bound and should not be deoptimized
  7210. this.bound &&
  7211. propertyReadSideEffects &&
  7212. !(this.variable || this.isUndefined)) {
  7213. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  7214. this.scope.context.requestTreeshakingPass();
  7215. }
  7216. }
  7217. disallowNamespaceReassignment() {
  7218. if (this.object instanceof Identifier) {
  7219. const variable = this.scope.findVariable(this.object.name);
  7220. if (variable.isNamespace) {
  7221. if (this.variable) {
  7222. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, createInclusionContext());
  7223. }
  7224. this.scope.context.log(LOGLEVEL_WARN, logIllegalImportReassignment(this.object.name, this.scope.context.module.id), this.start);
  7225. }
  7226. }
  7227. }
  7228. getDynamicPropertyKey() {
  7229. if (this.dynamicPropertyKey === null) {
  7230. this.dynamicPropertyKey = this.propertyKey;
  7231. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7232. return (this.dynamicPropertyKey =
  7233. value === SymbolToStringTag
  7234. ? value
  7235. : typeof value === 'symbol'
  7236. ? UnknownKey
  7237. : String(value));
  7238. }
  7239. return this.dynamicPropertyKey;
  7240. }
  7241. hasAccessEffect(context) {
  7242. const { propertyReadSideEffects } = this.scope.context.options
  7243. .treeshake;
  7244. return (!(this.variable || this.isUndefined) &&
  7245. propertyReadSideEffects &&
  7246. (propertyReadSideEffects === 'always' ||
  7247. this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey()], this.accessInteraction, context)));
  7248. }
  7249. }
  7250. function resolveNamespaceVariables(baseVariable, path, astContext) {
  7251. if (path.length === 0)
  7252. return baseVariable;
  7253. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  7254. return null;
  7255. const exportName = path[0].key;
  7256. const variable = baseVariable.context.traceExport(exportName);
  7257. if (!variable) {
  7258. if (path.length === 1) {
  7259. const fileName = baseVariable.context.fileName;
  7260. astContext.log(LOGLEVEL_WARN, logMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  7261. return 'undefined';
  7262. }
  7263. return null;
  7264. }
  7265. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  7266. }
  7267. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  7268. const IMPORT = 'import';
  7269. class MetaProperty extends NodeBase {
  7270. constructor() {
  7271. super(...arguments);
  7272. this.metaProperty = null;
  7273. this.preliminaryChunkId = null;
  7274. this.referenceId = null;
  7275. }
  7276. getReferencedFileName(outputPluginDriver) {
  7277. const { meta: { name }, metaProperty } = this;
  7278. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  7279. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  7280. }
  7281. return null;
  7282. }
  7283. hasEffects() {
  7284. return false;
  7285. }
  7286. hasEffectsOnInteractionAtPath(path, { type }) {
  7287. return path.length > 1 || type !== INTERACTION_ACCESSED;
  7288. }
  7289. include() {
  7290. if (!this.included)
  7291. this.includeNode();
  7292. }
  7293. includeNode() {
  7294. this.included = true;
  7295. if (this.meta.name === IMPORT) {
  7296. this.scope.context.addImportMeta(this);
  7297. const parent = this.parent;
  7298. const metaProperty = (this.metaProperty =
  7299. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  7300. ? parent.propertyKey
  7301. : null);
  7302. if (metaProperty?.startsWith(FILE_PREFIX)) {
  7303. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  7304. }
  7305. }
  7306. }
  7307. render(code, renderOptions) {
  7308. const { format, pluginDriver, snippets } = renderOptions;
  7309. const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  7310. const { id: moduleId } = module;
  7311. if (name !== IMPORT)
  7312. return;
  7313. const chunkId = preliminaryChunkId;
  7314. if (referenceId) {
  7315. const fileName = pluginDriver.getFileName(referenceId);
  7316. const relativePath = normalize(relative(dirname(chunkId), fileName));
  7317. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  7318. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  7319. ]) || relativeUrlMechanisms[format](relativePath);
  7320. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7321. return;
  7322. }
  7323. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  7324. metaProperty,
  7325. { chunkId, format, moduleId }
  7326. ]);
  7327. if (!replacement) {
  7328. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  7329. renderOptions.accessedDocumentCurrentScript ||=
  7330. formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
  7331. }
  7332. if (typeof replacement === 'string') {
  7333. if (parent instanceof MemberExpression) {
  7334. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7335. }
  7336. else {
  7337. code.overwrite(start, end, replacement, { contentOnly: true });
  7338. }
  7339. }
  7340. }
  7341. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  7342. this.preliminaryChunkId = preliminaryChunkId;
  7343. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  7344. if (accessedGlobals.length > 0) {
  7345. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7346. }
  7347. }
  7348. }
  7349. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  7350. const accessedMetaUrlGlobals = {
  7351. amd: ['document', 'module', 'URL'],
  7352. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  7353. es: [],
  7354. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  7355. system: ['module'],
  7356. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  7357. };
  7358. const accessedFileUrlGlobals = {
  7359. amd: ['document', 'require', 'URL'],
  7360. cjs: ['document', 'require', 'URL'],
  7361. es: [],
  7362. iife: ['document', 'URL'],
  7363. system: ['module', 'URL'],
  7364. umd: ['document', 'require', 'URL']
  7365. };
  7366. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  7367. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`);
  7368. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  7369. const urlMechanism = getUrl(chunkId);
  7370. return property === null
  7371. ? `({ url: ${urlMechanism} })`
  7372. : property === 'url'
  7373. ? urlMechanism
  7374. : 'undefined';
  7375. };
  7376. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  7377. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
  7378. 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)`;
  7379. const relativeUrlMechanisms = {
  7380. amd: relativePath => {
  7381. if (relativePath[0] !== '.')
  7382. relativePath = './' + relativePath;
  7383. return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
  7384. },
  7385. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  7386. es: relativePath => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`),
  7387. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  7388. system: relativePath => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`),
  7389. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  7390. };
  7391. const importMetaMechanisms = {
  7392. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  7393. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  7394. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  7395. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  7396. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  7397. };
  7398. class UndefinedVariable extends Variable {
  7399. constructor() {
  7400. super('undefined');
  7401. }
  7402. getLiteralValueAtPath() {
  7403. return undefined;
  7404. }
  7405. }
  7406. class ExportDefaultVariable extends LocalVariable {
  7407. constructor(name, exportDefaultDeclaration, context) {
  7408. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, EMPTY_PATH, context, 'other');
  7409. this.hasId = false;
  7410. this.originalId = null;
  7411. this.originalVariable = null;
  7412. const declaration = exportDefaultDeclaration.declaration;
  7413. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  7414. declaration.id) {
  7415. this.hasId = true;
  7416. this.originalId = declaration.id;
  7417. }
  7418. else if (declaration instanceof Identifier) {
  7419. this.originalId = declaration;
  7420. }
  7421. }
  7422. addReference(identifier) {
  7423. if (!this.hasId) {
  7424. this.name = identifier.name;
  7425. }
  7426. }
  7427. addUsedPlace(usedPlace) {
  7428. const original = this.getOriginalVariable();
  7429. if (original === this) {
  7430. super.addUsedPlace(usedPlace);
  7431. }
  7432. else {
  7433. original.addUsedPlace(usedPlace);
  7434. }
  7435. }
  7436. forbidName(name) {
  7437. const original = this.getOriginalVariable();
  7438. if (original === this) {
  7439. super.forbidName(name);
  7440. }
  7441. else {
  7442. original.forbidName(name);
  7443. }
  7444. }
  7445. getAssignedVariableName() {
  7446. return (this.originalId && this.originalId.name) || null;
  7447. }
  7448. getBaseVariableName() {
  7449. const original = this.getOriginalVariable();
  7450. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  7451. }
  7452. getDirectOriginalVariable() {
  7453. return this.originalId &&
  7454. (this.hasId ||
  7455. !(this.originalId.isPossibleTDZ() ||
  7456. this.originalId.variable.isReassigned ||
  7457. this.originalId.variable instanceof UndefinedVariable ||
  7458. // this avoids a circular dependency
  7459. 'syntheticNamespace' in this.originalId.variable))
  7460. ? this.originalId.variable
  7461. : null;
  7462. }
  7463. getName(getPropertyAccess) {
  7464. const original = this.getOriginalVariable();
  7465. return original === this
  7466. ? super.getName(getPropertyAccess)
  7467. : original.getName(getPropertyAccess);
  7468. }
  7469. getOriginalVariable() {
  7470. if (this.originalVariable)
  7471. return this.originalVariable;
  7472. // eslint-disable-next-line @typescript-eslint/no-this-alias
  7473. let original = this;
  7474. let currentVariable;
  7475. const checkedVariables = new Set();
  7476. do {
  7477. checkedVariables.add(original);
  7478. currentVariable = original;
  7479. original = currentVariable.getDirectOriginalVariable();
  7480. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  7481. return (this.originalVariable = original || currentVariable);
  7482. }
  7483. }
  7484. class NamespaceVariable extends Variable {
  7485. constructor(context) {
  7486. super(context.getModuleName());
  7487. this.memberVariables = null;
  7488. this.mergedNamespaces = [];
  7489. this.referencedEarly = false;
  7490. this.references = [];
  7491. this.context = context;
  7492. this.module = context.module;
  7493. }
  7494. addReference(identifier) {
  7495. this.references.push(identifier);
  7496. this.name = identifier.name;
  7497. }
  7498. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7499. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  7500. const key = path[0];
  7501. if (typeof key === 'string') {
  7502. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  7503. }
  7504. else {
  7505. deoptimizeInteraction(interaction);
  7506. }
  7507. }
  7508. }
  7509. deoptimizePath(path) {
  7510. if (path.length > 1) {
  7511. const key = path[0];
  7512. if (typeof key === 'string') {
  7513. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  7514. }
  7515. }
  7516. }
  7517. getLiteralValueAtPath(path) {
  7518. if (path[0] === SymbolToStringTag) {
  7519. return 'Module';
  7520. }
  7521. return UnknownValue;
  7522. }
  7523. getMemberVariables() {
  7524. if (this.memberVariables) {
  7525. return this.memberVariables;
  7526. }
  7527. const memberVariables = Object.create(null);
  7528. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  7529. for (const name of sortedExports) {
  7530. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  7531. const exportedVariable = this.context.traceExport(name);
  7532. if (exportedVariable) {
  7533. memberVariables[name] = exportedVariable;
  7534. }
  7535. }
  7536. }
  7537. return (this.memberVariables = memberVariables);
  7538. }
  7539. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7540. const { type } = interaction;
  7541. if (path.length === 0) {
  7542. // This can only be a call anyway
  7543. return true;
  7544. }
  7545. if (path.length === 1 && type !== INTERACTION_CALLED) {
  7546. return type === INTERACTION_ASSIGNED;
  7547. }
  7548. const key = path[0];
  7549. if (typeof key !== 'string') {
  7550. return true;
  7551. }
  7552. const memberVariable = this.getMemberVariables()[key];
  7553. return (!memberVariable ||
  7554. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  7555. }
  7556. includePath(path, context) {
  7557. super.includePath(path, context);
  7558. this.context.includeAllExports();
  7559. }
  7560. prepare(accessedGlobalsByScope) {
  7561. if (this.mergedNamespaces.length > 0) {
  7562. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  7563. }
  7564. }
  7565. renderBlock(options) {
  7566. const { exportNamesByVariable, format, freeze, indent: t, symbols, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  7567. const memberVariables = this.getMemberVariables();
  7568. const members = Object.entries(memberVariables)
  7569. .filter(([_, variable]) => variable.included)
  7570. .map(([name, variable]) => {
  7571. if (this.referencedEarly || variable.isReassigned || variable === this) {
  7572. return [
  7573. null,
  7574. `get ${stringifyObjectKeyIfNeeded(name)}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  7575. ];
  7576. }
  7577. return [name, variable.getName(getPropertyAccess)];
  7578. });
  7579. members.unshift([null, `__proto__:${_}null`]);
  7580. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  7581. if (this.mergedNamespaces.length > 0) {
  7582. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  7583. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  7584. }
  7585. else {
  7586. // The helper to merge namespaces will also take care of freezing and toStringTag
  7587. if (symbols) {
  7588. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  7589. }
  7590. if (freeze) {
  7591. output = `/*#__PURE__*/Object.freeze(${output})`;
  7592. }
  7593. }
  7594. const name = this.getName(getPropertyAccess);
  7595. output = `${cnst} ${name}${_}=${_}${output};`;
  7596. if (format === 'system' && exportNamesByVariable.has(this)) {
  7597. output += `${n}${getSystemExportStatement([this], options)};`;
  7598. }
  7599. return output;
  7600. }
  7601. renderFirst() {
  7602. return this.referencedEarly;
  7603. }
  7604. setMergedNamespaces(mergedNamespaces) {
  7605. this.mergedNamespaces = mergedNamespaces;
  7606. const moduleExecIndex = this.context.getModuleExecIndex();
  7607. for (const identifier of this.references) {
  7608. const { context } = identifier.scope;
  7609. if (context.getModuleExecIndex() <= moduleExecIndex) {
  7610. this.referencedEarly = true;
  7611. break;
  7612. }
  7613. }
  7614. }
  7615. }
  7616. NamespaceVariable.prototype.isNamespace = true;
  7617. class SyntheticNamedExportVariable extends Variable {
  7618. constructor(context, name, syntheticNamespace) {
  7619. super(name);
  7620. this.baseVariable = null;
  7621. this.context = context;
  7622. this.module = context.module;
  7623. this.syntheticNamespace = syntheticNamespace;
  7624. }
  7625. getBaseVariable() {
  7626. if (this.baseVariable)
  7627. return this.baseVariable;
  7628. let baseVariable = this.syntheticNamespace;
  7629. while (baseVariable instanceof ExportDefaultVariable ||
  7630. baseVariable instanceof SyntheticNamedExportVariable) {
  7631. if (baseVariable instanceof ExportDefaultVariable) {
  7632. const original = baseVariable.getOriginalVariable();
  7633. if (original === baseVariable)
  7634. break;
  7635. baseVariable = original;
  7636. }
  7637. if (baseVariable instanceof SyntheticNamedExportVariable) {
  7638. baseVariable = baseVariable.syntheticNamespace;
  7639. }
  7640. }
  7641. return (this.baseVariable = baseVariable);
  7642. }
  7643. getBaseVariableName() {
  7644. return this.syntheticNamespace.getBaseVariableName();
  7645. }
  7646. getName(getPropertyAccess) {
  7647. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  7648. }
  7649. includePath(path, context) {
  7650. super.includePath(path, context);
  7651. this.context.includeVariableInModule(this.syntheticNamespace, path, context);
  7652. }
  7653. setRenderNames(baseName, name) {
  7654. super.setRenderNames(baseName, name);
  7655. }
  7656. }
  7657. class ExternalChunk {
  7658. constructor(module, options, inputBase) {
  7659. this.options = options;
  7660. this.inputBase = inputBase;
  7661. this.defaultVariableName = '';
  7662. this.namespaceVariableName = '';
  7663. this.variableName = '';
  7664. this.fileName = null;
  7665. this.importAttributes = null;
  7666. this.id = module.id;
  7667. this.moduleInfo = module.info;
  7668. this.renormalizeRenderPath = module.renormalizeRenderPath;
  7669. this.suggestedVariableName = module.suggestedVariableName;
  7670. }
  7671. getFileName() {
  7672. if (this.fileName) {
  7673. return this.fileName;
  7674. }
  7675. const { paths } = this.options;
  7676. return (this.fileName =
  7677. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  7678. (this.renormalizeRenderPath ? normalize(relative(this.inputBase, this.id)) : this.id));
  7679. }
  7680. getImportAttributes(snippets) {
  7681. return (this.importAttributes ||= formatAttributes(['es', 'cjs'].includes(this.options.format) &&
  7682. this.options.externalImportAttributes &&
  7683. this.moduleInfo.attributes, snippets));
  7684. }
  7685. getImportPath(importer) {
  7686. return escapeId(this.renormalizeRenderPath
  7687. ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  7688. : this.getFileName());
  7689. }
  7690. }
  7691. function formatAttributes(attributes, { getObject }) {
  7692. if (!attributes) {
  7693. return null;
  7694. }
  7695. const assertionEntries = Object.entries(attributes).map(([key, value]) => [key, `'${value}'`]);
  7696. if (assertionEntries.length > 0) {
  7697. return getObject(assertionEntries, { lineBreakIndent: null });
  7698. }
  7699. return null;
  7700. }
  7701. function removeJsExtension(name) {
  7702. return name.endsWith('.js') ? name.slice(0, -3) : name;
  7703. }
  7704. function getCompleteAmdId(options, chunkId) {
  7705. if (options.autoId) {
  7706. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  7707. }
  7708. return options.id ?? '';
  7709. }
  7710. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
  7711. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  7712. if (!namedExportsMode) {
  7713. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  7714. }
  7715. let exportBlock = '';
  7716. if (namedExportsMode) {
  7717. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7718. if (!reexports) {
  7719. continue;
  7720. }
  7721. for (const specifier of reexports) {
  7722. if (specifier.reexported !== '*') {
  7723. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  7724. if (exportBlock)
  7725. exportBlock += n;
  7726. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  7727. const [left, right] = getDirectReturnFunction([], {
  7728. functionReturn: true,
  7729. lineBreakIndent: null,
  7730. name: null
  7731. });
  7732. exportBlock +=
  7733. `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
  7734. `${t}enumerable:${_}true,${n}` +
  7735. `${t}get:${_}${left}${importName}${right}${n}});`;
  7736. }
  7737. else if (specifier.reexported === '__proto__') {
  7738. exportBlock +=
  7739. `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  7740. `${t}enumerable:${_}true,${n}` +
  7741. `${t}value:${_}${importName}${n}});`;
  7742. }
  7743. else {
  7744. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  7745. }
  7746. }
  7747. }
  7748. }
  7749. }
  7750. for (const { exported, local } of exports) {
  7751. const lhs = `exports${getPropertyAccess(exported)}`;
  7752. const rhs = local;
  7753. if (lhs !== rhs) {
  7754. if (exportBlock)
  7755. exportBlock += n;
  7756. exportBlock +=
  7757. exported === '__proto__'
  7758. ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  7759. `${t}enumerable:${_}true,${n}` +
  7760. `${t}value:${_}${rhs}${n}});`
  7761. : `${lhs}${_}=${_}${rhs};`;
  7762. }
  7763. }
  7764. if (namedExportsMode) {
  7765. for (const { name, reexports } of dependencies) {
  7766. if (!reexports) {
  7767. continue;
  7768. }
  7769. for (const specifier of reexports) {
  7770. if (specifier.reexported === '*') {
  7771. if (exportBlock)
  7772. exportBlock += n;
  7773. if (!specifier.needsLiveBinding && reexportProtoFromExternal) {
  7774. const protoString = "'__proto__'";
  7775. exportBlock +=
  7776. `Object.prototype.hasOwnProperty.call(${name},${_}${protoString})${_}&&${n}` +
  7777. `${t}!Object.prototype.hasOwnProperty.call(exports,${_}${protoString})${_}&&${n}` +
  7778. `${t}Object.defineProperty(exports,${_}${protoString},${_}{${n}` +
  7779. `${t}${t}enumerable:${_}true,${n}` +
  7780. `${t}${t}value:${_}${name}[${protoString}]${n}` +
  7781. `${t}});${n}${n}`;
  7782. }
  7783. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  7784. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  7785. isAsync: false,
  7786. name: null
  7787. })}${copyPropertyIfNecessary});`;
  7788. }
  7789. }
  7790. }
  7791. }
  7792. if (exportBlock) {
  7793. return `${n}${n}${exportBlock}`;
  7794. }
  7795. return '';
  7796. }
  7797. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  7798. if (exports.length > 0) {
  7799. return exports[0].local;
  7800. }
  7801. else {
  7802. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7803. if (reexports) {
  7804. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  7805. }
  7806. }
  7807. }
  7808. }
  7809. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  7810. if (imported === 'default') {
  7811. if (!isChunk) {
  7812. const moduleInterop = interop(moduleId);
  7813. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  7814. ? defaultVariableName
  7815. : moduleVariableName;
  7816. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  7817. ? `${variableName}${getPropertyAccess('default')}`
  7818. : variableName;
  7819. }
  7820. return depNamedExportsMode
  7821. ? `${moduleVariableName}${getPropertyAccess('default')}`
  7822. : moduleVariableName;
  7823. }
  7824. if (imported === '*') {
  7825. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  7826. ? namespaceVariableName
  7827. : moduleVariableName;
  7828. }
  7829. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  7830. }
  7831. function getEsModuleValue(getObject) {
  7832. return getObject([['value', 'true']], {
  7833. lineBreakIndent: null
  7834. });
  7835. }
  7836. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  7837. if (hasNamedExports) {
  7838. if (addEsModule) {
  7839. if (addNamespaceToStringTag) {
  7840. return `Object.defineProperties(exports,${_}${getObject([
  7841. ['__esModule', getEsModuleValue(getObject)],
  7842. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  7843. ], {
  7844. lineBreakIndent: null
  7845. })});`;
  7846. }
  7847. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  7848. }
  7849. if (addNamespaceToStringTag) {
  7850. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  7851. }
  7852. }
  7853. return '';
  7854. }
  7855. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  7856. if (needsLiveBinding) {
  7857. const [left, right] = getDirectReturnFunction([], {
  7858. functionReturn: true,
  7859. lineBreakIndent: null,
  7860. name: null
  7861. });
  7862. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  7863. `${t}${t}enumerable:${_}true,${n}` +
  7864. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  7865. }
  7866. return `exports[k]${_}=${_}${name}[k]`;
  7867. };
  7868. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
  7869. const { _, cnst, n } = snippets;
  7870. const neededInteropHelpers = new Set();
  7871. const interopStatements = [];
  7872. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  7873. neededInteropHelpers.add(helper);
  7874. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  7875. };
  7876. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7877. if (isChunk) {
  7878. for (const { imported, reexported } of [
  7879. ...(imports || []),
  7880. ...(reexports || [])
  7881. ]) {
  7882. if (imported === '*' && reexported !== '*') {
  7883. if (!namedExportsMode) {
  7884. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  7885. }
  7886. break;
  7887. }
  7888. }
  7889. }
  7890. else {
  7891. const moduleInterop = interop(importPath);
  7892. let hasDefault = false;
  7893. let hasNamespace = false;
  7894. for (const { imported, reexported } of [
  7895. ...(imports || []),
  7896. ...(reexports || [])
  7897. ]) {
  7898. let helper;
  7899. let variableName;
  7900. if (imported === 'default') {
  7901. if (!hasDefault) {
  7902. hasDefault = true;
  7903. if (defaultVariableName !== namespaceVariableName) {
  7904. variableName = defaultVariableName;
  7905. helper = defaultInteropHelpersByInteropType[moduleInterop];
  7906. }
  7907. }
  7908. }
  7909. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  7910. hasNamespace = true;
  7911. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  7912. variableName = namespaceVariableName;
  7913. }
  7914. if (helper) {
  7915. addInteropStatement(variableName, helper, name);
  7916. }
  7917. }
  7918. }
  7919. }
  7920. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, symbols)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  7921. }
  7922. function addJsExtension(name) {
  7923. return name.endsWith('.js') ? name : name + '.js';
  7924. }
  7925. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  7926. // The assumption is that this makes sense for all relative ids:
  7927. // https://requirejs.org/docs/api.html#jsfiles
  7928. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  7929. if (id[0] !== '.') {
  7930. return id;
  7931. }
  7932. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  7933. }
  7934. const builtinModules = [
  7935. "node:assert",
  7936. "assert",
  7937. "node:assert/strict",
  7938. "assert/strict",
  7939. "node:async_hooks",
  7940. "async_hooks",
  7941. "node:buffer",
  7942. "buffer",
  7943. "node:child_process",
  7944. "child_process",
  7945. "node:cluster",
  7946. "cluster",
  7947. "node:console",
  7948. "console",
  7949. "node:constants",
  7950. "constants",
  7951. "node:crypto",
  7952. "crypto",
  7953. "node:dgram",
  7954. "dgram",
  7955. "node:diagnostics_channel",
  7956. "diagnostics_channel",
  7957. "node:dns",
  7958. "dns",
  7959. "node:dns/promises",
  7960. "dns/promises",
  7961. "node:domain",
  7962. "domain",
  7963. "node:events",
  7964. "events",
  7965. "node:fs",
  7966. "fs",
  7967. "node:fs/promises",
  7968. "fs/promises",
  7969. "node:http",
  7970. "http",
  7971. "node:http2",
  7972. "http2",
  7973. "node:https",
  7974. "https",
  7975. "node:inspector",
  7976. "inspector",
  7977. "node:inspector/promises",
  7978. "inspector/promises",
  7979. "node:module",
  7980. "module",
  7981. "node:net",
  7982. "net",
  7983. "node:os",
  7984. "os",
  7985. "node:path",
  7986. "path",
  7987. "node:path/posix",
  7988. "path/posix",
  7989. "node:path/win32",
  7990. "path/win32",
  7991. "node:perf_hooks",
  7992. "perf_hooks",
  7993. "node:process",
  7994. "process",
  7995. "node:querystring",
  7996. "querystring",
  7997. "node:quic",
  7998. "node:readline",
  7999. "readline",
  8000. "node:readline/promises",
  8001. "readline/promises",
  8002. "node:repl",
  8003. "repl",
  8004. "node:sea",
  8005. "node:sqlite",
  8006. "node:stream",
  8007. "stream",
  8008. "node:stream/consumers",
  8009. "stream/consumers",
  8010. "node:stream/promises",
  8011. "stream/promises",
  8012. "node:stream/web",
  8013. "stream/web",
  8014. "node:string_decoder",
  8015. "string_decoder",
  8016. "node:test",
  8017. "node:test/reporters",
  8018. "node:timers",
  8019. "timers",
  8020. "node:timers/promises",
  8021. "timers/promises",
  8022. "node:tls",
  8023. "tls",
  8024. "node:trace_events",
  8025. "trace_events",
  8026. "node:tty",
  8027. "tty",
  8028. "node:url",
  8029. "url",
  8030. "node:util",
  8031. "util",
  8032. "node:util/types",
  8033. "util/types",
  8034. "node:v8",
  8035. "v8",
  8036. "node:vm",
  8037. "vm",
  8038. "node:wasi",
  8039. "wasi",
  8040. "node:worker_threads",
  8041. "worker_threads",
  8042. "node:zlib",
  8043. "zlib"
  8044. ];
  8045. const nodeBuiltins = new Set(builtinModules);
  8046. function warnOnBuiltins(log, dependencies) {
  8047. const externalBuiltins = dependencies
  8048. .map(({ importPath }) => importPath)
  8049. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  8050. if (externalBuiltins.length === 0)
  8051. return;
  8052. log(LOGLEVEL_WARN, logMissingNodeBuiltins(externalBuiltins));
  8053. }
  8054. 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 }) {
  8055. warnOnBuiltins(log, dependencies);
  8056. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  8057. const parameters = dependencies.map(m => m.name);
  8058. const { n, getNonArrowFunctionIntro, _ } = snippets;
  8059. if (hasExports && (namedExportsMode || exports[0]?.local === 'exports.default')) {
  8060. parameters.unshift(`exports`);
  8061. deps.unshift(`'exports'`);
  8062. }
  8063. if (accessedGlobals.has('require')) {
  8064. parameters.unshift('require');
  8065. deps.unshift(`'require'`);
  8066. }
  8067. if (accessedGlobals.has('module')) {
  8068. parameters.unshift('module');
  8069. deps.unshift(`'module'`);
  8070. }
  8071. const completeAmdId = getCompleteAmdId(amd, id);
  8072. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  8073. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  8074. const useStrict = strict ? `${_}'use strict';` : '';
  8075. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  8076. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8077. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  8078. if (namespaceMarkers) {
  8079. namespaceMarkers = n + n + namespaceMarkers;
  8080. }
  8081. magicString
  8082. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8083. .indent(t)
  8084. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8085. // cf. https://v8.dev/blog/preparser#pife
  8086. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  8087. isAsync: false,
  8088. name: null
  8089. })}{${useStrict}${n}${n}`)
  8090. .append(`${n}${n}}));`);
  8091. }
  8092. 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 }) {
  8093. const { _, n } = snippets;
  8094. const useStrict = strict ? `'use strict';${n}${n}` : '';
  8095. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  8096. if (namespaceMarkers) {
  8097. namespaceMarkers += n + n;
  8098. }
  8099. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  8100. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  8101. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  8102. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, `module.exports${_}=${_}`);
  8103. magicString.append(`${exportBlock}${outro}`);
  8104. }
  8105. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  8106. let importBlock = '';
  8107. let definingVariable = false;
  8108. for (const { importPath, name, reexports, imports } of dependencies) {
  8109. if (!reexports && !imports) {
  8110. if (importBlock) {
  8111. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  8112. }
  8113. definingVariable = false;
  8114. importBlock += `require('${importPath}')`;
  8115. }
  8116. else {
  8117. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  8118. definingVariable = true;
  8119. importBlock += `${name}${_}=${_}require('${importPath}')`;
  8120. }
  8121. }
  8122. if (importBlock) {
  8123. return `${importBlock};${n}${n}`;
  8124. }
  8125. return '';
  8126. }
  8127. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, generatedCode: { symbols }, importAttributesKey }) {
  8128. const { n } = snippets;
  8129. const importBlock = getImportBlock(dependencies, importAttributesKey, snippets);
  8130. if (importBlock.length > 0)
  8131. intro += importBlock.join(n) + n + n;
  8132. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols);
  8133. if (intro)
  8134. magicString.prepend(intro);
  8135. const exportBlock = getExportBlock(exports, snippets);
  8136. if (exportBlock.length > 0)
  8137. magicString.append(n + n + exportBlock.join(n).trim());
  8138. if (outro)
  8139. magicString.append(outro);
  8140. magicString.trim();
  8141. }
  8142. function getImportBlock(dependencies, importAttributesKey, { _ }) {
  8143. const importBlock = [];
  8144. for (const { importPath, reexports, imports, name, attributes } of dependencies) {
  8145. const assertion = attributes ? `${_}${importAttributesKey}${_}${attributes}` : '';
  8146. const pathWithAssertion = `'${importPath}'${assertion};`;
  8147. if (!reexports && !imports) {
  8148. importBlock.push(`import${_}${pathWithAssertion}`);
  8149. continue;
  8150. }
  8151. if (imports) {
  8152. let defaultImport = null;
  8153. let starImport = null;
  8154. const importedNames = [];
  8155. for (const specifier of imports) {
  8156. if (specifier.imported === 'default') {
  8157. defaultImport = specifier;
  8158. }
  8159. else if (specifier.imported === '*') {
  8160. starImport = specifier;
  8161. }
  8162. else {
  8163. importedNames.push(specifier);
  8164. }
  8165. }
  8166. if (starImport) {
  8167. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  8168. }
  8169. if (defaultImport && importedNames.length === 0) {
  8170. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  8171. }
  8172. else if (importedNames.length > 0) {
  8173. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  8174. .map(specifier => specifier.imported === specifier.local
  8175. ? specifier.imported
  8176. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${specifier.local}`)
  8177. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  8178. }
  8179. }
  8180. if (reexports) {
  8181. let starExport = null;
  8182. const namespaceReexports = [];
  8183. const namedReexports = [];
  8184. for (const specifier of reexports) {
  8185. if (specifier.reexported === '*') {
  8186. starExport = specifier;
  8187. }
  8188. else if (specifier.imported === '*') {
  8189. namespaceReexports.push(specifier);
  8190. }
  8191. else {
  8192. namedReexports.push(specifier);
  8193. }
  8194. }
  8195. if (starExport) {
  8196. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  8197. }
  8198. if (namespaceReexports.length > 0) {
  8199. if (!imports ||
  8200. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  8201. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  8202. }
  8203. for (const specifier of namespaceReexports) {
  8204. importBlock.push(`export${_}{${_}${name === specifier.reexported
  8205. ? name
  8206. : `${name} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`} };`);
  8207. }
  8208. }
  8209. if (namedReexports.length > 0) {
  8210. importBlock.push(`export${_}{${_}${namedReexports
  8211. .map(specifier => specifier.imported === specifier.reexported
  8212. ? stringifyIdentifierIfNeeded(specifier.imported)
  8213. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`)
  8214. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  8215. }
  8216. }
  8217. }
  8218. return importBlock;
  8219. }
  8220. function getExportBlock(exports, { _, cnst }) {
  8221. const exportBlock = [];
  8222. const exportDeclaration = new Array(exports.length);
  8223. let index = 0;
  8224. for (const specifier of exports) {
  8225. if (specifier.expression) {
  8226. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  8227. }
  8228. exportDeclaration[index++] =
  8229. specifier.exported === specifier.local
  8230. ? specifier.local
  8231. : `${specifier.local} as ${stringifyIdentifierIfNeeded(specifier.exported)}`;
  8232. }
  8233. if (exportDeclaration.length > 0) {
  8234. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  8235. }
  8236. return exportBlock;
  8237. }
  8238. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  8239. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact, log) {
  8240. const parts = name.split('.');
  8241. // Check if the key exists in the object's prototype.
  8242. const isReserved = parts[0] in Object.prototype;
  8243. if (log && isReserved) {
  8244. log(LOGLEVEL_WARN, logReservedNamespace(parts[0]));
  8245. }
  8246. parts[0] =
  8247. (typeof globals === 'function'
  8248. ? globals(parts[0])
  8249. : isReserved
  8250. ? parts[0]
  8251. : globals[parts[0]]) || parts[0];
  8252. parts.pop();
  8253. let propertyPath = root;
  8254. return (parts
  8255. .map(part => {
  8256. propertyPath += getPropertyAccess(part);
  8257. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  8258. })
  8259. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  8260. }
  8261. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }, log) {
  8262. const parts = deepName.split('.');
  8263. // Check if the key exists in the object's prototype.
  8264. const isReserved = parts[0] in Object.prototype;
  8265. if (log && isReserved) {
  8266. log(LOGLEVEL_WARN, logReservedNamespace(parts[0]));
  8267. }
  8268. parts[0] =
  8269. (typeof globals === 'function'
  8270. ? globals(parts[0])
  8271. : isReserved
  8272. ? parts[0]
  8273. : globals[parts[0]]) || parts[0];
  8274. const last = parts.pop();
  8275. let propertyPath = root;
  8276. let deepAssignment = [
  8277. ...parts.map(part => {
  8278. propertyPath += getPropertyAccess(part);
  8279. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  8280. }),
  8281. `${propertyPath}${getPropertyAccess(last)}`
  8282. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  8283. if (parts.length > 0) {
  8284. deepAssignment = `(${deepAssignment})`;
  8285. }
  8286. return deepAssignment;
  8287. }
  8288. function trimEmptyImports(dependencies) {
  8289. let index = dependencies.length;
  8290. while (index--) {
  8291. const { imports, reexports } = dependencies[index];
  8292. if (imports || reexports) {
  8293. return dependencies.slice(0, index + 1);
  8294. }
  8295. }
  8296. return [];
  8297. }
  8298. 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 }) {
  8299. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  8300. const isNamespaced = name && name.includes('.');
  8301. const useVariableAssignment = !extend && !isNamespaced;
  8302. if (name && useVariableAssignment && !isLegal(name)) {
  8303. return error(logIllegalIdentifierAsName(name));
  8304. }
  8305. warnOnBuiltins(log, dependencies);
  8306. const external = trimEmptyImports(dependencies);
  8307. const deps = external.map(dep => dep.globalName || 'null');
  8308. const parameters = external.map(m => m.name);
  8309. if (hasExports && !name) {
  8310. log(LOGLEVEL_WARN, logMissingNameOptionForIifeExport());
  8311. }
  8312. if (hasExports && (namedExportsMode || exports[0]?.local === 'exports.default')) {
  8313. if (extend) {
  8314. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  8315. parameters.unshift('exports');
  8316. }
  8317. else {
  8318. deps.unshift('{}');
  8319. parameters.unshift('exports');
  8320. }
  8321. }
  8322. const useStrict = strict ? `${t}'use strict';${n}` : '';
  8323. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  8324. magicString.prepend(`${intro}${interopBlock}`);
  8325. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  8326. isAsync: false,
  8327. name: null
  8328. })}{${n}${useStrict}${n}`;
  8329. if (hasExports) {
  8330. if (name && !(extend && namedExportsMode)) {
  8331. wrapperIntro =
  8332. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  8333. `${_}=${_}${wrapperIntro}`;
  8334. }
  8335. if (isNamespaced) {
  8336. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact, log) + wrapperIntro;
  8337. }
  8338. }
  8339. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  8340. if (hasExports && !extend && namedExportsMode) {
  8341. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  8342. }
  8343. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8344. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  8345. if (namespaceMarkers) {
  8346. namespaceMarkers = n + n + namespaceMarkers;
  8347. }
  8348. magicString
  8349. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8350. .indent(t)
  8351. .prepend(wrapperIntro)
  8352. .append(wrapperOutro);
  8353. }
  8354. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  8355. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, generatedCode: { symbols }, strict, systemNullSetters }) {
  8356. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  8357. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  8358. const registeredName = name ? `'${name}',${_}` : '';
  8359. const wrapperParameters = accessedGlobals.has('module')
  8360. ? ['exports', 'module']
  8361. : hasExports
  8362. ? ['exports']
  8363. : [];
  8364. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8365. // cf. https://v8.dev/blog/preparser#pife
  8366. let wrapperStart = `System.register(${registeredName}[` +
  8367. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  8368. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  8369. isAsync: false,
  8370. name: null
  8371. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  8372. getStarExcludesBlock(starExcludes, t, snippets) +
  8373. getImportBindingsBlock(importBindings, t, snippets) +
  8374. `${n}${t}return${_}{${setters.length > 0
  8375. ? `${n}${t}${t}setters:${_}[${setters
  8376. .map(setter => setter
  8377. ? `${getFunctionIntro(['module'], {
  8378. isAsync: false,
  8379. name: null
  8380. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  8381. : systemNullSetters
  8382. ? `null`
  8383. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  8384. .join(`,${_}`)}],`
  8385. : ''}${n}`;
  8386. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  8387. isAsync: usesTopLevelAwait,
  8388. name: null
  8389. })}{${n}${n}`;
  8390. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  8391. magicString
  8392. .prepend(intro +
  8393. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols) +
  8394. getHoistedExportsBlock(exports, t, snippets))
  8395. .append(`${outro}${n}${n}` +
  8396. getSyntheticExportsBlock(exports, t, snippets) +
  8397. getMissingExportsBlock(exports, t, snippets))
  8398. .indent(`${t}${t}${t}`)
  8399. .append(wrapperEnd)
  8400. .prepend(wrapperStart);
  8401. }
  8402. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  8403. const importBindings = [];
  8404. const setters = [];
  8405. let starExcludes = null;
  8406. for (const { imports, reexports } of dependencies) {
  8407. const setter = [];
  8408. if (imports) {
  8409. for (const specifier of imports) {
  8410. importBindings.push(specifier.local);
  8411. if (specifier.imported === '*') {
  8412. setter.push(`${specifier.local}${_}=${_}module;`);
  8413. }
  8414. else {
  8415. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  8416. }
  8417. }
  8418. }
  8419. if (reexports) {
  8420. const reexportedNames = [];
  8421. let hasStarReexport = false;
  8422. for (const { imported, reexported } of reexports) {
  8423. if (reexported === '*') {
  8424. hasStarReexport = true;
  8425. }
  8426. else {
  8427. reexportedNames.push([
  8428. reexported,
  8429. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  8430. ]);
  8431. }
  8432. }
  8433. if (reexportedNames.length > 1 || hasStarReexport) {
  8434. if (hasStarReexport) {
  8435. if (!starExcludes) {
  8436. starExcludes = getStarExcludes({ dependencies, exports });
  8437. }
  8438. reexportedNames.unshift([null, `__proto__:${_}null`]);
  8439. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  8440. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  8441. }
  8442. else {
  8443. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  8444. setter.push(`exports(${exportMapping});`);
  8445. }
  8446. }
  8447. else {
  8448. const [key, value] = reexportedNames[0];
  8449. setter.push(`exports(${JSON.stringify(key)},${_}${value});`);
  8450. }
  8451. }
  8452. setters.push(setter.join(`${n}${t}${t}${t}`));
  8453. }
  8454. return { importBindings, setters, starExcludes };
  8455. }
  8456. const getStarExcludes = ({ dependencies, exports }) => {
  8457. const starExcludes = new Set(exports.map(expt => expt.exported));
  8458. starExcludes.add('default');
  8459. for (const { reexports } of dependencies) {
  8460. if (reexports) {
  8461. for (const reexport of reexports) {
  8462. if (reexport.reexported !== '*')
  8463. starExcludes.add(reexport.reexported);
  8464. }
  8465. }
  8466. }
  8467. return starExcludes;
  8468. };
  8469. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => {
  8470. if (starExcludes) {
  8471. const fields = [...starExcludes].map(property => [
  8472. property,
  8473. '1'
  8474. ]);
  8475. fields.unshift([null, `__proto__:${_}null`]);
  8476. return `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(fields, {
  8477. lineBreakIndent: { base: t, t }
  8478. })};`;
  8479. }
  8480. return '';
  8481. };
  8482. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  8483. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  8484. function getExportsBlock(exports, t, { _, n }) {
  8485. if (exports.length === 0) {
  8486. return '';
  8487. }
  8488. if (exports.length === 1) {
  8489. return `exports(${JSON.stringify(exports[0].name)},${_}${exports[0].value});${n}${n}`;
  8490. }
  8491. return (`exports({${n}` +
  8492. exports
  8493. .map(({ name, value }) => `${t}${stringifyObjectKeyIfNeeded(name)}:${_}${value}`)
  8494. .join(`,${n}`) +
  8495. `${n}});${n}${n}`);
  8496. }
  8497. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  8498. .filter(expt => expt.expression)
  8499. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  8500. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  8501. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  8502. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  8503. function globalProperty(name, globalVariable, getPropertyAccess) {
  8504. if (!name)
  8505. return 'null';
  8506. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  8507. }
  8508. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  8509. let propertyPath = globalVariable;
  8510. return name
  8511. .split('.')
  8512. .map(part => (propertyPath += getPropertyAccess(part)))
  8513. .join(`${_}&&${_}`);
  8514. }
  8515. 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 }) {
  8516. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  8517. const factoryVariable = compact ? 'f' : 'factory';
  8518. const globalVariable = compact ? 'g' : 'global';
  8519. if (hasExports && !name) {
  8520. return error(logMissingNameOptionForUmdExport());
  8521. }
  8522. warnOnBuiltins(log, dependencies);
  8523. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  8524. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  8525. const trimmedImports = trimEmptyImports(dependencies);
  8526. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  8527. const factoryParameters = trimmedImports.map(m => m.name);
  8528. if ((hasExports || noConflict) &&
  8529. (namedExportsMode || (hasExports && exports[0]?.local === 'exports.default'))) {
  8530. amdDeps.unshift(`'exports'`);
  8531. cjsDeps.unshift(`exports`);
  8532. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets, log));
  8533. factoryParameters.unshift('exports');
  8534. }
  8535. const completeAmdId = getCompleteAmdId(amd, id);
  8536. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  8537. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  8538. const define = amd.define;
  8539. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  8540. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  8541. let iifeExport;
  8542. if (noConflict) {
  8543. const noConflictExportsVariable = compact ? 'e' : 'exports';
  8544. let factory;
  8545. if (!namedExportsMode && hasExports) {
  8546. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets, log)};`;
  8547. }
  8548. else {
  8549. const module = globalDeps.shift();
  8550. factory =
  8551. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  8552. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  8553. }
  8554. iifeExport =
  8555. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  8556. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  8557. `${t}${t}${factory}${n}` +
  8558. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  8559. isAsync: false,
  8560. name: null
  8561. })}{${_}` +
  8562. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  8563. `${t}})()`;
  8564. }
  8565. else {
  8566. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  8567. if (!namedExportsMode && hasExports) {
  8568. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets, log);
  8569. }
  8570. }
  8571. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  8572. const wrapperParameters = [factoryVariable];
  8573. if (iifeNeedsGlobal) {
  8574. wrapperParameters.unshift(globalVariable);
  8575. }
  8576. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  8577. const iifeStart = iifeNeedsGlobal
  8578. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  8579. : '';
  8580. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  8581. const cjsIntro = iifeNeedsGlobal
  8582. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  8583. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  8584. : '';
  8585. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  8586. cjsIntro +
  8587. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  8588. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  8589. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8590. // cf. https://v8.dev/blog/preparser#pife
  8591. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  8592. isAsync: false,
  8593. name: null
  8594. })}{${useStrict}${n}`;
  8595. const wrapperOutro = n + n + '}));';
  8596. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  8597. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8598. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  8599. if (namespaceMarkers) {
  8600. namespaceMarkers = n + n + namespaceMarkers;
  8601. }
  8602. magicString
  8603. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8604. .trim()
  8605. .indent(t)
  8606. .append(wrapperOutro)
  8607. .prepend(wrapperIntro);
  8608. }
  8609. const finalisers = { amd, cjs, es, iife, system, umd };
  8610. function getDefaultExportFromCjs (x) {
  8611. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  8612. }
  8613. function getAugmentedNamespace(n) {
  8614. if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  8615. var f = n.default;
  8616. if (typeof f == "function") {
  8617. var a = function a () {
  8618. if (this instanceof a) {
  8619. return Reflect.construct(f, arguments, this.constructor);
  8620. }
  8621. return f.apply(this, arguments);
  8622. };
  8623. a.prototype = f.prototype;
  8624. } else a = {};
  8625. Object.defineProperty(a, '__esModule', {value: true});
  8626. Object.keys(n).forEach(function (k) {
  8627. var d = Object.getOwnPropertyDescriptor(n, k);
  8628. Object.defineProperty(a, k, d.get ? d : {
  8629. enumerable: true,
  8630. get: function () {
  8631. return n[k];
  8632. }
  8633. });
  8634. });
  8635. return a;
  8636. }
  8637. var utils = {};
  8638. var constants;
  8639. var hasRequiredConstants;
  8640. function requireConstants () {
  8641. if (hasRequiredConstants) return constants;
  8642. hasRequiredConstants = 1;
  8643. const WIN_SLASH = '\\\\/';
  8644. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  8645. /**
  8646. * Posix glob regex
  8647. */
  8648. const DOT_LITERAL = '\\.';
  8649. const PLUS_LITERAL = '\\+';
  8650. const QMARK_LITERAL = '\\?';
  8651. const SLASH_LITERAL = '\\/';
  8652. const ONE_CHAR = '(?=.)';
  8653. const QMARK = '[^/]';
  8654. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  8655. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  8656. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  8657. const NO_DOT = `(?!${DOT_LITERAL})`;
  8658. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  8659. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  8660. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  8661. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  8662. const STAR = `${QMARK}*?`;
  8663. const SEP = '/';
  8664. const POSIX_CHARS = {
  8665. DOT_LITERAL,
  8666. PLUS_LITERAL,
  8667. QMARK_LITERAL,
  8668. SLASH_LITERAL,
  8669. ONE_CHAR,
  8670. QMARK,
  8671. END_ANCHOR,
  8672. DOTS_SLASH,
  8673. NO_DOT,
  8674. NO_DOTS,
  8675. NO_DOT_SLASH,
  8676. NO_DOTS_SLASH,
  8677. QMARK_NO_DOT,
  8678. STAR,
  8679. START_ANCHOR,
  8680. SEP
  8681. };
  8682. /**
  8683. * Windows glob regex
  8684. */
  8685. const WINDOWS_CHARS = {
  8686. ...POSIX_CHARS,
  8687. SLASH_LITERAL: `[${WIN_SLASH}]`,
  8688. QMARK: WIN_NO_SLASH,
  8689. STAR: `${WIN_NO_SLASH}*?`,
  8690. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  8691. NO_DOT: `(?!${DOT_LITERAL})`,
  8692. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  8693. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  8694. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  8695. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  8696. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  8697. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
  8698. SEP: '\\'
  8699. };
  8700. /**
  8701. * POSIX Bracket Regex
  8702. */
  8703. const POSIX_REGEX_SOURCE = {
  8704. alnum: 'a-zA-Z0-9',
  8705. alpha: 'a-zA-Z',
  8706. ascii: '\\x00-\\x7F',
  8707. blank: ' \\t',
  8708. cntrl: '\\x00-\\x1F\\x7F',
  8709. digit: '0-9',
  8710. graph: '\\x21-\\x7E',
  8711. lower: 'a-z',
  8712. print: '\\x20-\\x7E ',
  8713. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  8714. space: ' \\t\\r\\n\\v\\f',
  8715. upper: 'A-Z',
  8716. word: 'A-Za-z0-9_',
  8717. xdigit: 'A-Fa-f0-9'
  8718. };
  8719. constants = {
  8720. MAX_LENGTH: 1024 * 64,
  8721. POSIX_REGEX_SOURCE,
  8722. // regular expressions
  8723. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  8724. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  8725. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  8726. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  8727. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  8728. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  8729. // Replace globs with equivalent patterns to reduce parsing time.
  8730. REPLACEMENTS: {
  8731. '***': '*',
  8732. '**/**': '**',
  8733. '**/**/**': '**'
  8734. },
  8735. // Digits
  8736. CHAR_0: 48, /* 0 */
  8737. CHAR_9: 57, /* 9 */
  8738. // Alphabet chars.
  8739. CHAR_UPPERCASE_A: 65, /* A */
  8740. CHAR_LOWERCASE_A: 97, /* a */
  8741. CHAR_UPPERCASE_Z: 90, /* Z */
  8742. CHAR_LOWERCASE_Z: 122, /* z */
  8743. CHAR_LEFT_PARENTHESES: 40, /* ( */
  8744. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  8745. CHAR_ASTERISK: 42, /* * */
  8746. // Non-alphabetic chars.
  8747. CHAR_AMPERSAND: 38, /* & */
  8748. CHAR_AT: 64, /* @ */
  8749. CHAR_BACKWARD_SLASH: 92, /* \ */
  8750. CHAR_CARRIAGE_RETURN: 13, /* \r */
  8751. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  8752. CHAR_COLON: 58, /* : */
  8753. CHAR_COMMA: 44, /* , */
  8754. CHAR_DOT: 46, /* . */
  8755. CHAR_DOUBLE_QUOTE: 34, /* " */
  8756. CHAR_EQUAL: 61, /* = */
  8757. CHAR_EXCLAMATION_MARK: 33, /* ! */
  8758. CHAR_FORM_FEED: 12, /* \f */
  8759. CHAR_FORWARD_SLASH: 47, /* / */
  8760. CHAR_GRAVE_ACCENT: 96, /* ` */
  8761. CHAR_HASH: 35, /* # */
  8762. CHAR_HYPHEN_MINUS: 45, /* - */
  8763. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  8764. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  8765. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  8766. CHAR_LINE_FEED: 10, /* \n */
  8767. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  8768. CHAR_PERCENT: 37, /* % */
  8769. CHAR_PLUS: 43, /* + */
  8770. CHAR_QUESTION_MARK: 63, /* ? */
  8771. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  8772. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  8773. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  8774. CHAR_SEMICOLON: 59, /* ; */
  8775. CHAR_SINGLE_QUOTE: 39, /* ' */
  8776. CHAR_SPACE: 32, /* */
  8777. CHAR_TAB: 9, /* \t */
  8778. CHAR_UNDERSCORE: 95, /* _ */
  8779. CHAR_VERTICAL_LINE: 124, /* | */
  8780. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  8781. /**
  8782. * Create EXTGLOB_CHARS
  8783. */
  8784. extglobChars(chars) {
  8785. return {
  8786. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  8787. '?': { type: 'qmark', open: '(?:', close: ')?' },
  8788. '+': { type: 'plus', open: '(?:', close: ')+' },
  8789. '*': { type: 'star', open: '(?:', close: ')*' },
  8790. '@': { type: 'at', open: '(?:', close: ')' }
  8791. };
  8792. },
  8793. /**
  8794. * Create GLOB_CHARS
  8795. */
  8796. globChars(win32) {
  8797. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  8798. }
  8799. };
  8800. return constants;
  8801. }
  8802. /*global navigator*/
  8803. var hasRequiredUtils;
  8804. function requireUtils () {
  8805. if (hasRequiredUtils) return utils;
  8806. hasRequiredUtils = 1;
  8807. (function (exports) {
  8808. const {
  8809. REGEX_BACKSLASH,
  8810. REGEX_REMOVE_BACKSLASH,
  8811. REGEX_SPECIAL_CHARS,
  8812. REGEX_SPECIAL_CHARS_GLOBAL
  8813. } = /*@__PURE__*/ requireConstants();
  8814. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  8815. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  8816. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  8817. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  8818. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  8819. exports.isWindows = () => {
  8820. if (typeof navigator !== 'undefined' && navigator.platform) {
  8821. const platform = navigator.platform.toLowerCase();
  8822. return platform === 'win32' || platform === 'windows';
  8823. }
  8824. if (typeof process !== 'undefined' && process.platform) {
  8825. return process.platform === 'win32';
  8826. }
  8827. return false;
  8828. };
  8829. exports.removeBackslashes = str => {
  8830. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  8831. return match === '\\' ? '' : match;
  8832. });
  8833. };
  8834. exports.escapeLast = (input, char, lastIdx) => {
  8835. const idx = input.lastIndexOf(char, lastIdx);
  8836. if (idx === -1) return input;
  8837. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  8838. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  8839. };
  8840. exports.removePrefix = (input, state = {}) => {
  8841. let output = input;
  8842. if (output.startsWith('./')) {
  8843. output = output.slice(2);
  8844. state.prefix = './';
  8845. }
  8846. return output;
  8847. };
  8848. exports.wrapOutput = (input, state = {}, options = {}) => {
  8849. const prepend = options.contains ? '' : '^';
  8850. const append = options.contains ? '' : '$';
  8851. let output = `${prepend}(?:${input})${append}`;
  8852. if (state.negated === true) {
  8853. output = `(?:^(?!${output}).*$)`;
  8854. }
  8855. return output;
  8856. };
  8857. exports.basename = (path, { windows } = {}) => {
  8858. const segs = path.split(windows ? /[\\/]/ : '/');
  8859. const last = segs[segs.length - 1];
  8860. if (last === '') {
  8861. return segs[segs.length - 2];
  8862. }
  8863. return last;
  8864. };
  8865. } (utils));
  8866. return utils;
  8867. }
  8868. var scan_1;
  8869. var hasRequiredScan;
  8870. function requireScan () {
  8871. if (hasRequiredScan) return scan_1;
  8872. hasRequiredScan = 1;
  8873. const utils = /*@__PURE__*/ requireUtils();
  8874. const {
  8875. CHAR_ASTERISK, /* * */
  8876. CHAR_AT, /* @ */
  8877. CHAR_BACKWARD_SLASH, /* \ */
  8878. CHAR_COMMA, /* , */
  8879. CHAR_DOT, /* . */
  8880. CHAR_EXCLAMATION_MARK, /* ! */
  8881. CHAR_FORWARD_SLASH, /* / */
  8882. CHAR_LEFT_CURLY_BRACE, /* { */
  8883. CHAR_LEFT_PARENTHESES, /* ( */
  8884. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  8885. CHAR_PLUS, /* + */
  8886. CHAR_QUESTION_MARK, /* ? */
  8887. CHAR_RIGHT_CURLY_BRACE, /* } */
  8888. CHAR_RIGHT_PARENTHESES, /* ) */
  8889. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  8890. } = /*@__PURE__*/ requireConstants();
  8891. const isPathSeparator = code => {
  8892. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  8893. };
  8894. const depth = token => {
  8895. if (token.isPrefix !== true) {
  8896. token.depth = token.isGlobstar ? Infinity : 1;
  8897. }
  8898. };
  8899. /**
  8900. * Quickly scans a glob pattern and returns an object with a handful of
  8901. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  8902. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  8903. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  8904. *
  8905. * ```js
  8906. * const pm = require('picomatch');
  8907. * console.log(pm.scan('foo/bar/*.js'));
  8908. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  8909. * ```
  8910. * @param {String} `str`
  8911. * @param {Object} `options`
  8912. * @return {Object} Returns an object with tokens and regex source string.
  8913. * @api public
  8914. */
  8915. const scan = (input, options) => {
  8916. const opts = options || {};
  8917. const length = input.length - 1;
  8918. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  8919. const slashes = [];
  8920. const tokens = [];
  8921. const parts = [];
  8922. let str = input;
  8923. let index = -1;
  8924. let start = 0;
  8925. let lastIndex = 0;
  8926. let isBrace = false;
  8927. let isBracket = false;
  8928. let isGlob = false;
  8929. let isExtglob = false;
  8930. let isGlobstar = false;
  8931. let braceEscaped = false;
  8932. let backslashes = false;
  8933. let negated = false;
  8934. let negatedExtglob = false;
  8935. let finished = false;
  8936. let braces = 0;
  8937. let prev;
  8938. let code;
  8939. let token = { value: '', depth: 0, isGlob: false };
  8940. const eos = () => index >= length;
  8941. const peek = () => str.charCodeAt(index + 1);
  8942. const advance = () => {
  8943. prev = code;
  8944. return str.charCodeAt(++index);
  8945. };
  8946. while (index < length) {
  8947. code = advance();
  8948. let next;
  8949. if (code === CHAR_BACKWARD_SLASH) {
  8950. backslashes = token.backslashes = true;
  8951. code = advance();
  8952. if (code === CHAR_LEFT_CURLY_BRACE) {
  8953. braceEscaped = true;
  8954. }
  8955. continue;
  8956. }
  8957. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  8958. braces++;
  8959. while (eos() !== true && (code = advance())) {
  8960. if (code === CHAR_BACKWARD_SLASH) {
  8961. backslashes = token.backslashes = true;
  8962. advance();
  8963. continue;
  8964. }
  8965. if (code === CHAR_LEFT_CURLY_BRACE) {
  8966. braces++;
  8967. continue;
  8968. }
  8969. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  8970. isBrace = token.isBrace = true;
  8971. isGlob = token.isGlob = true;
  8972. finished = true;
  8973. if (scanToEnd === true) {
  8974. continue;
  8975. }
  8976. break;
  8977. }
  8978. if (braceEscaped !== true && code === CHAR_COMMA) {
  8979. isBrace = token.isBrace = true;
  8980. isGlob = token.isGlob = true;
  8981. finished = true;
  8982. if (scanToEnd === true) {
  8983. continue;
  8984. }
  8985. break;
  8986. }
  8987. if (code === CHAR_RIGHT_CURLY_BRACE) {
  8988. braces--;
  8989. if (braces === 0) {
  8990. braceEscaped = false;
  8991. isBrace = token.isBrace = true;
  8992. finished = true;
  8993. break;
  8994. }
  8995. }
  8996. }
  8997. if (scanToEnd === true) {
  8998. continue;
  8999. }
  9000. break;
  9001. }
  9002. if (code === CHAR_FORWARD_SLASH) {
  9003. slashes.push(index);
  9004. tokens.push(token);
  9005. token = { value: '', depth: 0, isGlob: false };
  9006. if (finished === true) continue;
  9007. if (prev === CHAR_DOT && index === (start + 1)) {
  9008. start += 2;
  9009. continue;
  9010. }
  9011. lastIndex = index + 1;
  9012. continue;
  9013. }
  9014. if (opts.noext !== true) {
  9015. const isExtglobChar = code === CHAR_PLUS
  9016. || code === CHAR_AT
  9017. || code === CHAR_ASTERISK
  9018. || code === CHAR_QUESTION_MARK
  9019. || code === CHAR_EXCLAMATION_MARK;
  9020. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  9021. isGlob = token.isGlob = true;
  9022. isExtglob = token.isExtglob = true;
  9023. finished = true;
  9024. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  9025. negatedExtglob = true;
  9026. }
  9027. if (scanToEnd === true) {
  9028. while (eos() !== true && (code = advance())) {
  9029. if (code === CHAR_BACKWARD_SLASH) {
  9030. backslashes = token.backslashes = true;
  9031. code = advance();
  9032. continue;
  9033. }
  9034. if (code === CHAR_RIGHT_PARENTHESES) {
  9035. isGlob = token.isGlob = true;
  9036. finished = true;
  9037. break;
  9038. }
  9039. }
  9040. continue;
  9041. }
  9042. break;
  9043. }
  9044. }
  9045. if (code === CHAR_ASTERISK) {
  9046. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  9047. isGlob = token.isGlob = true;
  9048. finished = true;
  9049. if (scanToEnd === true) {
  9050. continue;
  9051. }
  9052. break;
  9053. }
  9054. if (code === CHAR_QUESTION_MARK) {
  9055. isGlob = token.isGlob = true;
  9056. finished = true;
  9057. if (scanToEnd === true) {
  9058. continue;
  9059. }
  9060. break;
  9061. }
  9062. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  9063. while (eos() !== true && (next = advance())) {
  9064. if (next === CHAR_BACKWARD_SLASH) {
  9065. backslashes = token.backslashes = true;
  9066. advance();
  9067. continue;
  9068. }
  9069. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  9070. isBracket = token.isBracket = true;
  9071. isGlob = token.isGlob = true;
  9072. finished = true;
  9073. break;
  9074. }
  9075. }
  9076. if (scanToEnd === true) {
  9077. continue;
  9078. }
  9079. break;
  9080. }
  9081. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  9082. negated = token.negated = true;
  9083. start++;
  9084. continue;
  9085. }
  9086. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  9087. isGlob = token.isGlob = true;
  9088. if (scanToEnd === true) {
  9089. while (eos() !== true && (code = advance())) {
  9090. if (code === CHAR_LEFT_PARENTHESES) {
  9091. backslashes = token.backslashes = true;
  9092. code = advance();
  9093. continue;
  9094. }
  9095. if (code === CHAR_RIGHT_PARENTHESES) {
  9096. finished = true;
  9097. break;
  9098. }
  9099. }
  9100. continue;
  9101. }
  9102. break;
  9103. }
  9104. if (isGlob === true) {
  9105. finished = true;
  9106. if (scanToEnd === true) {
  9107. continue;
  9108. }
  9109. break;
  9110. }
  9111. }
  9112. if (opts.noext === true) {
  9113. isExtglob = false;
  9114. isGlob = false;
  9115. }
  9116. let base = str;
  9117. let prefix = '';
  9118. let glob = '';
  9119. if (start > 0) {
  9120. prefix = str.slice(0, start);
  9121. str = str.slice(start);
  9122. lastIndex -= start;
  9123. }
  9124. if (base && isGlob === true && lastIndex > 0) {
  9125. base = str.slice(0, lastIndex);
  9126. glob = str.slice(lastIndex);
  9127. } else if (isGlob === true) {
  9128. base = '';
  9129. glob = str;
  9130. } else {
  9131. base = str;
  9132. }
  9133. if (base && base !== '' && base !== '/' && base !== str) {
  9134. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  9135. base = base.slice(0, -1);
  9136. }
  9137. }
  9138. if (opts.unescape === true) {
  9139. if (glob) glob = utils.removeBackslashes(glob);
  9140. if (base && backslashes === true) {
  9141. base = utils.removeBackslashes(base);
  9142. }
  9143. }
  9144. const state = {
  9145. prefix,
  9146. input,
  9147. start,
  9148. base,
  9149. glob,
  9150. isBrace,
  9151. isBracket,
  9152. isGlob,
  9153. isExtglob,
  9154. isGlobstar,
  9155. negated,
  9156. negatedExtglob
  9157. };
  9158. if (opts.tokens === true) {
  9159. state.maxDepth = 0;
  9160. if (!isPathSeparator(code)) {
  9161. tokens.push(token);
  9162. }
  9163. state.tokens = tokens;
  9164. }
  9165. if (opts.parts === true || opts.tokens === true) {
  9166. let prevIndex;
  9167. for (let idx = 0; idx < slashes.length; idx++) {
  9168. const n = prevIndex ? prevIndex + 1 : start;
  9169. const i = slashes[idx];
  9170. const value = input.slice(n, i);
  9171. if (opts.tokens) {
  9172. if (idx === 0 && start !== 0) {
  9173. tokens[idx].isPrefix = true;
  9174. tokens[idx].value = prefix;
  9175. } else {
  9176. tokens[idx].value = value;
  9177. }
  9178. depth(tokens[idx]);
  9179. state.maxDepth += tokens[idx].depth;
  9180. }
  9181. if (idx !== 0 || value !== '') {
  9182. parts.push(value);
  9183. }
  9184. prevIndex = i;
  9185. }
  9186. if (prevIndex && prevIndex + 1 < input.length) {
  9187. const value = input.slice(prevIndex + 1);
  9188. parts.push(value);
  9189. if (opts.tokens) {
  9190. tokens[tokens.length - 1].value = value;
  9191. depth(tokens[tokens.length - 1]);
  9192. state.maxDepth += tokens[tokens.length - 1].depth;
  9193. }
  9194. }
  9195. state.slashes = slashes;
  9196. state.parts = parts;
  9197. }
  9198. return state;
  9199. };
  9200. scan_1 = scan;
  9201. return scan_1;
  9202. }
  9203. var parse_1;
  9204. var hasRequiredParse;
  9205. function requireParse () {
  9206. if (hasRequiredParse) return parse_1;
  9207. hasRequiredParse = 1;
  9208. const constants = /*@__PURE__*/ requireConstants();
  9209. const utils = /*@__PURE__*/ requireUtils();
  9210. /**
  9211. * Constants
  9212. */
  9213. const {
  9214. MAX_LENGTH,
  9215. POSIX_REGEX_SOURCE,
  9216. REGEX_NON_SPECIAL_CHARS,
  9217. REGEX_SPECIAL_CHARS_BACKREF,
  9218. REPLACEMENTS
  9219. } = constants;
  9220. /**
  9221. * Helpers
  9222. */
  9223. const expandRange = (args, options) => {
  9224. if (typeof options.expandRange === 'function') {
  9225. return options.expandRange(...args, options);
  9226. }
  9227. args.sort();
  9228. const value = `[${args.join('-')}]`;
  9229. return value;
  9230. };
  9231. /**
  9232. * Create the message for a syntax error
  9233. */
  9234. const syntaxError = (type, char) => {
  9235. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  9236. };
  9237. /**
  9238. * Parse the given input string.
  9239. * @param {String} input
  9240. * @param {Object} options
  9241. * @return {Object}
  9242. */
  9243. const parse = (input, options) => {
  9244. if (typeof input !== 'string') {
  9245. throw new TypeError('Expected a string');
  9246. }
  9247. input = REPLACEMENTS[input] || input;
  9248. const opts = { ...options };
  9249. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  9250. let len = input.length;
  9251. if (len > max) {
  9252. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  9253. }
  9254. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  9255. const tokens = [bos];
  9256. const capture = opts.capture ? '' : '?:';
  9257. // create constants based on platform, for windows or posix
  9258. const PLATFORM_CHARS = constants.globChars(opts.windows);
  9259. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  9260. const {
  9261. DOT_LITERAL,
  9262. PLUS_LITERAL,
  9263. SLASH_LITERAL,
  9264. ONE_CHAR,
  9265. DOTS_SLASH,
  9266. NO_DOT,
  9267. NO_DOT_SLASH,
  9268. NO_DOTS_SLASH,
  9269. QMARK,
  9270. QMARK_NO_DOT,
  9271. STAR,
  9272. START_ANCHOR
  9273. } = PLATFORM_CHARS;
  9274. const globstar = opts => {
  9275. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  9276. };
  9277. const nodot = opts.dot ? '' : NO_DOT;
  9278. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  9279. let star = opts.bash === true ? globstar(opts) : STAR;
  9280. if (opts.capture) {
  9281. star = `(${star})`;
  9282. }
  9283. // minimatch options support
  9284. if (typeof opts.noext === 'boolean') {
  9285. opts.noextglob = opts.noext;
  9286. }
  9287. const state = {
  9288. input,
  9289. index: -1,
  9290. start: 0,
  9291. dot: opts.dot === true,
  9292. consumed: '',
  9293. output: '',
  9294. prefix: '',
  9295. backtrack: false,
  9296. negated: false,
  9297. brackets: 0,
  9298. braces: 0,
  9299. parens: 0,
  9300. quotes: 0,
  9301. globstar: false,
  9302. tokens
  9303. };
  9304. input = utils.removePrefix(input, state);
  9305. len = input.length;
  9306. const extglobs = [];
  9307. const braces = [];
  9308. const stack = [];
  9309. let prev = bos;
  9310. let value;
  9311. /**
  9312. * Tokenizing helpers
  9313. */
  9314. const eos = () => state.index === len - 1;
  9315. const peek = state.peek = (n = 1) => input[state.index + n];
  9316. const advance = state.advance = () => input[++state.index] || '';
  9317. const remaining = () => input.slice(state.index + 1);
  9318. const consume = (value = '', num = 0) => {
  9319. state.consumed += value;
  9320. state.index += num;
  9321. };
  9322. const append = token => {
  9323. state.output += token.output != null ? token.output : token.value;
  9324. consume(token.value);
  9325. };
  9326. const negate = () => {
  9327. let count = 1;
  9328. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  9329. advance();
  9330. state.start++;
  9331. count++;
  9332. }
  9333. if (count % 2 === 0) {
  9334. return false;
  9335. }
  9336. state.negated = true;
  9337. state.start++;
  9338. return true;
  9339. };
  9340. const increment = type => {
  9341. state[type]++;
  9342. stack.push(type);
  9343. };
  9344. const decrement = type => {
  9345. state[type]--;
  9346. stack.pop();
  9347. };
  9348. /**
  9349. * Push tokens onto the tokens array. This helper speeds up
  9350. * tokenizing by 1) helping us avoid backtracking as much as possible,
  9351. * and 2) helping us avoid creating extra tokens when consecutive
  9352. * characters are plain text. This improves performance and simplifies
  9353. * lookbehinds.
  9354. */
  9355. const push = tok => {
  9356. if (prev.type === 'globstar') {
  9357. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  9358. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  9359. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  9360. state.output = state.output.slice(0, -prev.output.length);
  9361. prev.type = 'star';
  9362. prev.value = '*';
  9363. prev.output = star;
  9364. state.output += prev.output;
  9365. }
  9366. }
  9367. if (extglobs.length && tok.type !== 'paren') {
  9368. extglobs[extglobs.length - 1].inner += tok.value;
  9369. }
  9370. if (tok.value || tok.output) append(tok);
  9371. if (prev && prev.type === 'text' && tok.type === 'text') {
  9372. prev.output = (prev.output || prev.value) + tok.value;
  9373. prev.value += tok.value;
  9374. return;
  9375. }
  9376. tok.prev = prev;
  9377. tokens.push(tok);
  9378. prev = tok;
  9379. };
  9380. const extglobOpen = (type, value) => {
  9381. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  9382. token.prev = prev;
  9383. token.parens = state.parens;
  9384. token.output = state.output;
  9385. const output = (opts.capture ? '(' : '') + token.open;
  9386. increment('parens');
  9387. push({ type, value, output: state.output ? '' : ONE_CHAR });
  9388. push({ type: 'paren', extglob: true, value: advance(), output });
  9389. extglobs.push(token);
  9390. };
  9391. const extglobClose = token => {
  9392. let output = token.close + (opts.capture ? ')' : '');
  9393. let rest;
  9394. if (token.type === 'negate') {
  9395. let extglobStar = star;
  9396. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  9397. extglobStar = globstar(opts);
  9398. }
  9399. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  9400. output = token.close = `)$))${extglobStar}`;
  9401. }
  9402. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  9403. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  9404. // In this case, we need to parse the string and use it in the output of the original pattern.
  9405. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  9406. //
  9407. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  9408. const expression = parse(rest, { ...options, fastpaths: false }).output;
  9409. output = token.close = `)${expression})${extglobStar})`;
  9410. }
  9411. if (token.prev.type === 'bos') {
  9412. state.negatedExtglob = true;
  9413. }
  9414. }
  9415. push({ type: 'paren', extglob: true, value, output });
  9416. decrement('parens');
  9417. };
  9418. /**
  9419. * Fast paths
  9420. */
  9421. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  9422. let backslashes = false;
  9423. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  9424. if (first === '\\') {
  9425. backslashes = true;
  9426. return m;
  9427. }
  9428. if (first === '?') {
  9429. if (esc) {
  9430. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  9431. }
  9432. if (index === 0) {
  9433. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  9434. }
  9435. return QMARK.repeat(chars.length);
  9436. }
  9437. if (first === '.') {
  9438. return DOT_LITERAL.repeat(chars.length);
  9439. }
  9440. if (first === '*') {
  9441. if (esc) {
  9442. return esc + first + (rest ? star : '');
  9443. }
  9444. return star;
  9445. }
  9446. return esc ? m : `\\${m}`;
  9447. });
  9448. if (backslashes === true) {
  9449. if (opts.unescape === true) {
  9450. output = output.replace(/\\/g, '');
  9451. } else {
  9452. output = output.replace(/\\+/g, m => {
  9453. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  9454. });
  9455. }
  9456. }
  9457. if (output === input && opts.contains === true) {
  9458. state.output = input;
  9459. return state;
  9460. }
  9461. state.output = utils.wrapOutput(output, state, options);
  9462. return state;
  9463. }
  9464. /**
  9465. * Tokenize input until we reach end-of-string
  9466. */
  9467. while (!eos()) {
  9468. value = advance();
  9469. if (value === '\u0000') {
  9470. continue;
  9471. }
  9472. /**
  9473. * Escaped characters
  9474. */
  9475. if (value === '\\') {
  9476. const next = peek();
  9477. if (next === '/' && opts.bash !== true) {
  9478. continue;
  9479. }
  9480. if (next === '.' || next === ';') {
  9481. continue;
  9482. }
  9483. if (!next) {
  9484. value += '\\';
  9485. push({ type: 'text', value });
  9486. continue;
  9487. }
  9488. // collapse slashes to reduce potential for exploits
  9489. const match = /^\\+/.exec(remaining());
  9490. let slashes = 0;
  9491. if (match && match[0].length > 2) {
  9492. slashes = match[0].length;
  9493. state.index += slashes;
  9494. if (slashes % 2 !== 0) {
  9495. value += '\\';
  9496. }
  9497. }
  9498. if (opts.unescape === true) {
  9499. value = advance();
  9500. } else {
  9501. value += advance();
  9502. }
  9503. if (state.brackets === 0) {
  9504. push({ type: 'text', value });
  9505. continue;
  9506. }
  9507. }
  9508. /**
  9509. * If we're inside a regex character class, continue
  9510. * until we reach the closing bracket.
  9511. */
  9512. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  9513. if (opts.posix !== false && value === ':') {
  9514. const inner = prev.value.slice(1);
  9515. if (inner.includes('[')) {
  9516. prev.posix = true;
  9517. if (inner.includes(':')) {
  9518. const idx = prev.value.lastIndexOf('[');
  9519. const pre = prev.value.slice(0, idx);
  9520. const rest = prev.value.slice(idx + 2);
  9521. const posix = POSIX_REGEX_SOURCE[rest];
  9522. if (posix) {
  9523. prev.value = pre + posix;
  9524. state.backtrack = true;
  9525. advance();
  9526. if (!bos.output && tokens.indexOf(prev) === 1) {
  9527. bos.output = ONE_CHAR;
  9528. }
  9529. continue;
  9530. }
  9531. }
  9532. }
  9533. }
  9534. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  9535. value = `\\${value}`;
  9536. }
  9537. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  9538. value = `\\${value}`;
  9539. }
  9540. if (opts.posix === true && value === '!' && prev.value === '[') {
  9541. value = '^';
  9542. }
  9543. prev.value += value;
  9544. append({ value });
  9545. continue;
  9546. }
  9547. /**
  9548. * If we're inside a quoted string, continue
  9549. * until we reach the closing double quote.
  9550. */
  9551. if (state.quotes === 1 && value !== '"') {
  9552. value = utils.escapeRegex(value);
  9553. prev.value += value;
  9554. append({ value });
  9555. continue;
  9556. }
  9557. /**
  9558. * Double quotes
  9559. */
  9560. if (value === '"') {
  9561. state.quotes = state.quotes === 1 ? 0 : 1;
  9562. if (opts.keepQuotes === true) {
  9563. push({ type: 'text', value });
  9564. }
  9565. continue;
  9566. }
  9567. /**
  9568. * Parentheses
  9569. */
  9570. if (value === '(') {
  9571. increment('parens');
  9572. push({ type: 'paren', value });
  9573. continue;
  9574. }
  9575. if (value === ')') {
  9576. if (state.parens === 0 && opts.strictBrackets === true) {
  9577. throw new SyntaxError(syntaxError('opening', '('));
  9578. }
  9579. const extglob = extglobs[extglobs.length - 1];
  9580. if (extglob && state.parens === extglob.parens + 1) {
  9581. extglobClose(extglobs.pop());
  9582. continue;
  9583. }
  9584. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  9585. decrement('parens');
  9586. continue;
  9587. }
  9588. /**
  9589. * Square brackets
  9590. */
  9591. if (value === '[') {
  9592. if (opts.nobracket === true || !remaining().includes(']')) {
  9593. if (opts.nobracket !== true && opts.strictBrackets === true) {
  9594. throw new SyntaxError(syntaxError('closing', ']'));
  9595. }
  9596. value = `\\${value}`;
  9597. } else {
  9598. increment('brackets');
  9599. }
  9600. push({ type: 'bracket', value });
  9601. continue;
  9602. }
  9603. if (value === ']') {
  9604. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  9605. push({ type: 'text', value, output: `\\${value}` });
  9606. continue;
  9607. }
  9608. if (state.brackets === 0) {
  9609. if (opts.strictBrackets === true) {
  9610. throw new SyntaxError(syntaxError('opening', '['));
  9611. }
  9612. push({ type: 'text', value, output: `\\${value}` });
  9613. continue;
  9614. }
  9615. decrement('brackets');
  9616. const prevValue = prev.value.slice(1);
  9617. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  9618. value = `/${value}`;
  9619. }
  9620. prev.value += value;
  9621. append({ value });
  9622. // when literal brackets are explicitly disabled
  9623. // assume we should match with a regex character class
  9624. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  9625. continue;
  9626. }
  9627. const escaped = utils.escapeRegex(prev.value);
  9628. state.output = state.output.slice(0, -prev.value.length);
  9629. // when literal brackets are explicitly enabled
  9630. // assume we should escape the brackets to match literal characters
  9631. if (opts.literalBrackets === true) {
  9632. state.output += escaped;
  9633. prev.value = escaped;
  9634. continue;
  9635. }
  9636. // when the user specifies nothing, try to match both
  9637. prev.value = `(${capture}${escaped}|${prev.value})`;
  9638. state.output += prev.value;
  9639. continue;
  9640. }
  9641. /**
  9642. * Braces
  9643. */
  9644. if (value === '{' && opts.nobrace !== true) {
  9645. increment('braces');
  9646. const open = {
  9647. type: 'brace',
  9648. value,
  9649. output: '(',
  9650. outputIndex: state.output.length,
  9651. tokensIndex: state.tokens.length
  9652. };
  9653. braces.push(open);
  9654. push(open);
  9655. continue;
  9656. }
  9657. if (value === '}') {
  9658. const brace = braces[braces.length - 1];
  9659. if (opts.nobrace === true || !brace) {
  9660. push({ type: 'text', value, output: value });
  9661. continue;
  9662. }
  9663. let output = ')';
  9664. if (brace.dots === true) {
  9665. const arr = tokens.slice();
  9666. const range = [];
  9667. for (let i = arr.length - 1; i >= 0; i--) {
  9668. tokens.pop();
  9669. if (arr[i].type === 'brace') {
  9670. break;
  9671. }
  9672. if (arr[i].type !== 'dots') {
  9673. range.unshift(arr[i].value);
  9674. }
  9675. }
  9676. output = expandRange(range, opts);
  9677. state.backtrack = true;
  9678. }
  9679. if (brace.comma !== true && brace.dots !== true) {
  9680. const out = state.output.slice(0, brace.outputIndex);
  9681. const toks = state.tokens.slice(brace.tokensIndex);
  9682. brace.value = brace.output = '\\{';
  9683. value = output = '\\}';
  9684. state.output = out;
  9685. for (const t of toks) {
  9686. state.output += (t.output || t.value);
  9687. }
  9688. }
  9689. push({ type: 'brace', value, output });
  9690. decrement('braces');
  9691. braces.pop();
  9692. continue;
  9693. }
  9694. /**
  9695. * Pipes
  9696. */
  9697. if (value === '|') {
  9698. if (extglobs.length > 0) {
  9699. extglobs[extglobs.length - 1].conditions++;
  9700. }
  9701. push({ type: 'text', value });
  9702. continue;
  9703. }
  9704. /**
  9705. * Commas
  9706. */
  9707. if (value === ',') {
  9708. let output = value;
  9709. const brace = braces[braces.length - 1];
  9710. if (brace && stack[stack.length - 1] === 'braces') {
  9711. brace.comma = true;
  9712. output = '|';
  9713. }
  9714. push({ type: 'comma', value, output });
  9715. continue;
  9716. }
  9717. /**
  9718. * Slashes
  9719. */
  9720. if (value === '/') {
  9721. // if the beginning of the glob is "./", advance the start
  9722. // to the current index, and don't add the "./" characters
  9723. // to the state. This greatly simplifies lookbehinds when
  9724. // checking for BOS characters like "!" and "." (not "./")
  9725. if (prev.type === 'dot' && state.index === state.start + 1) {
  9726. state.start = state.index + 1;
  9727. state.consumed = '';
  9728. state.output = '';
  9729. tokens.pop();
  9730. prev = bos; // reset "prev" to the first token
  9731. continue;
  9732. }
  9733. push({ type: 'slash', value, output: SLASH_LITERAL });
  9734. continue;
  9735. }
  9736. /**
  9737. * Dots
  9738. */
  9739. if (value === '.') {
  9740. if (state.braces > 0 && prev.type === 'dot') {
  9741. if (prev.value === '.') prev.output = DOT_LITERAL;
  9742. const brace = braces[braces.length - 1];
  9743. prev.type = 'dots';
  9744. prev.output += value;
  9745. prev.value += value;
  9746. brace.dots = true;
  9747. continue;
  9748. }
  9749. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  9750. push({ type: 'text', value, output: DOT_LITERAL });
  9751. continue;
  9752. }
  9753. push({ type: 'dot', value, output: DOT_LITERAL });
  9754. continue;
  9755. }
  9756. /**
  9757. * Question marks
  9758. */
  9759. if (value === '?') {
  9760. const isGroup = prev && prev.value === '(';
  9761. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9762. extglobOpen('qmark', value);
  9763. continue;
  9764. }
  9765. if (prev && prev.type === 'paren') {
  9766. const next = peek();
  9767. let output = value;
  9768. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  9769. output = `\\${value}`;
  9770. }
  9771. push({ type: 'text', value, output });
  9772. continue;
  9773. }
  9774. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  9775. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  9776. continue;
  9777. }
  9778. push({ type: 'qmark', value, output: QMARK });
  9779. continue;
  9780. }
  9781. /**
  9782. * Exclamation
  9783. */
  9784. if (value === '!') {
  9785. if (opts.noextglob !== true && peek() === '(') {
  9786. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  9787. extglobOpen('negate', value);
  9788. continue;
  9789. }
  9790. }
  9791. if (opts.nonegate !== true && state.index === 0) {
  9792. negate();
  9793. continue;
  9794. }
  9795. }
  9796. /**
  9797. * Plus
  9798. */
  9799. if (value === '+') {
  9800. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9801. extglobOpen('plus', value);
  9802. continue;
  9803. }
  9804. if ((prev && prev.value === '(') || opts.regex === false) {
  9805. push({ type: 'plus', value, output: PLUS_LITERAL });
  9806. continue;
  9807. }
  9808. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  9809. push({ type: 'plus', value });
  9810. continue;
  9811. }
  9812. push({ type: 'plus', value: PLUS_LITERAL });
  9813. continue;
  9814. }
  9815. /**
  9816. * Plain text
  9817. */
  9818. if (value === '@') {
  9819. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9820. push({ type: 'at', extglob: true, value, output: '' });
  9821. continue;
  9822. }
  9823. push({ type: 'text', value });
  9824. continue;
  9825. }
  9826. /**
  9827. * Plain text
  9828. */
  9829. if (value !== '*') {
  9830. if (value === '$' || value === '^') {
  9831. value = `\\${value}`;
  9832. }
  9833. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  9834. if (match) {
  9835. value += match[0];
  9836. state.index += match[0].length;
  9837. }
  9838. push({ type: 'text', value });
  9839. continue;
  9840. }
  9841. /**
  9842. * Stars
  9843. */
  9844. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  9845. prev.type = 'star';
  9846. prev.star = true;
  9847. prev.value += value;
  9848. prev.output = star;
  9849. state.backtrack = true;
  9850. state.globstar = true;
  9851. consume(value);
  9852. continue;
  9853. }
  9854. let rest = remaining();
  9855. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  9856. extglobOpen('star', value);
  9857. continue;
  9858. }
  9859. if (prev.type === 'star') {
  9860. if (opts.noglobstar === true) {
  9861. consume(value);
  9862. continue;
  9863. }
  9864. const prior = prev.prev;
  9865. const before = prior.prev;
  9866. const isStart = prior.type === 'slash' || prior.type === 'bos';
  9867. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  9868. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  9869. push({ type: 'star', value, output: '' });
  9870. continue;
  9871. }
  9872. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  9873. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  9874. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  9875. push({ type: 'star', value, output: '' });
  9876. continue;
  9877. }
  9878. // strip consecutive `/**/`
  9879. while (rest.slice(0, 3) === '/**') {
  9880. const after = input[state.index + 4];
  9881. if (after && after !== '/') {
  9882. break;
  9883. }
  9884. rest = rest.slice(3);
  9885. consume('/**', 3);
  9886. }
  9887. if (prior.type === 'bos' && eos()) {
  9888. prev.type = 'globstar';
  9889. prev.value += value;
  9890. prev.output = globstar(opts);
  9891. state.output = prev.output;
  9892. state.globstar = true;
  9893. consume(value);
  9894. continue;
  9895. }
  9896. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  9897. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  9898. prior.output = `(?:${prior.output}`;
  9899. prev.type = 'globstar';
  9900. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  9901. prev.value += value;
  9902. state.globstar = true;
  9903. state.output += prior.output + prev.output;
  9904. consume(value);
  9905. continue;
  9906. }
  9907. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  9908. const end = rest[1] !== void 0 ? '|$' : '';
  9909. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  9910. prior.output = `(?:${prior.output}`;
  9911. prev.type = 'globstar';
  9912. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  9913. prev.value += value;
  9914. state.output += prior.output + prev.output;
  9915. state.globstar = true;
  9916. consume(value + advance());
  9917. push({ type: 'slash', value: '/', output: '' });
  9918. continue;
  9919. }
  9920. if (prior.type === 'bos' && rest[0] === '/') {
  9921. prev.type = 'globstar';
  9922. prev.value += value;
  9923. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  9924. state.output = prev.output;
  9925. state.globstar = true;
  9926. consume(value + advance());
  9927. push({ type: 'slash', value: '/', output: '' });
  9928. continue;
  9929. }
  9930. // remove single star from output
  9931. state.output = state.output.slice(0, -prev.output.length);
  9932. // reset previous token to globstar
  9933. prev.type = 'globstar';
  9934. prev.output = globstar(opts);
  9935. prev.value += value;
  9936. // reset output with globstar
  9937. state.output += prev.output;
  9938. state.globstar = true;
  9939. consume(value);
  9940. continue;
  9941. }
  9942. const token = { type: 'star', value, output: star };
  9943. if (opts.bash === true) {
  9944. token.output = '.*?';
  9945. if (prev.type === 'bos' || prev.type === 'slash') {
  9946. token.output = nodot + token.output;
  9947. }
  9948. push(token);
  9949. continue;
  9950. }
  9951. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  9952. token.output = value;
  9953. push(token);
  9954. continue;
  9955. }
  9956. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  9957. if (prev.type === 'dot') {
  9958. state.output += NO_DOT_SLASH;
  9959. prev.output += NO_DOT_SLASH;
  9960. } else if (opts.dot === true) {
  9961. state.output += NO_DOTS_SLASH;
  9962. prev.output += NO_DOTS_SLASH;
  9963. } else {
  9964. state.output += nodot;
  9965. prev.output += nodot;
  9966. }
  9967. if (peek() !== '*') {
  9968. state.output += ONE_CHAR;
  9969. prev.output += ONE_CHAR;
  9970. }
  9971. }
  9972. push(token);
  9973. }
  9974. while (state.brackets > 0) {
  9975. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  9976. state.output = utils.escapeLast(state.output, '[');
  9977. decrement('brackets');
  9978. }
  9979. while (state.parens > 0) {
  9980. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  9981. state.output = utils.escapeLast(state.output, '(');
  9982. decrement('parens');
  9983. }
  9984. while (state.braces > 0) {
  9985. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  9986. state.output = utils.escapeLast(state.output, '{');
  9987. decrement('braces');
  9988. }
  9989. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  9990. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  9991. }
  9992. // rebuild the output if we had to backtrack at any point
  9993. if (state.backtrack === true) {
  9994. state.output = '';
  9995. for (const token of state.tokens) {
  9996. state.output += token.output != null ? token.output : token.value;
  9997. if (token.suffix) {
  9998. state.output += token.suffix;
  9999. }
  10000. }
  10001. }
  10002. return state;
  10003. };
  10004. /**
  10005. * Fast paths for creating regular expressions for common glob patterns.
  10006. * This can significantly speed up processing and has very little downside
  10007. * impact when none of the fast paths match.
  10008. */
  10009. parse.fastpaths = (input, options) => {
  10010. const opts = { ...options };
  10011. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  10012. const len = input.length;
  10013. if (len > max) {
  10014. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  10015. }
  10016. input = REPLACEMENTS[input] || input;
  10017. // create constants based on platform, for windows or posix
  10018. const {
  10019. DOT_LITERAL,
  10020. SLASH_LITERAL,
  10021. ONE_CHAR,
  10022. DOTS_SLASH,
  10023. NO_DOT,
  10024. NO_DOTS,
  10025. NO_DOTS_SLASH,
  10026. STAR,
  10027. START_ANCHOR
  10028. } = constants.globChars(opts.windows);
  10029. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  10030. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  10031. const capture = opts.capture ? '' : '?:';
  10032. const state = { negated: false, prefix: '' };
  10033. let star = opts.bash === true ? '.*?' : STAR;
  10034. if (opts.capture) {
  10035. star = `(${star})`;
  10036. }
  10037. const globstar = opts => {
  10038. if (opts.noglobstar === true) return star;
  10039. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  10040. };
  10041. const create = str => {
  10042. switch (str) {
  10043. case '*':
  10044. return `${nodot}${ONE_CHAR}${star}`;
  10045. case '.*':
  10046. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  10047. case '*.*':
  10048. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  10049. case '*/*':
  10050. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  10051. case '**':
  10052. return nodot + globstar(opts);
  10053. case '**/*':
  10054. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  10055. case '**/*.*':
  10056. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  10057. case '**/.*':
  10058. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  10059. default: {
  10060. const match = /^(.*?)\.(\w+)$/.exec(str);
  10061. if (!match) return;
  10062. const source = create(match[1]);
  10063. if (!source) return;
  10064. return source + DOT_LITERAL + match[2];
  10065. }
  10066. }
  10067. };
  10068. const output = utils.removePrefix(input, state);
  10069. let source = create(output);
  10070. if (source && opts.strictSlashes !== true) {
  10071. source += `${SLASH_LITERAL}?`;
  10072. }
  10073. return source;
  10074. };
  10075. parse_1 = parse;
  10076. return parse_1;
  10077. }
  10078. var picomatch_1$1;
  10079. var hasRequiredPicomatch$1;
  10080. function requirePicomatch$1 () {
  10081. if (hasRequiredPicomatch$1) return picomatch_1$1;
  10082. hasRequiredPicomatch$1 = 1;
  10083. const scan = /*@__PURE__*/ requireScan();
  10084. const parse = /*@__PURE__*/ requireParse();
  10085. const utils = /*@__PURE__*/ requireUtils();
  10086. const constants = /*@__PURE__*/ requireConstants();
  10087. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  10088. /**
  10089. * Creates a matcher function from one or more glob patterns. The
  10090. * returned function takes a string to match as its first argument,
  10091. * and returns true if the string is a match. The returned matcher
  10092. * function also takes a boolean as the second argument that, when true,
  10093. * returns an object with additional information.
  10094. *
  10095. * ```js
  10096. * const picomatch = require('picomatch');
  10097. * // picomatch(glob[, options]);
  10098. *
  10099. * const isMatch = picomatch('*.!(*a)');
  10100. * console.log(isMatch('a.a')); //=> false
  10101. * console.log(isMatch('a.b')); //=> true
  10102. * ```
  10103. * @name picomatch
  10104. * @param {String|Array} `globs` One or more glob patterns.
  10105. * @param {Object=} `options`
  10106. * @return {Function=} Returns a matcher function.
  10107. * @api public
  10108. */
  10109. const picomatch = (glob, options, returnState = false) => {
  10110. if (Array.isArray(glob)) {
  10111. const fns = glob.map(input => picomatch(input, options, returnState));
  10112. const arrayMatcher = str => {
  10113. for (const isMatch of fns) {
  10114. const state = isMatch(str);
  10115. if (state) return state;
  10116. }
  10117. return false;
  10118. };
  10119. return arrayMatcher;
  10120. }
  10121. const isState = isObject(glob) && glob.tokens && glob.input;
  10122. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  10123. throw new TypeError('Expected pattern to be a non-empty string');
  10124. }
  10125. const opts = options || {};
  10126. const posix = opts.windows;
  10127. const regex = isState
  10128. ? picomatch.compileRe(glob, options)
  10129. : picomatch.makeRe(glob, options, false, true);
  10130. const state = regex.state;
  10131. delete regex.state;
  10132. let isIgnored = () => false;
  10133. if (opts.ignore) {
  10134. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  10135. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  10136. }
  10137. const matcher = (input, returnObject = false) => {
  10138. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  10139. const result = { glob, state, regex, posix, input, output, match, isMatch };
  10140. if (typeof opts.onResult === 'function') {
  10141. opts.onResult(result);
  10142. }
  10143. if (isMatch === false) {
  10144. result.isMatch = false;
  10145. return returnObject ? result : false;
  10146. }
  10147. if (isIgnored(input)) {
  10148. if (typeof opts.onIgnore === 'function') {
  10149. opts.onIgnore(result);
  10150. }
  10151. result.isMatch = false;
  10152. return returnObject ? result : false;
  10153. }
  10154. if (typeof opts.onMatch === 'function') {
  10155. opts.onMatch(result);
  10156. }
  10157. return returnObject ? result : true;
  10158. };
  10159. if (returnState) {
  10160. matcher.state = state;
  10161. }
  10162. return matcher;
  10163. };
  10164. /**
  10165. * Test `input` with the given `regex`. This is used by the main
  10166. * `picomatch()` function to test the input string.
  10167. *
  10168. * ```js
  10169. * const picomatch = require('picomatch');
  10170. * // picomatch.test(input, regex[, options]);
  10171. *
  10172. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  10173. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  10174. * ```
  10175. * @param {String} `input` String to test.
  10176. * @param {RegExp} `regex`
  10177. * @return {Object} Returns an object with matching info.
  10178. * @api public
  10179. */
  10180. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  10181. if (typeof input !== 'string') {
  10182. throw new TypeError('Expected input to be a string');
  10183. }
  10184. if (input === '') {
  10185. return { isMatch: false, output: '' };
  10186. }
  10187. const opts = options || {};
  10188. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  10189. let match = input === glob;
  10190. let output = (match && format) ? format(input) : input;
  10191. if (match === false) {
  10192. output = format ? format(input) : input;
  10193. match = output === glob;
  10194. }
  10195. if (match === false || opts.capture === true) {
  10196. if (opts.matchBase === true || opts.basename === true) {
  10197. match = picomatch.matchBase(input, regex, options, posix);
  10198. } else {
  10199. match = regex.exec(output);
  10200. }
  10201. }
  10202. return { isMatch: Boolean(match), match, output };
  10203. };
  10204. /**
  10205. * Match the basename of a filepath.
  10206. *
  10207. * ```js
  10208. * const picomatch = require('picomatch');
  10209. * // picomatch.matchBase(input, glob[, options]);
  10210. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  10211. * ```
  10212. * @param {String} `input` String to test.
  10213. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  10214. * @return {Boolean}
  10215. * @api public
  10216. */
  10217. picomatch.matchBase = (input, glob, options) => {
  10218. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  10219. return regex.test(utils.basename(input));
  10220. };
  10221. /**
  10222. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  10223. *
  10224. * ```js
  10225. * const picomatch = require('picomatch');
  10226. * // picomatch.isMatch(string, patterns[, options]);
  10227. *
  10228. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  10229. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  10230. * ```
  10231. * @param {String|Array} str The string to test.
  10232. * @param {String|Array} patterns One or more glob patterns to use for matching.
  10233. * @param {Object} [options] See available [options](#options).
  10234. * @return {Boolean} Returns true if any patterns match `str`
  10235. * @api public
  10236. */
  10237. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  10238. /**
  10239. * Parse a glob pattern to create the source string for a regular
  10240. * expression.
  10241. *
  10242. * ```js
  10243. * const picomatch = require('picomatch');
  10244. * const result = picomatch.parse(pattern[, options]);
  10245. * ```
  10246. * @param {String} `pattern`
  10247. * @param {Object} `options`
  10248. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  10249. * @api public
  10250. */
  10251. picomatch.parse = (pattern, options) => {
  10252. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  10253. return parse(pattern, { ...options, fastpaths: false });
  10254. };
  10255. /**
  10256. * Scan a glob pattern to separate the pattern into segments.
  10257. *
  10258. * ```js
  10259. * const picomatch = require('picomatch');
  10260. * // picomatch.scan(input[, options]);
  10261. *
  10262. * const result = picomatch.scan('!./foo/*.js');
  10263. * console.log(result);
  10264. * { prefix: '!./',
  10265. * input: '!./foo/*.js',
  10266. * start: 3,
  10267. * base: 'foo',
  10268. * glob: '*.js',
  10269. * isBrace: false,
  10270. * isBracket: false,
  10271. * isGlob: true,
  10272. * isExtglob: false,
  10273. * isGlobstar: false,
  10274. * negated: true }
  10275. * ```
  10276. * @param {String} `input` Glob pattern to scan.
  10277. * @param {Object} `options`
  10278. * @return {Object} Returns an object with
  10279. * @api public
  10280. */
  10281. picomatch.scan = (input, options) => scan(input, options);
  10282. /**
  10283. * Compile a regular expression from the `state` object returned by the
  10284. * [parse()](#parse) method.
  10285. *
  10286. * @param {Object} `state`
  10287. * @param {Object} `options`
  10288. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  10289. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  10290. * @return {RegExp}
  10291. * @api public
  10292. */
  10293. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  10294. if (returnOutput === true) {
  10295. return state.output;
  10296. }
  10297. const opts = options || {};
  10298. const prepend = opts.contains ? '' : '^';
  10299. const append = opts.contains ? '' : '$';
  10300. let source = `${prepend}(?:${state.output})${append}`;
  10301. if (state && state.negated === true) {
  10302. source = `^(?!${source}).*$`;
  10303. }
  10304. const regex = picomatch.toRegex(source, options);
  10305. if (returnState === true) {
  10306. regex.state = state;
  10307. }
  10308. return regex;
  10309. };
  10310. /**
  10311. * Create a regular expression from a parsed glob pattern.
  10312. *
  10313. * ```js
  10314. * const picomatch = require('picomatch');
  10315. * const state = picomatch.parse('*.js');
  10316. * // picomatch.compileRe(state[, options]);
  10317. *
  10318. * console.log(picomatch.compileRe(state));
  10319. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  10320. * ```
  10321. * @param {String} `state` The object returned from the `.parse` method.
  10322. * @param {Object} `options`
  10323. * @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.
  10324. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  10325. * @return {RegExp} Returns a regex created from the given pattern.
  10326. * @api public
  10327. */
  10328. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  10329. if (!input || typeof input !== 'string') {
  10330. throw new TypeError('Expected a non-empty string');
  10331. }
  10332. let parsed = { negated: false, fastpaths: true };
  10333. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  10334. parsed.output = parse.fastpaths(input, options);
  10335. }
  10336. if (!parsed.output) {
  10337. parsed = parse(input, options);
  10338. }
  10339. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  10340. };
  10341. /**
  10342. * Create a regular expression from the given regex source string.
  10343. *
  10344. * ```js
  10345. * const picomatch = require('picomatch');
  10346. * // picomatch.toRegex(source[, options]);
  10347. *
  10348. * const { output } = picomatch.parse('*.js');
  10349. * console.log(picomatch.toRegex(output));
  10350. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  10351. * ```
  10352. * @param {String} `source` Regular expression source string.
  10353. * @param {Object} `options`
  10354. * @return {RegExp}
  10355. * @api public
  10356. */
  10357. picomatch.toRegex = (source, options) => {
  10358. try {
  10359. const opts = options || {};
  10360. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  10361. } catch (err) {
  10362. if (options && options.debug === true) throw err;
  10363. return /$^/;
  10364. }
  10365. };
  10366. /**
  10367. * Picomatch constants.
  10368. * @return {Object}
  10369. */
  10370. picomatch.constants = constants;
  10371. /**
  10372. * Expose "picomatch"
  10373. */
  10374. picomatch_1$1 = picomatch;
  10375. return picomatch_1$1;
  10376. }
  10377. var picomatch_1;
  10378. var hasRequiredPicomatch;
  10379. function requirePicomatch () {
  10380. if (hasRequiredPicomatch) return picomatch_1;
  10381. hasRequiredPicomatch = 1;
  10382. const pico = /*@__PURE__*/ requirePicomatch$1();
  10383. const utils = /*@__PURE__*/ requireUtils();
  10384. function picomatch(glob, options, returnState = false) {
  10385. // default to os.platform()
  10386. if (options && (options.windows === null || options.windows === undefined)) {
  10387. // don't mutate the original options object
  10388. options = { ...options, windows: utils.isWindows() };
  10389. }
  10390. return pico(glob, options, returnState);
  10391. }
  10392. Object.assign(picomatch, pico);
  10393. picomatch_1 = picomatch;
  10394. return picomatch_1;
  10395. }
  10396. var picomatchExports = /*@__PURE__*/ requirePicomatch();
  10397. const picomatch = /*@__PURE__*/getDefaultExportFromCjs(picomatchExports);
  10398. const extractors = {
  10399. ArrayPattern(names, param) {
  10400. for (const element of param.elements) {
  10401. if (element)
  10402. extractors[element.type](names, element);
  10403. }
  10404. },
  10405. AssignmentPattern(names, param) {
  10406. extractors[param.left.type](names, param.left);
  10407. },
  10408. Identifier(names, param) {
  10409. names.push(param.name);
  10410. },
  10411. MemberExpression() { },
  10412. ObjectPattern(names, param) {
  10413. for (const prop of param.properties) {
  10414. // @ts-ignore Typescript reports that this is not a valid type
  10415. if (prop.type === 'RestElement') {
  10416. extractors.RestElement(names, prop);
  10417. }
  10418. else {
  10419. extractors[prop.value.type](names, prop.value);
  10420. }
  10421. }
  10422. },
  10423. RestElement(names, param) {
  10424. extractors[param.argument.type](names, param.argument);
  10425. }
  10426. };
  10427. const extractAssignedNames = function extractAssignedNames(param) {
  10428. const names = [];
  10429. extractors[param.type](names, param);
  10430. return names;
  10431. };
  10432. // Helper since Typescript can't detect readonly arrays with Array.isArray
  10433. function isArray(arg) {
  10434. return Array.isArray(arg);
  10435. }
  10436. function ensureArray$1(thing) {
  10437. if (isArray(thing))
  10438. return thing;
  10439. if (thing == null)
  10440. return [];
  10441. return [thing];
  10442. }
  10443. const normalizePathRegExp = new RegExp(`\\${win32.sep}`, 'g');
  10444. const normalizePath = function normalizePath(filename) {
  10445. return filename.replace(normalizePathRegExp, posix.sep);
  10446. };
  10447. function getMatcherString$1(id, resolutionBase) {
  10448. if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) {
  10449. return normalizePath(id);
  10450. }
  10451. // resolve('') is valid and will default to process.cwd()
  10452. const basePath = normalizePath(resolve(resolutionBase || ''))
  10453. // escape all possible (posix + win) path characters that might interfere with regex
  10454. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  10455. // Note that we use posix.join because:
  10456. // 1. the basePath has been normalized to use /
  10457. // 2. the incoming glob (id) matcher, also uses /
  10458. // otherwise Node will force backslash (\) on windows
  10459. return posix.join(basePath, normalizePath(id));
  10460. }
  10461. const createFilter$1 = function createFilter(include, exclude, options) {
  10462. const resolutionBase = options && options.resolve;
  10463. const getMatcher = (id) => id instanceof RegExp
  10464. ? id
  10465. : {
  10466. test: (what) => {
  10467. // this refactor is a tad overly verbose but makes for easy debugging
  10468. const pattern = getMatcherString$1(id, resolutionBase);
  10469. const fn = picomatch(pattern, { dot: true });
  10470. const result = fn(what);
  10471. return result;
  10472. }
  10473. };
  10474. const includeMatchers = ensureArray$1(include).map(getMatcher);
  10475. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  10476. if (!includeMatchers.length && !excludeMatchers.length)
  10477. return (id) => typeof id === 'string' && !id.includes('\0');
  10478. return function result(id) {
  10479. if (typeof id !== 'string')
  10480. return false;
  10481. if (id.includes('\0'))
  10482. return false;
  10483. const pathId = normalizePath(id);
  10484. for (let i = 0; i < excludeMatchers.length; ++i) {
  10485. const matcher = excludeMatchers[i];
  10486. if (matcher instanceof RegExp) {
  10487. matcher.lastIndex = 0;
  10488. }
  10489. if (matcher.test(pathId))
  10490. return false;
  10491. }
  10492. for (let i = 0; i < includeMatchers.length; ++i) {
  10493. const matcher = includeMatchers[i];
  10494. if (matcher instanceof RegExp) {
  10495. matcher.lastIndex = 0;
  10496. }
  10497. if (matcher.test(pathId))
  10498. return true;
  10499. }
  10500. return !includeMatchers.length;
  10501. };
  10502. };
  10503. 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';
  10504. 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';
  10505. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  10506. forbiddenIdentifiers.add('');
  10507. class ArrayPattern extends NodeBase {
  10508. addExportedVariables(variables, exportNamesByVariable) {
  10509. for (const element of this.elements) {
  10510. element?.addExportedVariables(variables, exportNamesByVariable);
  10511. }
  10512. }
  10513. declare(kind, destructuredInitPath, init) {
  10514. const variables = [];
  10515. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10516. for (const element of this.elements) {
  10517. if (element !== null) {
  10518. variables.push(...element.declare(kind, includedPatternPath, init));
  10519. }
  10520. }
  10521. return variables;
  10522. }
  10523. deoptimizeAssignment(destructuredInitPath, init) {
  10524. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10525. for (const element of this.elements) {
  10526. element?.deoptimizeAssignment(includedPatternPath, init);
  10527. }
  10528. }
  10529. // Patterns can only be deoptimized at the empty path at the moment
  10530. deoptimizePath() {
  10531. for (const element of this.elements) {
  10532. element?.deoptimizePath(EMPTY_PATH);
  10533. }
  10534. }
  10535. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10536. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10537. for (const element of this.elements) {
  10538. if (element?.hasEffectsWhenDestructuring(context, includedPatternPath, init)) {
  10539. return true;
  10540. }
  10541. }
  10542. return false;
  10543. }
  10544. // Patterns are only checked at the empty path at the moment
  10545. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  10546. for (const element of this.elements) {
  10547. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  10548. return true;
  10549. }
  10550. return false;
  10551. }
  10552. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  10553. let included = false;
  10554. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10555. for (const element of this.elements) {
  10556. if (element) {
  10557. element.included ||= included;
  10558. included =
  10559. element.includeDestructuredIfNecessary(context, includedPatternPath, init) || included;
  10560. }
  10561. }
  10562. if (included) {
  10563. // This is necessary so that if any pattern element is included, all are
  10564. // included for proper deconflicting
  10565. for (const element of this.elements) {
  10566. if (element && !element.included) {
  10567. element.included = true;
  10568. element.includeDestructuredIfNecessary(context, includedPatternPath, init);
  10569. }
  10570. }
  10571. }
  10572. return (this.included ||= included);
  10573. }
  10574. markDeclarationReached() {
  10575. for (const element of this.elements) {
  10576. element?.markDeclarationReached();
  10577. }
  10578. }
  10579. }
  10580. ArrayPattern.prototype.includeNode = onlyIncludeSelf;
  10581. const getIncludedPatternPath = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  10582. ? destructuredInitPath
  10583. : [...destructuredInitPath, UnknownInteger];
  10584. class ArrowFunctionExpression extends FunctionBase {
  10585. constructor() {
  10586. super(...arguments);
  10587. this.objectEntity = null;
  10588. }
  10589. get expression() {
  10590. return isFlagSet(this.flags, 8388608 /* Flag.expression */);
  10591. }
  10592. set expression(value) {
  10593. this.flags = setFlag(this.flags, 8388608 /* Flag.expression */, value);
  10594. }
  10595. createScope(parentScope) {
  10596. this.scope = new ReturnValueScope(parentScope, false);
  10597. }
  10598. hasEffects() {
  10599. return false;
  10600. }
  10601. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10602. if (this.annotationNoSideEffects &&
  10603. path.length === 0 &&
  10604. interaction.type === INTERACTION_CALLED) {
  10605. return false;
  10606. }
  10607. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  10608. return true;
  10609. }
  10610. if (interaction.type === INTERACTION_CALLED) {
  10611. const { ignore, brokenFlow } = context;
  10612. context.ignore = {
  10613. breaks: false,
  10614. continues: false,
  10615. labels: new Set(),
  10616. returnYield: true,
  10617. this: false
  10618. };
  10619. if (this.body.hasEffects(context))
  10620. return true;
  10621. context.ignore = ignore;
  10622. context.brokenFlow = brokenFlow;
  10623. }
  10624. return false;
  10625. }
  10626. onlyFunctionCallUsed() {
  10627. const isIIFE = this.parent.type === CallExpression$1 &&
  10628. this.parent.callee === this;
  10629. return isIIFE || super.onlyFunctionCallUsed();
  10630. }
  10631. include(context, includeChildrenRecursively) {
  10632. super.include(context, includeChildrenRecursively);
  10633. for (const parameter of this.params) {
  10634. if (!(parameter instanceof Identifier)) {
  10635. parameter.include(context, includeChildrenRecursively);
  10636. }
  10637. }
  10638. }
  10639. includeNode(context) {
  10640. this.included = true;
  10641. this.body.includePath(UNKNOWN_PATH, context);
  10642. for (const parameter of this.params) {
  10643. if (!(parameter instanceof Identifier)) {
  10644. parameter.includePath(UNKNOWN_PATH, context);
  10645. }
  10646. }
  10647. }
  10648. getObjectEntity() {
  10649. if (this.objectEntity !== null) {
  10650. return this.objectEntity;
  10651. }
  10652. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  10653. }
  10654. }
  10655. class ObjectPattern extends NodeBase {
  10656. addExportedVariables(variables, exportNamesByVariable) {
  10657. for (const property of this.properties) {
  10658. if (property.type === Property$1) {
  10659. property.value.addExportedVariables(variables, exportNamesByVariable);
  10660. }
  10661. else {
  10662. property.argument.addExportedVariables(variables, exportNamesByVariable);
  10663. }
  10664. }
  10665. }
  10666. declare(kind, destructuredInitPath, init) {
  10667. const variables = [];
  10668. for (const property of this.properties) {
  10669. variables.push(...property.declare(kind, destructuredInitPath, init));
  10670. }
  10671. return variables;
  10672. }
  10673. deoptimizeAssignment(destructuredInitPath, init) {
  10674. for (const property of this.properties) {
  10675. property.deoptimizeAssignment(destructuredInitPath, init);
  10676. }
  10677. }
  10678. deoptimizePath(path) {
  10679. if (path.length === 0) {
  10680. for (const property of this.properties) {
  10681. property.deoptimizePath(path);
  10682. }
  10683. }
  10684. }
  10685. hasEffectsOnInteractionAtPath(
  10686. // At the moment, this is only triggered for assignment left-hand sides,
  10687. // where the path is empty
  10688. _path, interaction, context) {
  10689. for (const property of this.properties) {
  10690. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  10691. return true;
  10692. }
  10693. return false;
  10694. }
  10695. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10696. for (const property of this.properties) {
  10697. if (property.hasEffectsWhenDestructuring(context, destructuredInitPath, init))
  10698. return true;
  10699. }
  10700. return false;
  10701. }
  10702. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  10703. if (!this.properties.length)
  10704. return false;
  10705. const lastProperty = this.properties.at(-1);
  10706. const lastPropertyIncluded = lastProperty.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  10707. const lastPropertyIsRestElement = lastProperty.type === RestElement$1;
  10708. let included = lastPropertyIsRestElement ? lastPropertyIncluded : false;
  10709. for (const property of this.properties.slice(0, -1)) {
  10710. if (lastPropertyIsRestElement && lastPropertyIncluded) {
  10711. property.includeNode(context);
  10712. }
  10713. included =
  10714. property.includeDestructuredIfNecessary(context, destructuredInitPath, init) || included;
  10715. }
  10716. return (this.included ||= included);
  10717. }
  10718. markDeclarationReached() {
  10719. for (const property of this.properties) {
  10720. property.markDeclarationReached();
  10721. }
  10722. }
  10723. render(code, options) {
  10724. if (this.properties.length > 0) {
  10725. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  10726. let lastSeparatorPos = null;
  10727. for (const { node, separator, start, end } of separatedNodes) {
  10728. if (!node.included) {
  10729. treeshakeNode(node, code, start, end);
  10730. continue;
  10731. }
  10732. lastSeparatorPos = separator;
  10733. node.render(code, options);
  10734. }
  10735. if (lastSeparatorPos) {
  10736. code.remove(lastSeparatorPos, this.end - 1);
  10737. }
  10738. }
  10739. }
  10740. }
  10741. ObjectPattern.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  10742. ObjectPattern.prototype.applyDeoptimizations = doNotDeoptimize;
  10743. class AssignmentExpression extends NodeBase {
  10744. hasEffects(context) {
  10745. const { deoptimized, left, operator, right } = this;
  10746. if (!deoptimized)
  10747. this.applyDeoptimizations();
  10748. // MemberExpressions do not access the property before assignments if the
  10749. // operator is '='.
  10750. return (right.hasEffects(context) ||
  10751. left.hasEffectsAsAssignmentTarget(context, operator !== '=') ||
  10752. this.left.hasEffectsWhenDestructuring?.(context, EMPTY_PATH, right));
  10753. }
  10754. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10755. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  10756. }
  10757. include(context, includeChildrenRecursively) {
  10758. const { deoptimized, left, right, operator } = this;
  10759. if (!deoptimized)
  10760. this.applyDeoptimizations();
  10761. if (!this.included)
  10762. this.includeNode(context);
  10763. const hasEffectsContext = createHasEffectsContext();
  10764. if (includeChildrenRecursively ||
  10765. operator !== '=' ||
  10766. left.included ||
  10767. left.hasEffectsAsAssignmentTarget(hasEffectsContext, false) ||
  10768. left.hasEffectsWhenDestructuring?.(hasEffectsContext, EMPTY_PATH, right)) {
  10769. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  10770. }
  10771. right.include(context, includeChildrenRecursively);
  10772. }
  10773. includeNode(context) {
  10774. this.included = true;
  10775. if (!this.deoptimized)
  10776. this.applyDeoptimizations();
  10777. this.right.includePath(UNKNOWN_PATH, context);
  10778. }
  10779. initialise() {
  10780. super.initialise();
  10781. if (this.left instanceof Identifier) {
  10782. const variable = this.scope.variables.get(this.left.name);
  10783. if (variable?.kind === 'const') {
  10784. this.scope.context.error(logConstVariableReassignError(), this.left.start);
  10785. }
  10786. }
  10787. this.left.setAssignedValue(this.right);
  10788. }
  10789. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  10790. const { left, right, start, end, parent } = this;
  10791. if (left.included) {
  10792. left.render(code, options);
  10793. right.render(code, options);
  10794. }
  10795. else {
  10796. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  10797. code.remove(start, inclusionStart);
  10798. if (preventASI) {
  10799. removeLineBreaks(code, inclusionStart, right.start);
  10800. }
  10801. right.render(code, options, {
  10802. renderedParentType: renderedParentType || parent.type,
  10803. renderedSurroundingElement: renderedSurroundingElement || parent.type
  10804. });
  10805. }
  10806. if (options.format === 'system') {
  10807. if (left instanceof Identifier) {
  10808. const variable = left.variable;
  10809. const exportNames = options.exportNamesByVariable.get(variable);
  10810. if (exportNames) {
  10811. if (exportNames.length === 1) {
  10812. renderSystemExportExpression(variable, start, end, code, options);
  10813. }
  10814. else {
  10815. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  10816. }
  10817. return;
  10818. }
  10819. }
  10820. else {
  10821. const systemPatternExports = [];
  10822. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  10823. if (systemPatternExports.length > 0) {
  10824. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  10825. return;
  10826. }
  10827. }
  10828. }
  10829. if (left.included &&
  10830. left instanceof ObjectPattern &&
  10831. (renderedSurroundingElement === ExpressionStatement$1 ||
  10832. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  10833. code.appendRight(start, '(');
  10834. code.prependLeft(end, ')');
  10835. }
  10836. }
  10837. applyDeoptimizations() {
  10838. this.deoptimized = true;
  10839. this.left.deoptimizeAssignment(EMPTY_PATH, this.right);
  10840. this.scope.context.requestTreeshakingPass();
  10841. }
  10842. }
  10843. class AssignmentPattern extends NodeBase {
  10844. addExportedVariables(variables, exportNamesByVariable) {
  10845. this.left.addExportedVariables(variables, exportNamesByVariable);
  10846. }
  10847. declare(kind, destructuredInitPath, init) {
  10848. return this.left.declare(kind, destructuredInitPath, init);
  10849. }
  10850. deoptimizeAssignment(destructuredInitPath, init) {
  10851. this.left.deoptimizeAssignment(destructuredInitPath, init);
  10852. }
  10853. deoptimizePath(path) {
  10854. if (path.length === 0) {
  10855. this.left.deoptimizePath(path);
  10856. }
  10857. }
  10858. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10859. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  10860. }
  10861. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10862. return this.left.hasEffectsWhenDestructuring(context, destructuredInitPath, init);
  10863. }
  10864. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  10865. let included = this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init) ||
  10866. this.included;
  10867. if ((included ||= this.right.shouldBeIncluded(context))) {
  10868. this.right.include(context, false);
  10869. if (!this.left.included) {
  10870. this.left.included = true;
  10871. // Unfortunately, we need to include the left side again now, so that
  10872. // any declared variables are properly included.
  10873. this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  10874. }
  10875. }
  10876. return (this.included = included);
  10877. }
  10878. includeNode(context) {
  10879. this.included = true;
  10880. if (!this.deoptimized)
  10881. this.applyDeoptimizations();
  10882. this.right.includePath(UNKNOWN_PATH, context);
  10883. }
  10884. markDeclarationReached() {
  10885. this.left.markDeclarationReached();
  10886. }
  10887. render(code, options, { isShorthandProperty } = BLANK) {
  10888. this.left.render(code, options, { isShorthandProperty });
  10889. this.right.render(code, options);
  10890. }
  10891. applyDeoptimizations() {
  10892. this.deoptimized = true;
  10893. this.left.deoptimizePath(EMPTY_PATH);
  10894. this.right.deoptimizePath(UNKNOWN_PATH);
  10895. this.scope.context.requestTreeshakingPass();
  10896. }
  10897. }
  10898. class AwaitExpression extends NodeBase {
  10899. hasEffects() {
  10900. if (!this.deoptimized)
  10901. this.applyDeoptimizations();
  10902. return true;
  10903. }
  10904. initialise() {
  10905. super.initialise();
  10906. let parent = this.parent;
  10907. do {
  10908. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  10909. return;
  10910. } while ((parent = parent.parent));
  10911. this.scope.context.usesTopLevelAwait = true;
  10912. }
  10913. include(context, includeChildrenRecursively) {
  10914. if (!this.included)
  10915. this.includeNode(context);
  10916. this.argument.include(context, includeChildrenRecursively);
  10917. }
  10918. includeNode(context) {
  10919. this.included = true;
  10920. if (!this.deoptimized)
  10921. this.applyDeoptimizations();
  10922. // Thenables need to be included
  10923. this.argument.includePath(THEN_PATH, context);
  10924. }
  10925. includePath(path, context) {
  10926. if (!this.deoptimized)
  10927. this.applyDeoptimizations();
  10928. if (!this.included)
  10929. this.includeNode(context);
  10930. this.argument.includePath(path, context);
  10931. }
  10932. }
  10933. const THEN_PATH = ['then'];
  10934. const binaryOperators = {
  10935. '!=': (left, right) => left != right,
  10936. '!==': (left, right) => left !== right,
  10937. '%': (left, right) => left % right,
  10938. '&': (left, right) => left & right,
  10939. '*': (left, right) => left * right,
  10940. // At the moment, "**" will be transpiled to Math.pow
  10941. '**': (left, right) => left ** right,
  10942. '+': (left, right) => left + right,
  10943. '-': (left, right) => left - right,
  10944. '/': (left, right) => left / right,
  10945. '<': (left, right) => left < right,
  10946. '<<': (left, right) => left << right,
  10947. '<=': (left, right) => left <= right,
  10948. '==': (left, right) => left == right,
  10949. '===': (left, right) => left === right,
  10950. '>': (left, right) => left > right,
  10951. '>=': (left, right) => left >= right,
  10952. '>>': (left, right) => left >> right,
  10953. '>>>': (left, right) => left >>> right,
  10954. '^': (left, right) => left ^ right,
  10955. '|': (left, right) => left | right
  10956. // We use the fallback for cases where we return something unknown
  10957. // in: () => UnknownValue,
  10958. // instanceof: () => UnknownValue,
  10959. };
  10960. class BinaryExpression extends NodeBase {
  10961. deoptimizeCache() { }
  10962. getLiteralValueAtPath(path, recursionTracker, origin) {
  10963. if (path.length > 0)
  10964. return UnknownValue;
  10965. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10966. if (typeof leftValue === 'symbol')
  10967. return UnknownValue;
  10968. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10969. if (typeof rightValue === 'symbol')
  10970. return UnknownValue;
  10971. const operatorFunction = binaryOperators[this.operator];
  10972. if (!operatorFunction)
  10973. return UnknownValue;
  10974. return operatorFunction(leftValue, rightValue);
  10975. }
  10976. hasEffects(context) {
  10977. // support some implicit type coercion runtime errors
  10978. if (this.operator === '+' &&
  10979. this.parent instanceof ExpressionStatement &&
  10980. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  10981. return true;
  10982. }
  10983. return super.hasEffects(context);
  10984. }
  10985. hasEffectsOnInteractionAtPath(path, { type }) {
  10986. return type !== INTERACTION_ACCESSED || path.length > 1;
  10987. }
  10988. includeNode(context) {
  10989. this.included = true;
  10990. if (this.operator === 'in') {
  10991. this.right.includePath(UNKNOWN_PATH, context);
  10992. }
  10993. }
  10994. removeAnnotations(code) {
  10995. this.left.removeAnnotations(code);
  10996. }
  10997. render(code, options, { renderedSurroundingElement } = BLANK) {
  10998. this.left.render(code, options, { renderedSurroundingElement });
  10999. this.right.render(code, options);
  11000. }
  11001. }
  11002. BinaryExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  11003. class BreakStatement extends NodeBase {
  11004. hasEffects(context) {
  11005. if (this.label) {
  11006. if (!context.ignore.labels.has(this.label.name))
  11007. return true;
  11008. context.includedLabels.add(this.label.name);
  11009. }
  11010. else {
  11011. if (!context.ignore.breaks)
  11012. return true;
  11013. context.hasBreak = true;
  11014. }
  11015. context.brokenFlow = true;
  11016. return false;
  11017. }
  11018. include(context, includeChildrenRecursively) {
  11019. this.included = true;
  11020. if (this.label) {
  11021. this.label.include(context, includeChildrenRecursively);
  11022. context.includedLabels.add(this.label.name);
  11023. }
  11024. else {
  11025. context.hasBreak = true;
  11026. }
  11027. context.brokenFlow = true;
  11028. }
  11029. }
  11030. BreakStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11031. BreakStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11032. function renderCallArguments(code, options, node) {
  11033. if (node.arguments.length > 0) {
  11034. if (node.arguments[node.arguments.length - 1].included) {
  11035. for (const argument of node.arguments) {
  11036. argument.render(code, options);
  11037. }
  11038. }
  11039. else {
  11040. let lastIncludedIndex = node.arguments.length - 2;
  11041. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  11042. lastIncludedIndex--;
  11043. }
  11044. if (lastIncludedIndex >= 0) {
  11045. for (let index = 0; index <= lastIncludedIndex; index++) {
  11046. node.arguments[index].render(code, options);
  11047. }
  11048. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  11049. }
  11050. else {
  11051. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  11052. }
  11053. }
  11054. }
  11055. }
  11056. class CallExpressionBase extends NodeBase {
  11057. constructor() {
  11058. super(...arguments);
  11059. this.returnExpression = null;
  11060. this.deoptimizableDependentExpressions = [];
  11061. this.expressionsToBeDeoptimized = new Set();
  11062. }
  11063. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11064. const { args } = interaction;
  11065. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  11066. if (isPure)
  11067. return;
  11068. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  11069. if (deoptimizedExpressions.length === 0)
  11070. return;
  11071. if (returnExpression === UNKNOWN_EXPRESSION) {
  11072. for (const expression of deoptimizedExpressions) {
  11073. expression.deoptimizePath(UNKNOWN_PATH);
  11074. }
  11075. }
  11076. else {
  11077. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11078. for (const expression of deoptimizedExpressions) {
  11079. this.expressionsToBeDeoptimized.add(expression);
  11080. }
  11081. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11082. }, null);
  11083. }
  11084. }
  11085. deoptimizeCache() {
  11086. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  11087. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11088. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  11089. this.expressionsToBeDeoptimized = EMPTY_SET;
  11090. this.deoptimizableDependentExpressions = EMPTY_ARRAY;
  11091. for (const expression of deoptimizableDependentExpressions) {
  11092. expression.deoptimizeCache();
  11093. }
  11094. for (const expression of expressionsToBeDeoptimized) {
  11095. expression.deoptimizePath(UNKNOWN_PATH);
  11096. }
  11097. }
  11098. }
  11099. deoptimizePath(path) {
  11100. if (path.length === 0 ||
  11101. this.scope.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  11102. return;
  11103. }
  11104. const [returnExpression] = this.getReturnExpression();
  11105. if (returnExpression !== UNKNOWN_EXPRESSION) {
  11106. returnExpression.deoptimizePath(path);
  11107. }
  11108. }
  11109. getLiteralValueAtPath(path, recursionTracker, origin) {
  11110. const [returnExpression] = this.getReturnExpression(recursionTracker);
  11111. if (returnExpression === UNKNOWN_EXPRESSION) {
  11112. return UnknownValue;
  11113. }
  11114. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11115. this.deoptimizableDependentExpressions.push(origin);
  11116. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  11117. }, UnknownValue);
  11118. }
  11119. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11120. const returnExpression = this.getReturnExpression(recursionTracker);
  11121. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  11122. return returnExpression;
  11123. }
  11124. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11125. this.deoptimizableDependentExpressions.push(origin);
  11126. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11127. return [expression, isPure || returnExpression[1]];
  11128. }, UNKNOWN_RETURN_EXPRESSION);
  11129. }
  11130. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11131. const { type } = interaction;
  11132. if (type === INTERACTION_CALLED) {
  11133. const { args, withNew } = interaction;
  11134. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  11135. return false;
  11136. }
  11137. }
  11138. else if ((type === INTERACTION_ASSIGNED
  11139. ? context.assigned
  11140. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  11141. return false;
  11142. }
  11143. const [returnExpression, isPure] = this.getReturnExpression();
  11144. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  11145. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  11146. }
  11147. }
  11148. class CallExpression extends CallExpressionBase {
  11149. get hasCheckedForWarnings() {
  11150. return isFlagSet(this.flags, 268435456 /* Flag.checkedForWarnings */);
  11151. }
  11152. set hasCheckedForWarnings(value) {
  11153. this.flags = setFlag(this.flags, 268435456 /* Flag.checkedForWarnings */, value);
  11154. }
  11155. get optional() {
  11156. return isFlagSet(this.flags, 128 /* Flag.optional */);
  11157. }
  11158. set optional(value) {
  11159. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  11160. }
  11161. bind() {
  11162. super.bind();
  11163. this.interaction = {
  11164. args: [
  11165. this.callee instanceof MemberExpression && !this.callee.variable
  11166. ? this.callee.object
  11167. : null,
  11168. ...this.arguments
  11169. ],
  11170. type: INTERACTION_CALLED,
  11171. withNew: false
  11172. };
  11173. }
  11174. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  11175. return getChainElementLiteralValueAtPath(this, this.callee, path, recursionTracker, origin);
  11176. }
  11177. hasEffects(context) {
  11178. if (!this.deoptimized)
  11179. this.applyDeoptimizations();
  11180. for (const argument of this.arguments) {
  11181. if (argument.hasEffects(context))
  11182. return true;
  11183. }
  11184. if (this.annotationPure) {
  11185. return false;
  11186. }
  11187. return (this.callee.hasEffects(context) ||
  11188. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  11189. }
  11190. hasEffectsAsChainElement(context) {
  11191. const calleeHasEffects = 'hasEffectsAsChainElement' in this.callee
  11192. ? this.callee.hasEffectsAsChainElement(context)
  11193. : this.callee.hasEffects(context);
  11194. if (calleeHasEffects === IS_SKIPPED_CHAIN)
  11195. return IS_SKIPPED_CHAIN;
  11196. if (this.optional &&
  11197. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  11198. return (!this.annotationPure && calleeHasEffects) || IS_SKIPPED_CHAIN;
  11199. }
  11200. // We only apply deoptimizations lazily once we know we are not skipping
  11201. if (!this.deoptimized)
  11202. this.applyDeoptimizations();
  11203. for (const argument of this.arguments) {
  11204. if (argument.hasEffects(context))
  11205. return true;
  11206. }
  11207. return (!this.annotationPure &&
  11208. (calleeHasEffects ||
  11209. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)));
  11210. }
  11211. include(context, includeChildrenRecursively) {
  11212. if (!this.included)
  11213. this.includeNode(context);
  11214. if (includeChildrenRecursively) {
  11215. super.include(context, true);
  11216. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  11217. this.callee instanceof Identifier &&
  11218. this.callee.variable) {
  11219. this.callee.variable.markCalledFromTryStatement();
  11220. }
  11221. }
  11222. else {
  11223. this.callee.include(context, false);
  11224. this.callee.includeCallArguments(this.interaction, context);
  11225. }
  11226. }
  11227. includeNode(context) {
  11228. this.included = true;
  11229. if (!this.deoptimized)
  11230. this.applyDeoptimizations();
  11231. this.callee.includePath(UNKNOWN_PATH, context);
  11232. }
  11233. initialise() {
  11234. super.initialise();
  11235. if (this.annotations &&
  11236. this.scope.context.options.treeshake.annotations) {
  11237. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  11238. }
  11239. }
  11240. render(code, options, { renderedSurroundingElement } = BLANK) {
  11241. this.callee.render(code, options, {
  11242. isCalleeOfRenderedParent: true,
  11243. renderedSurroundingElement
  11244. });
  11245. renderCallArguments(code, options, this);
  11246. if (this.callee instanceof Identifier && !this.hasCheckedForWarnings) {
  11247. this.hasCheckedForWarnings = true;
  11248. const variable = this.scope.findVariable(this.callee.name);
  11249. if (variable.isNamespace) {
  11250. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(this.callee.name), this.start);
  11251. }
  11252. if (this.callee.name === 'eval') {
  11253. this.scope.context.log(LOGLEVEL_WARN, logEval(this.scope.context.module.id), this.start);
  11254. }
  11255. }
  11256. }
  11257. applyDeoptimizations() {
  11258. this.deoptimized = true;
  11259. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  11260. this.scope.context.requestTreeshakingPass();
  11261. }
  11262. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  11263. if (this.returnExpression === null) {
  11264. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11265. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  11266. }
  11267. return this.returnExpression;
  11268. }
  11269. }
  11270. class CatchClause extends NodeBase {
  11271. createScope(parentScope) {
  11272. this.scope = new ParameterScope(parentScope, true);
  11273. }
  11274. parseNode(esTreeNode) {
  11275. const { body, param, type } = esTreeNode;
  11276. this.type = type;
  11277. if (param) {
  11278. this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
  11279. this.param.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  11280. }
  11281. this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
  11282. return super.parseNode(esTreeNode);
  11283. }
  11284. }
  11285. CatchClause.prototype.preventChildBlockScope = true;
  11286. CatchClause.prototype.includeNode = onlyIncludeSelf;
  11287. class ChainExpression extends NodeBase {
  11288. // deoptimizations are not relevant as we are not caching values
  11289. deoptimizeCache() { }
  11290. getLiteralValueAtPath(path, recursionTracker, origin) {
  11291. const literalValue = this.expression.getLiteralValueAtPathAsChainElement(path, recursionTracker, origin);
  11292. return literalValue === IS_SKIPPED_CHAIN ? undefined : literalValue;
  11293. }
  11294. hasEffects(context) {
  11295. return this.expression.hasEffectsAsChainElement(context) === true;
  11296. }
  11297. includePath(path, context) {
  11298. this.included = true;
  11299. this.expression.includePath(path, context);
  11300. }
  11301. removeAnnotations(code) {
  11302. this.expression.removeAnnotations(code);
  11303. }
  11304. }
  11305. ChainExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11306. ChainExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  11307. class ClassBodyScope extends ChildScope {
  11308. constructor(parent, classNode) {
  11309. const { context } = parent;
  11310. super(parent, context);
  11311. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, EMPTY_PATH, context, 'other')));
  11312. this.instanceScope = new ChildScope(this, context);
  11313. this.instanceScope.variables.set('this', new ThisVariable(context));
  11314. }
  11315. findLexicalBoundary() {
  11316. return this;
  11317. }
  11318. }
  11319. class ClassBody extends NodeBase {
  11320. createScope(parentScope) {
  11321. this.scope = new ClassBodyScope(parentScope, this.parent);
  11322. }
  11323. include(context, includeChildrenRecursively) {
  11324. this.included = true;
  11325. this.scope.context.includeVariableInModule(this.scope.thisVariable, UNKNOWN_PATH, context);
  11326. for (const definition of this.body) {
  11327. definition.include(context, includeChildrenRecursively);
  11328. }
  11329. }
  11330. parseNode(esTreeNode) {
  11331. const body = (this.body = new Array(esTreeNode.body.length));
  11332. let index = 0;
  11333. for (const definition of esTreeNode.body) {
  11334. body[index++] = new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition);
  11335. }
  11336. return super.parseNode(esTreeNode);
  11337. }
  11338. }
  11339. ClassBody.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11340. ClassBody.prototype.applyDeoptimizations = doNotDeoptimize;
  11341. class ClassExpression extends ClassNode {
  11342. render(code, options, { renderedSurroundingElement } = BLANK) {
  11343. super.render(code, options);
  11344. if (renderedSurroundingElement === ExpressionStatement$1) {
  11345. code.appendRight(this.start, '(');
  11346. code.prependLeft(this.end, ')');
  11347. }
  11348. }
  11349. }
  11350. function tryCastLiteralValueToBoolean(literalValue) {
  11351. if (typeof literalValue === 'symbol') {
  11352. if (literalValue === UnknownFalsyValue) {
  11353. return false;
  11354. }
  11355. if (literalValue === UnknownTruthyValue) {
  11356. return true;
  11357. }
  11358. return UnknownValue;
  11359. }
  11360. return !!literalValue;
  11361. }
  11362. class MultiExpression extends ExpressionEntity {
  11363. constructor(expressions) {
  11364. super();
  11365. this.expressions = expressions;
  11366. }
  11367. deoptimizePath(path) {
  11368. for (const expression of this.expressions) {
  11369. expression.deoptimizePath(path);
  11370. }
  11371. }
  11372. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11373. return [
  11374. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  11375. false
  11376. ];
  11377. }
  11378. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11379. for (const expression of this.expressions) {
  11380. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  11381. return true;
  11382. }
  11383. return false;
  11384. }
  11385. }
  11386. class ConditionalExpression extends NodeBase {
  11387. constructor() {
  11388. super(...arguments);
  11389. this.expressionsToBeDeoptimized = [];
  11390. this.usedBranch = null;
  11391. }
  11392. get isBranchResolutionAnalysed() {
  11393. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  11394. }
  11395. set isBranchResolutionAnalysed(value) {
  11396. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  11397. }
  11398. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11399. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11400. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11401. }
  11402. deoptimizeCache() {
  11403. if (this.usedBranch !== null) {
  11404. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  11405. this.usedBranch = null;
  11406. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  11407. if (this.included) {
  11408. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  11409. }
  11410. const { expressionsToBeDeoptimized } = this;
  11411. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  11412. for (const expression of expressionsToBeDeoptimized) {
  11413. expression.deoptimizeCache();
  11414. }
  11415. }
  11416. }
  11417. deoptimizePath(path) {
  11418. const usedBranch = this.getUsedBranch();
  11419. if (usedBranch) {
  11420. usedBranch.deoptimizePath(path);
  11421. }
  11422. else {
  11423. this.consequent.deoptimizePath(path);
  11424. this.alternate.deoptimizePath(path);
  11425. }
  11426. }
  11427. getLiteralValueAtPath(path, recursionTracker, origin) {
  11428. const usedBranch = this.getUsedBranch();
  11429. if (!usedBranch)
  11430. return UnknownValue;
  11431. this.expressionsToBeDeoptimized.push(origin);
  11432. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  11433. }
  11434. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11435. const usedBranch = this.getUsedBranch();
  11436. if (!usedBranch)
  11437. return [
  11438. new MultiExpression([
  11439. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  11440. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  11441. ]),
  11442. false
  11443. ];
  11444. this.expressionsToBeDeoptimized.push(origin);
  11445. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11446. }
  11447. hasEffects(context) {
  11448. if (this.test.hasEffects(context))
  11449. return true;
  11450. const usedBranch = this.getUsedBranch();
  11451. if (!usedBranch) {
  11452. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  11453. }
  11454. return usedBranch.hasEffects(context);
  11455. }
  11456. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11457. const usedBranch = this.getUsedBranch();
  11458. if (!usedBranch) {
  11459. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  11460. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  11461. }
  11462. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  11463. }
  11464. include(context, includeChildrenRecursively) {
  11465. this.included = true;
  11466. const usedBranch = this.getUsedBranch();
  11467. if (usedBranch === null || includeChildrenRecursively || this.test.shouldBeIncluded(context)) {
  11468. this.test.include(context, includeChildrenRecursively);
  11469. this.consequent.include(context, includeChildrenRecursively);
  11470. this.alternate.include(context, includeChildrenRecursively);
  11471. }
  11472. else {
  11473. usedBranch.include(context, includeChildrenRecursively);
  11474. }
  11475. }
  11476. includePath(path, context) {
  11477. this.included = true;
  11478. const usedBranch = this.getUsedBranch();
  11479. if (usedBranch === null || this.test.shouldBeIncluded(context)) {
  11480. this.consequent.includePath(path, context);
  11481. this.alternate.includePath(path, context);
  11482. }
  11483. else {
  11484. usedBranch.includePath(path, context);
  11485. }
  11486. }
  11487. includeCallArguments(interaction, context) {
  11488. const usedBranch = this.getUsedBranch();
  11489. if (usedBranch) {
  11490. usedBranch.includeCallArguments(interaction, context);
  11491. }
  11492. else {
  11493. this.consequent.includeCallArguments(interaction, context);
  11494. this.alternate.includeCallArguments(interaction, context);
  11495. }
  11496. }
  11497. removeAnnotations(code) {
  11498. this.test.removeAnnotations(code);
  11499. }
  11500. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  11501. if (this.test.included) {
  11502. this.test.render(code, options, { renderedSurroundingElement });
  11503. this.consequent.render(code, options);
  11504. this.alternate.render(code, options);
  11505. }
  11506. else {
  11507. const usedBranch = this.getUsedBranch();
  11508. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  11509. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  11510. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  11511. : colonPos) + 1);
  11512. if (preventASI) {
  11513. removeLineBreaks(code, inclusionStart, usedBranch.start);
  11514. }
  11515. code.remove(this.start, inclusionStart);
  11516. if (this.consequent.included) {
  11517. code.remove(colonPos, this.end);
  11518. }
  11519. this.test.removeAnnotations(code);
  11520. usedBranch.render(code, options, {
  11521. isCalleeOfRenderedParent,
  11522. preventASI: true,
  11523. renderedParentType: renderedParentType || this.parent.type,
  11524. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  11525. });
  11526. }
  11527. }
  11528. getUsedBranch() {
  11529. if (this.isBranchResolutionAnalysed) {
  11530. return this.usedBranch;
  11531. }
  11532. this.isBranchResolutionAnalysed = true;
  11533. const testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  11534. return typeof testValue === 'symbol'
  11535. ? null
  11536. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  11537. }
  11538. }
  11539. ConditionalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11540. ConditionalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  11541. class ContinueStatement extends NodeBase {
  11542. hasEffects(context) {
  11543. if (this.label) {
  11544. if (!context.ignore.labels.has(this.label.name))
  11545. return true;
  11546. context.includedLabels.add(this.label.name);
  11547. }
  11548. else {
  11549. if (!context.ignore.continues)
  11550. return true;
  11551. context.hasContinue = true;
  11552. }
  11553. context.brokenFlow = true;
  11554. return false;
  11555. }
  11556. include(context, includeChildrenRecursively) {
  11557. this.included = true;
  11558. if (this.label) {
  11559. this.label.include(context, includeChildrenRecursively);
  11560. context.includedLabels.add(this.label.name);
  11561. }
  11562. else {
  11563. context.hasContinue = true;
  11564. }
  11565. context.brokenFlow = true;
  11566. }
  11567. }
  11568. ContinueStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11569. ContinueStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11570. class DebuggerStatement extends NodeBase {
  11571. hasEffects() {
  11572. return true;
  11573. }
  11574. }
  11575. DebuggerStatement.prototype.includeNode = onlyIncludeSelf;
  11576. class Decorator extends NodeBase {
  11577. hasEffects(context) {
  11578. return (this.expression.hasEffects(context) ||
  11579. this.expression.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context));
  11580. }
  11581. }
  11582. Decorator.prototype.includeNode = onlyIncludeSelf;
  11583. function hasLoopBodyEffects(context, body) {
  11584. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  11585. const { breaks, continues } = ignore;
  11586. ignore.breaks = true;
  11587. ignore.continues = true;
  11588. context.hasBreak = false;
  11589. context.hasContinue = false;
  11590. if (body.hasEffects(context))
  11591. return true;
  11592. ignore.breaks = breaks;
  11593. ignore.continues = continues;
  11594. context.hasBreak = hasBreak;
  11595. context.hasContinue = hasContinue;
  11596. context.brokenFlow = brokenFlow;
  11597. return false;
  11598. }
  11599. function includeLoopBody(context, body, includeChildrenRecursively) {
  11600. const { brokenFlow, hasBreak, hasContinue } = context;
  11601. context.hasBreak = false;
  11602. context.hasContinue = false;
  11603. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11604. context.hasBreak = hasBreak;
  11605. context.hasContinue = hasContinue;
  11606. context.brokenFlow = brokenFlow;
  11607. }
  11608. class DoWhileStatement extends NodeBase {
  11609. hasEffects(context) {
  11610. if (this.test.hasEffects(context))
  11611. return true;
  11612. return hasLoopBodyEffects(context, this.body);
  11613. }
  11614. include(context, includeChildrenRecursively) {
  11615. this.included = true;
  11616. this.test.include(context, includeChildrenRecursively);
  11617. includeLoopBody(context, this.body, includeChildrenRecursively);
  11618. }
  11619. }
  11620. DoWhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11621. DoWhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11622. class EmptyStatement extends NodeBase {
  11623. hasEffects() {
  11624. return false;
  11625. }
  11626. }
  11627. EmptyStatement.prototype.includeNode = onlyIncludeSelf;
  11628. class ExportAllDeclaration extends NodeBase {
  11629. hasEffects() {
  11630. return false;
  11631. }
  11632. initialise() {
  11633. super.initialise();
  11634. this.scope.context.addExport(this);
  11635. }
  11636. render(code, _options, nodeRenderOptions) {
  11637. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  11638. }
  11639. }
  11640. ExportAllDeclaration.prototype.needsBoundaries = true;
  11641. ExportAllDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11642. ExportAllDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  11643. class ExportNamedDeclaration extends NodeBase {
  11644. bind() {
  11645. // Do not bind specifiers
  11646. this.declaration?.bind();
  11647. }
  11648. hasEffects(context) {
  11649. return !!this.declaration?.hasEffects(context);
  11650. }
  11651. initialise() {
  11652. super.initialise();
  11653. this.scope.context.addExport(this);
  11654. }
  11655. removeAnnotations(code) {
  11656. this.declaration?.removeAnnotations(code);
  11657. }
  11658. render(code, options, nodeRenderOptions) {
  11659. const { start, end } = nodeRenderOptions;
  11660. if (this.declaration === null) {
  11661. code.remove(start, end);
  11662. }
  11663. else {
  11664. let endBoundary = this.declaration.start;
  11665. // the start of the decorator may be before the start of the class declaration
  11666. if (this.declaration instanceof ClassDeclaration) {
  11667. const decorators = this.declaration.decorators;
  11668. for (const decorator of decorators) {
  11669. endBoundary = Math.min(endBoundary, decorator.start);
  11670. }
  11671. if (endBoundary <= this.start) {
  11672. endBoundary = this.declaration.start;
  11673. }
  11674. }
  11675. code.remove(this.start, endBoundary);
  11676. this.declaration.render(code, options, { end, start });
  11677. }
  11678. }
  11679. }
  11680. ExportNamedDeclaration.prototype.needsBoundaries = true;
  11681. ExportNamedDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11682. ExportNamedDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  11683. class ExportSpecifier extends NodeBase {
  11684. }
  11685. ExportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11686. ExportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  11687. class ForInStatement extends NodeBase {
  11688. createScope(parentScope) {
  11689. this.scope = new BlockScope(parentScope);
  11690. }
  11691. hasEffects(context) {
  11692. const { body, deoptimized, left, right } = this;
  11693. if (!deoptimized)
  11694. this.applyDeoptimizations();
  11695. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  11696. return true;
  11697. return hasLoopBodyEffects(context, body);
  11698. }
  11699. include(context, includeChildrenRecursively) {
  11700. const { body, deoptimized, left, right } = this;
  11701. if (!deoptimized)
  11702. this.applyDeoptimizations();
  11703. if (!this.included)
  11704. this.includeNode(context);
  11705. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  11706. right.include(context, includeChildrenRecursively);
  11707. includeLoopBody(context, body, includeChildrenRecursively);
  11708. }
  11709. includeNode(context) {
  11710. this.included = true;
  11711. if (!this.deoptimized)
  11712. this.applyDeoptimizations();
  11713. this.right.includePath(UNKNOWN_PATH, context);
  11714. }
  11715. initialise() {
  11716. super.initialise();
  11717. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  11718. }
  11719. render(code, options) {
  11720. this.left.render(code, options, NO_SEMICOLON);
  11721. this.right.render(code, options, NO_SEMICOLON);
  11722. // handle no space between "in" and the right side
  11723. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  11724. code.prependLeft(this.right.start, ' ');
  11725. }
  11726. this.body.render(code, options);
  11727. }
  11728. applyDeoptimizations() {
  11729. this.deoptimized = true;
  11730. this.left.deoptimizePath(EMPTY_PATH);
  11731. this.scope.context.requestTreeshakingPass();
  11732. }
  11733. }
  11734. class ForOfStatement extends NodeBase {
  11735. get await() {
  11736. return isFlagSet(this.flags, 131072 /* Flag.await */);
  11737. }
  11738. set await(value) {
  11739. this.flags = setFlag(this.flags, 131072 /* Flag.await */, value);
  11740. }
  11741. createScope(parentScope) {
  11742. this.scope = new BlockScope(parentScope);
  11743. }
  11744. hasEffects() {
  11745. if (!this.deoptimized)
  11746. this.applyDeoptimizations();
  11747. // Placeholder until proper Symbol.Iterator support
  11748. return true;
  11749. }
  11750. include(context, includeChildrenRecursively) {
  11751. const { body, deoptimized, left, right } = this;
  11752. if (!deoptimized)
  11753. this.applyDeoptimizations();
  11754. if (!this.included)
  11755. this.includeNode(context);
  11756. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  11757. right.include(context, includeChildrenRecursively);
  11758. includeLoopBody(context, body, includeChildrenRecursively);
  11759. }
  11760. includeNode(context) {
  11761. this.included = true;
  11762. if (!this.deoptimized)
  11763. this.applyDeoptimizations();
  11764. this.right.includePath(UNKNOWN_PATH, context);
  11765. }
  11766. initialise() {
  11767. super.initialise();
  11768. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  11769. }
  11770. render(code, options) {
  11771. this.left.render(code, options, NO_SEMICOLON);
  11772. this.right.render(code, options, NO_SEMICOLON);
  11773. // handle no space between "of" and the right side
  11774. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  11775. code.prependLeft(this.right.start, ' ');
  11776. }
  11777. this.body.render(code, options);
  11778. }
  11779. applyDeoptimizations() {
  11780. this.deoptimized = true;
  11781. this.left.deoptimizePath(EMPTY_PATH);
  11782. this.right.deoptimizePath(UNKNOWN_PATH);
  11783. this.scope.context.requestTreeshakingPass();
  11784. }
  11785. }
  11786. class ForStatement extends NodeBase {
  11787. createScope(parentScope) {
  11788. this.scope = new BlockScope(parentScope);
  11789. }
  11790. hasEffects(context) {
  11791. if (this.init?.hasEffects(context) ||
  11792. this.test?.hasEffects(context) ||
  11793. this.update?.hasEffects(context)) {
  11794. return true;
  11795. }
  11796. return hasLoopBodyEffects(context, this.body);
  11797. }
  11798. include(context, includeChildrenRecursively) {
  11799. this.included = true;
  11800. this.init?.include(context, includeChildrenRecursively, {
  11801. asSingleStatement: true
  11802. });
  11803. this.test?.include(context, includeChildrenRecursively);
  11804. this.update?.include(context, includeChildrenRecursively);
  11805. includeLoopBody(context, this.body, includeChildrenRecursively);
  11806. }
  11807. render(code, options) {
  11808. this.init?.render(code, options, NO_SEMICOLON);
  11809. this.test?.render(code, options, NO_SEMICOLON);
  11810. this.update?.render(code, options, NO_SEMICOLON);
  11811. this.body.render(code, options);
  11812. }
  11813. }
  11814. ForStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11815. ForStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11816. class FunctionExpression extends FunctionNode {
  11817. createScope(parentScope) {
  11818. super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
  11819. }
  11820. parseNode(esTreeNode) {
  11821. if (esTreeNode.id !== null) {
  11822. this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
  11823. }
  11824. return super.parseNode(esTreeNode);
  11825. }
  11826. onlyFunctionCallUsed() {
  11827. const isIIFE = this.parent.type === CallExpression$1 &&
  11828. this.parent.callee === this &&
  11829. (this.id === null || this.id.variable.getOnlyFunctionCallUsed());
  11830. return isIIFE || super.onlyFunctionCallUsed();
  11831. }
  11832. render(code, options, { renderedSurroundingElement } = BLANK) {
  11833. super.render(code, options);
  11834. if (renderedSurroundingElement === ExpressionStatement$1) {
  11835. code.appendRight(this.start, '(');
  11836. code.prependLeft(this.end, ')');
  11837. }
  11838. }
  11839. }
  11840. class TrackingScope extends BlockScope {
  11841. constructor() {
  11842. super(...arguments);
  11843. this.hoistedDeclarations = [];
  11844. }
  11845. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  11846. this.hoistedDeclarations.push(identifier);
  11847. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  11848. }
  11849. }
  11850. const unset = Symbol('unset');
  11851. class IfStatement extends NodeBase {
  11852. constructor() {
  11853. super(...arguments);
  11854. this.testValue = unset;
  11855. }
  11856. deoptimizeCache() {
  11857. this.testValue = UnknownValue;
  11858. }
  11859. hasEffects(context) {
  11860. if (this.test.hasEffects(context)) {
  11861. return true;
  11862. }
  11863. const testValue = this.getTestValue();
  11864. if (typeof testValue === 'symbol') {
  11865. const { brokenFlow } = context;
  11866. if (this.consequent.hasEffects(context))
  11867. return true;
  11868. const consequentBrokenFlow = context.brokenFlow;
  11869. context.brokenFlow = brokenFlow;
  11870. if (this.alternate === null)
  11871. return false;
  11872. if (this.alternate.hasEffects(context))
  11873. return true;
  11874. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  11875. return false;
  11876. }
  11877. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  11878. }
  11879. include(context, includeChildrenRecursively) {
  11880. this.included = true;
  11881. if (includeChildrenRecursively) {
  11882. this.includeRecursively(includeChildrenRecursively, context);
  11883. }
  11884. else {
  11885. const testValue = this.getTestValue();
  11886. if (typeof testValue === 'symbol') {
  11887. this.includeUnknownTest(context);
  11888. }
  11889. else {
  11890. this.includeKnownTest(context, testValue);
  11891. }
  11892. }
  11893. }
  11894. parseNode(esTreeNode) {
  11895. this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
  11896. if (esTreeNode.alternate) {
  11897. this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
  11898. }
  11899. return super.parseNode(esTreeNode);
  11900. }
  11901. render(code, options) {
  11902. const { snippets: { getPropertyAccess } } = options;
  11903. // Note that unknown test values are always included
  11904. const testValue = this.getTestValue();
  11905. const hoistedDeclarations = [];
  11906. const includesIfElse = this.test.included;
  11907. const noTreeshake = !this.scope.context.options.treeshake;
  11908. if (includesIfElse) {
  11909. this.test.render(code, options);
  11910. }
  11911. else {
  11912. code.remove(this.start, this.consequent.start);
  11913. }
  11914. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  11915. this.consequent.render(code, options);
  11916. }
  11917. else {
  11918. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  11919. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  11920. }
  11921. if (this.alternate) {
  11922. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  11923. if (includesIfElse) {
  11924. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  11925. code.prependLeft(this.alternate.start, ' ');
  11926. }
  11927. }
  11928. else {
  11929. code.remove(this.consequent.end, this.alternate.start);
  11930. }
  11931. this.alternate.render(code, options);
  11932. }
  11933. else {
  11934. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  11935. code.overwrite(this.alternate.start, this.end, ';');
  11936. }
  11937. else {
  11938. code.remove(this.consequent.end, this.end);
  11939. }
  11940. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  11941. }
  11942. }
  11943. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  11944. }
  11945. getTestValue() {
  11946. if (this.testValue === unset) {
  11947. return (this.testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  11948. }
  11949. return this.testValue;
  11950. }
  11951. includeKnownTest(context, testValue) {
  11952. if (this.test.shouldBeIncluded(context)) {
  11953. this.test.include(context, false);
  11954. }
  11955. if (testValue && this.consequent.shouldBeIncluded(context)) {
  11956. this.consequent.include(context, false, { asSingleStatement: true });
  11957. }
  11958. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  11959. this.alternate.include(context, false, { asSingleStatement: true });
  11960. }
  11961. }
  11962. includeRecursively(includeChildrenRecursively, context) {
  11963. this.test.include(context, includeChildrenRecursively);
  11964. this.consequent.include(context, includeChildrenRecursively);
  11965. this.alternate?.include(context, includeChildrenRecursively);
  11966. }
  11967. includeUnknownTest(context) {
  11968. this.test.include(context, false);
  11969. const { brokenFlow } = context;
  11970. let consequentBrokenFlow = false;
  11971. if (this.consequent.shouldBeIncluded(context)) {
  11972. this.consequent.include(context, false, { asSingleStatement: true });
  11973. consequentBrokenFlow = context.brokenFlow;
  11974. context.brokenFlow = brokenFlow;
  11975. }
  11976. if (this.alternate?.shouldBeIncluded(context)) {
  11977. this.alternate.include(context, false, { asSingleStatement: true });
  11978. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  11979. }
  11980. }
  11981. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  11982. const hoistedVariables = [
  11983. ...new Set(hoistedDeclarations.map(identifier => {
  11984. const variable = identifier.variable;
  11985. return variable.included ? variable.getName(getPropertyAccess) : '';
  11986. }))
  11987. ]
  11988. .filter(Boolean)
  11989. .join(', ');
  11990. if (hoistedVariables) {
  11991. const parentType = this.parent.type;
  11992. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  11993. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  11994. if (needsBraces) {
  11995. code.appendLeft(this.end, ` }`);
  11996. }
  11997. }
  11998. }
  11999. shouldKeepAlternateBranch() {
  12000. let currentParent = this.parent;
  12001. do {
  12002. if (currentParent instanceof IfStatement && currentParent.alternate) {
  12003. return true;
  12004. }
  12005. if (currentParent instanceof BlockStatement) {
  12006. return false;
  12007. }
  12008. currentParent = currentParent.parent;
  12009. } while (currentParent);
  12010. return false;
  12011. }
  12012. }
  12013. IfStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12014. IfStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  12015. class ImportAttribute extends NodeBase {
  12016. }
  12017. class ImportDeclaration extends NodeBase {
  12018. // Do not bind specifiers or attributes
  12019. bind() { }
  12020. hasEffects() {
  12021. return false;
  12022. }
  12023. initialise() {
  12024. super.initialise();
  12025. this.scope.context.addImport(this);
  12026. }
  12027. render(code, _options, nodeRenderOptions) {
  12028. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  12029. }
  12030. }
  12031. ImportDeclaration.prototype.needsBoundaries = true;
  12032. ImportDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12033. ImportDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  12034. class ImportDefaultSpecifier extends NodeBase {
  12035. }
  12036. ImportDefaultSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12037. ImportDefaultSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12038. function isReassignedExportsMember(variable, exportNamesByVariable) {
  12039. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  12040. }
  12041. class VariableDeclarator extends NodeBase {
  12042. declareDeclarator(kind, isUsingDeclaration) {
  12043. this.isUsingDeclaration = isUsingDeclaration;
  12044. this.id.declare(kind, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION);
  12045. }
  12046. deoptimizePath(path) {
  12047. this.id.deoptimizePath(path);
  12048. }
  12049. hasEffects(context) {
  12050. const initEffect = this.init?.hasEffects(context);
  12051. this.id.markDeclarationReached();
  12052. return (initEffect ||
  12053. this.isUsingDeclaration ||
  12054. this.id.hasEffects(context) ||
  12055. (this.scope.context.options.treeshake
  12056. .propertyReadSideEffects &&
  12057. this.id.hasEffectsWhenDestructuring(context, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION)));
  12058. }
  12059. include(context, includeChildrenRecursively) {
  12060. const { id, init } = this;
  12061. if (!this.included)
  12062. this.includeNode();
  12063. init?.include(context, includeChildrenRecursively);
  12064. id.markDeclarationReached();
  12065. if (includeChildrenRecursively) {
  12066. id.include(context, includeChildrenRecursively);
  12067. }
  12068. else {
  12069. id.includeDestructuredIfNecessary(context, EMPTY_PATH, init || UNDEFINED_EXPRESSION);
  12070. }
  12071. }
  12072. removeAnnotations(code) {
  12073. this.init?.removeAnnotations(code);
  12074. }
  12075. render(code, options) {
  12076. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  12077. const { end, id, init, start } = this;
  12078. const renderId = id.included || this.isUsingDeclaration;
  12079. if (renderId) {
  12080. id.render(code, options);
  12081. }
  12082. else {
  12083. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  12084. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  12085. }
  12086. if (init) {
  12087. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  12088. const renderedVariable = id.variable.getName(getPropertyAccess);
  12089. if (renderedVariable !== id.name) {
  12090. code.appendLeft(init.start + 5, ` ${id.name}`);
  12091. }
  12092. }
  12093. init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  12094. }
  12095. else if (id instanceof Identifier &&
  12096. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  12097. code.appendLeft(end, `${_}=${_}void 0`);
  12098. }
  12099. }
  12100. includeNode() {
  12101. this.included = true;
  12102. const { id, init } = this;
  12103. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  12104. const { name, variable } = id;
  12105. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  12106. if (accessedVariable !== variable) {
  12107. accessedVariable.forbidName(name);
  12108. }
  12109. }
  12110. }
  12111. }
  12112. }
  12113. VariableDeclarator.prototype.applyDeoptimizations = doNotDeoptimize;
  12114. function getChunkInfoWithPath(chunk) {
  12115. return { fileName: chunk.getFileName(), ...chunk.getPreRenderedChunkInfo() };
  12116. }
  12117. class ImportExpression extends NodeBase {
  12118. constructor() {
  12119. super(...arguments);
  12120. this.inlineNamespace = null;
  12121. this.hasUnknownAccessedKey = false;
  12122. this.accessedPropKey = new Set();
  12123. this.attributes = null;
  12124. this.mechanism = null;
  12125. this.namespaceExportName = undefined;
  12126. this.resolution = null;
  12127. this.resolutionString = null;
  12128. }
  12129. get withinTopLevelAwait() {
  12130. return isFlagSet(this.flags, 134217728 /* Flag.withinTopLevelAwait */);
  12131. }
  12132. set withinTopLevelAwait(value) {
  12133. this.flags = setFlag(this.flags, 134217728 /* Flag.withinTopLevelAwait */, value);
  12134. }
  12135. // Do not bind attributes
  12136. bind() {
  12137. this.source.bind();
  12138. }
  12139. /**
  12140. * Get imported variables for deterministic usage, valid cases are:
  12141. *
  12142. * 1. `const { foo } = await import('bar')`.
  12143. * 2. `(await import('bar')).foo`
  12144. * 3. `import('bar').then(({ foo }) => {})`
  12145. *
  12146. * Returns empty array if it's side-effect only import.
  12147. * Returns undefined if it's not fully deterministic.
  12148. */
  12149. getDeterministicImportedNames() {
  12150. const parent1 = this.parent;
  12151. // Side-effect only: import('bar')
  12152. if (parent1 instanceof ExpressionStatement) {
  12153. return EMPTY_ARRAY;
  12154. }
  12155. if (parent1 instanceof AwaitExpression) {
  12156. const parent2 = parent1.parent;
  12157. // Side-effect only: await import('bar')
  12158. if (parent2 instanceof ExpressionStatement) {
  12159. return EMPTY_ARRAY;
  12160. }
  12161. // Case 1: const { foo } / module = await import('bar')
  12162. if (parent2 instanceof VariableDeclarator) {
  12163. const declaration = parent2.id;
  12164. if (declaration instanceof Identifier) {
  12165. return this.hasUnknownAccessedKey ? undefined : [...this.accessedPropKey];
  12166. }
  12167. if (declaration instanceof ObjectPattern) {
  12168. return getDeterministicObjectDestructure(declaration);
  12169. }
  12170. }
  12171. // Case 2: (await import('bar')).foo
  12172. if (parent2 instanceof MemberExpression) {
  12173. const id = parent2.property;
  12174. if (!parent2.computed && id instanceof Identifier) {
  12175. return [id.name];
  12176. }
  12177. }
  12178. return;
  12179. }
  12180. if (parent1 instanceof MemberExpression) {
  12181. const callExpression = parent1.parent;
  12182. const property = parent1.property;
  12183. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  12184. return;
  12185. }
  12186. const memberName = property.name;
  12187. // side-effect only, when only chaining .catch or .finally
  12188. if (callExpression.parent instanceof ExpressionStatement &&
  12189. ['catch', 'finally'].includes(memberName)) {
  12190. return EMPTY_ARRAY;
  12191. }
  12192. if (memberName !== 'then')
  12193. return;
  12194. // Side-effect only: import('bar').then()
  12195. if (callExpression.arguments.length === 0) {
  12196. return EMPTY_ARRAY;
  12197. }
  12198. const thenCallback = callExpression.arguments[0];
  12199. if (callExpression.arguments.length !== 1 ||
  12200. !(thenCallback instanceof ArrowFunctionExpression ||
  12201. thenCallback instanceof FunctionExpression)) {
  12202. return;
  12203. }
  12204. // Side-effect only: import('bar').then(() => {})
  12205. if (thenCallback.params.length === 0) {
  12206. return EMPTY_ARRAY;
  12207. }
  12208. const declaration = thenCallback.params[0];
  12209. if (thenCallback.params.length === 1 && declaration instanceof ObjectPattern) {
  12210. return getDeterministicObjectDestructure(declaration);
  12211. }
  12212. return this.hasUnknownAccessedKey ? undefined : [...this.accessedPropKey];
  12213. }
  12214. }
  12215. hasEffects() {
  12216. return true;
  12217. }
  12218. include(context, includeChildrenRecursively) {
  12219. if (!this.included)
  12220. this.includeNode();
  12221. this.source.include(context, includeChildrenRecursively);
  12222. }
  12223. includeNode() {
  12224. this.included = true;
  12225. this.scope.context.includeDynamicImport(this);
  12226. this.scope.addAccessedDynamicImport(this);
  12227. }
  12228. includePath(path) {
  12229. if (!this.included)
  12230. this.includeNode();
  12231. // Technically, this is not correct as dynamic imports return a Promise.
  12232. if (this.hasUnknownAccessedKey)
  12233. return;
  12234. if (path[0] === UnknownKey) {
  12235. this.hasUnknownAccessedKey = true;
  12236. }
  12237. else if (typeof path[0] === 'string') {
  12238. this.accessedPropKey.add(path[0]);
  12239. }
  12240. // Update included paths
  12241. this.scope.context.includeDynamicImport(this);
  12242. }
  12243. initialise() {
  12244. super.initialise();
  12245. this.scope.context.addDynamicImport(this);
  12246. let parent = this.parent;
  12247. let withinAwaitExpression = false;
  12248. let withinTopLevelAwait = false;
  12249. do {
  12250. if (withinAwaitExpression &&
  12251. (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)) {
  12252. withinTopLevelAwait = false;
  12253. }
  12254. if (parent instanceof AwaitExpression) {
  12255. withinAwaitExpression = true;
  12256. withinTopLevelAwait = true;
  12257. }
  12258. } while ((parent = parent.parent));
  12259. if (withinAwaitExpression && withinTopLevelAwait) {
  12260. this.withinTopLevelAwait = true;
  12261. }
  12262. }
  12263. parseNode(esTreeNode) {
  12264. this.sourceAstNode = esTreeNode.source;
  12265. return super.parseNode(esTreeNode);
  12266. }
  12267. render(code, options) {
  12268. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess }, importAttributesKey } = options;
  12269. if (this.inlineNamespace) {
  12270. const [left, right] = getDirectReturnFunction([], {
  12271. functionReturn: true,
  12272. lineBreakIndent: null,
  12273. name: null
  12274. });
  12275. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  12276. return;
  12277. }
  12278. if (this.mechanism) {
  12279. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  12280. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  12281. }
  12282. if (this.resolutionString) {
  12283. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  12284. if (this.namespaceExportName) {
  12285. const [left, right] = getDirectReturnFunction(['n'], {
  12286. functionReturn: true,
  12287. lineBreakIndent: null,
  12288. name: null
  12289. });
  12290. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  12291. }
  12292. }
  12293. else {
  12294. this.source.render(code, options);
  12295. }
  12296. if (this.attributes !== true) {
  12297. if (this.options) {
  12298. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  12299. }
  12300. if (this.attributes) {
  12301. code.appendLeft(this.end - 1, `,${_}${getObject([[importAttributesKey, this.attributes]], {
  12302. lineBreakIndent: null
  12303. })}`);
  12304. }
  12305. }
  12306. }
  12307. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, attributes, ownChunk, targetChunk) {
  12308. const { format } = options;
  12309. this.inlineNamespace = null;
  12310. this.resolution = resolution;
  12311. this.resolutionString = resolutionString;
  12312. this.namespaceExportName = namespaceExportName;
  12313. this.attributes = attributes;
  12314. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  12315. let helper;
  12316. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver, ownChunk, targetChunk));
  12317. if (helper) {
  12318. accessedGlobals.push(helper);
  12319. }
  12320. if (accessedGlobals.length > 0) {
  12321. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  12322. }
  12323. }
  12324. setInternalResolution(inlineNamespace) {
  12325. this.inlineNamespace = inlineNamespace;
  12326. }
  12327. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver, ownChunk, targetChunk) {
  12328. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  12329. {
  12330. chunk: getChunkInfoWithPath(ownChunk),
  12331. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  12332. format,
  12333. getTargetChunkImports() {
  12334. if (targetChunk === null)
  12335. return null;
  12336. const chunkInfos = [];
  12337. const importerPath = ownChunk.getFileName();
  12338. for (const dep of targetChunk.dependencies) {
  12339. const resolvedImportPath = `'${dep.getImportPath(importerPath)}'`;
  12340. if (dep instanceof ExternalChunk) {
  12341. chunkInfos.push({
  12342. fileName: dep.getFileName(),
  12343. resolvedImportPath,
  12344. type: 'external'
  12345. });
  12346. }
  12347. else {
  12348. chunkInfos.push({
  12349. chunk: dep.getPreRenderedChunkInfo(),
  12350. fileName: dep.getFileName(),
  12351. resolvedImportPath,
  12352. type: 'internal'
  12353. });
  12354. }
  12355. }
  12356. return chunkInfos;
  12357. },
  12358. moduleId: this.scope.context.module.id,
  12359. targetChunk: targetChunk ? getChunkInfoWithPath(targetChunk) : null,
  12360. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  12361. }
  12362. ]);
  12363. if (mechanism) {
  12364. return { helper: null, mechanism };
  12365. }
  12366. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  12367. switch (format) {
  12368. case 'cjs': {
  12369. if (dynamicImportInCjs &&
  12370. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  12371. return { helper: null, mechanism: null };
  12372. }
  12373. const helper = getInteropHelper(resolution, exportMode, interop);
  12374. let left = `require(`;
  12375. let right = `)`;
  12376. if (helper) {
  12377. left = `/*#__PURE__*/${helper}(${left}`;
  12378. right += ')';
  12379. }
  12380. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  12381. functionReturn: true,
  12382. lineBreakIndent: null,
  12383. name: null
  12384. });
  12385. left = `Promise.resolve().then(${functionLeft}${left}`;
  12386. right += `${functionRight})`;
  12387. if (!arrowFunctions && hasDynamicTarget) {
  12388. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12389. needsArrowReturnParens: false,
  12390. needsWrappedFunction: true
  12391. });
  12392. right = ')';
  12393. }
  12394. return {
  12395. helper,
  12396. mechanism: { left, right }
  12397. };
  12398. }
  12399. case 'amd': {
  12400. const resolve = compact ? 'c' : 'resolve';
  12401. const reject = compact ? 'e' : 'reject';
  12402. const helper = getInteropHelper(resolution, exportMode, interop);
  12403. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  12404. functionReturn: false,
  12405. lineBreakIndent: null,
  12406. name: null
  12407. });
  12408. const resolveNamespace = helper
  12409. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  12410. : resolve;
  12411. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  12412. functionReturn: false,
  12413. lineBreakIndent: null,
  12414. name: null
  12415. });
  12416. let left = `new Promise(${handlerLeft}require([`;
  12417. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  12418. if (!arrowFunctions && hasDynamicTarget) {
  12419. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12420. needsArrowReturnParens: false,
  12421. needsWrappedFunction: true
  12422. });
  12423. right = ')';
  12424. }
  12425. return {
  12426. helper,
  12427. mechanism: { left, right }
  12428. };
  12429. }
  12430. case 'system': {
  12431. return {
  12432. helper: null,
  12433. mechanism: {
  12434. left: 'module.import(',
  12435. right: ')'
  12436. }
  12437. };
  12438. }
  12439. }
  12440. return { helper: null, mechanism: null };
  12441. }
  12442. }
  12443. ImportExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  12444. function getInteropHelper(resolution, exportMode, interop) {
  12445. return exportMode === 'external'
  12446. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  12447. : exportMode === 'default'
  12448. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  12449. : null;
  12450. }
  12451. const accessedImportGlobals = {
  12452. amd: ['require'],
  12453. cjs: ['require'],
  12454. system: ['module']
  12455. };
  12456. function getDeterministicObjectDestructure(objectPattern) {
  12457. const variables = [];
  12458. for (const property of objectPattern.properties) {
  12459. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  12460. return;
  12461. variables.push(property.key.name);
  12462. }
  12463. return variables;
  12464. }
  12465. class ImportNamespaceSpecifier extends NodeBase {
  12466. }
  12467. ImportNamespaceSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12468. ImportNamespaceSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12469. class ImportSpecifier extends NodeBase {
  12470. }
  12471. ImportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12472. ImportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12473. class JSXIdentifier extends IdentifierBase {
  12474. constructor() {
  12475. super(...arguments);
  12476. this.isNativeElement = false;
  12477. }
  12478. bind() {
  12479. const type = this.getType();
  12480. if (type === 0 /* IdentifierType.Reference */) {
  12481. this.variable = this.scope.findVariable(this.name);
  12482. this.variable.addReference(this);
  12483. }
  12484. else if (type === 1 /* IdentifierType.NativeElementName */) {
  12485. this.isNativeElement = true;
  12486. }
  12487. }
  12488. include(context) {
  12489. if (!this.included)
  12490. this.includeNode(context);
  12491. }
  12492. includeNode(context) {
  12493. this.included = true;
  12494. if (!this.deoptimized)
  12495. this.applyDeoptimizations();
  12496. if (this.variable !== null) {
  12497. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  12498. }
  12499. }
  12500. includePath(path, context) {
  12501. if (!this.included) {
  12502. this.included = true;
  12503. if (this.variable !== null) {
  12504. this.scope.context.includeVariableInModule(this.variable, path, context);
  12505. }
  12506. }
  12507. else if (path.length > 0) {
  12508. this.variable?.includePath(path, context);
  12509. }
  12510. }
  12511. render(code, { snippets: { getPropertyAccess }, useOriginalName }) {
  12512. if (this.variable) {
  12513. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  12514. if (name !== this.name) {
  12515. code.overwrite(this.start, this.end, name, {
  12516. contentOnly: true,
  12517. storeName: true
  12518. });
  12519. }
  12520. }
  12521. else if (this.isNativeElement &&
  12522. this.scope.context.options.jsx.mode !== 'preserve') {
  12523. code.update(this.start, this.end, JSON.stringify(this.name));
  12524. }
  12525. }
  12526. getType() {
  12527. switch (this.parent.type) {
  12528. case 'JSXOpeningElement':
  12529. case 'JSXClosingElement': {
  12530. return this.name.startsWith(this.name.charAt(0).toUpperCase())
  12531. ? 0 /* IdentifierType.Reference */
  12532. : 1 /* IdentifierType.NativeElementName */;
  12533. }
  12534. case 'JSXMemberExpression': {
  12535. return this.parent.object === this
  12536. ? 0 /* IdentifierType.Reference */
  12537. : 2 /* IdentifierType.Other */;
  12538. }
  12539. case 'JSXAttribute':
  12540. case 'JSXNamespacedName': {
  12541. return 2 /* IdentifierType.Other */;
  12542. }
  12543. default: {
  12544. /* istanbul ignore next */
  12545. throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
  12546. }
  12547. }
  12548. }
  12549. }
  12550. class JSXAttribute extends NodeBase {
  12551. render(code, options, { jsxMode } = BLANK) {
  12552. super.render(code, options);
  12553. if (['classic', 'automatic'].includes(jsxMode)) {
  12554. const { name, value } = this;
  12555. const key = name instanceof JSXIdentifier ? name.name : `${name.namespace.name}:${name.name.name}`;
  12556. if (!(jsxMode === 'automatic' && key === 'key')) {
  12557. const safeKey = stringifyObjectKeyIfNeeded(key);
  12558. if (key !== safeKey) {
  12559. code.overwrite(name.start, name.end, safeKey, { contentOnly: true });
  12560. }
  12561. if (value) {
  12562. code.overwrite(name.end, value.start, ': ', { contentOnly: true });
  12563. }
  12564. else {
  12565. code.appendLeft(name.end, ': true');
  12566. }
  12567. }
  12568. }
  12569. }
  12570. }
  12571. JSXAttribute.prototype.includeNode = onlyIncludeSelf;
  12572. class JSXClosingBase extends NodeBase {
  12573. render(code, options) {
  12574. const { mode } = this.scope.context.options.jsx;
  12575. if (mode !== 'preserve') {
  12576. code.overwrite(this.start, this.end, ')', { contentOnly: true });
  12577. }
  12578. else {
  12579. super.render(code, options);
  12580. }
  12581. }
  12582. }
  12583. JSXClosingBase.prototype.includeNode = onlyIncludeSelf;
  12584. class JSXClosingElement extends JSXClosingBase {
  12585. }
  12586. class JSXClosingFragment extends JSXClosingBase {
  12587. }
  12588. class JSXSpreadAttribute extends NodeBase {
  12589. render(code, options) {
  12590. this.argument.render(code, options);
  12591. const { mode } = this.scope.context.options.jsx;
  12592. if (mode !== 'preserve') {
  12593. code.overwrite(this.start, this.argument.start, '', { contentOnly: true });
  12594. code.overwrite(this.argument.end, this.end, '', { contentOnly: true });
  12595. }
  12596. }
  12597. }
  12598. class JSXEmptyExpression extends NodeBase {
  12599. }
  12600. JSXEmptyExpression.prototype.includeNode = onlyIncludeSelf;
  12601. class JSXExpressionContainer extends NodeBase {
  12602. includeNode(context) {
  12603. this.included = true;
  12604. if (!this.deoptimized)
  12605. this.applyDeoptimizations();
  12606. this.expression.includePath(UNKNOWN_PATH, context);
  12607. }
  12608. render(code, options) {
  12609. const { mode } = this.scope.context.options.jsx;
  12610. if (mode !== 'preserve') {
  12611. code.remove(this.start, this.expression.start);
  12612. code.remove(this.expression.end, this.end);
  12613. }
  12614. this.expression.render(code, options);
  12615. }
  12616. }
  12617. function getRenderedJsxChildren(children) {
  12618. let renderedChildren = 0;
  12619. for (const child of children) {
  12620. if (!(child instanceof JSXExpressionContainer && child.expression instanceof JSXEmptyExpression)) {
  12621. renderedChildren++;
  12622. }
  12623. }
  12624. return renderedChildren;
  12625. }
  12626. function getAndIncludeFactoryVariable(factory, preserve, importSource, node, context) {
  12627. const [baseName, nestedName] = factory.split('.');
  12628. let factoryVariable;
  12629. if (importSource) {
  12630. factoryVariable = node.scope.context.getImportedJsxFactoryVariable(nestedName ? 'default' : baseName, node.start, importSource);
  12631. if (preserve) {
  12632. // This pretends we are accessing an included global variable of the same name
  12633. const globalVariable = node.scope.findGlobal(baseName);
  12634. globalVariable.includePath(UNKNOWN_PATH, context);
  12635. // This excludes this variable from renaming
  12636. factoryVariable.globalName = baseName;
  12637. }
  12638. }
  12639. else {
  12640. factoryVariable = node.scope.findGlobal(baseName);
  12641. }
  12642. node.scope.context.includeVariableInModule(factoryVariable, UNKNOWN_PATH, context);
  12643. if (factoryVariable instanceof LocalVariable) {
  12644. factoryVariable.consolidateInitializers();
  12645. factoryVariable.addUsedPlace(node);
  12646. node.scope.context.requestTreeshakingPass();
  12647. }
  12648. return factoryVariable;
  12649. }
  12650. class JSXElementBase extends NodeBase {
  12651. constructor() {
  12652. super(...arguments);
  12653. this.factoryVariable = null;
  12654. this.factory = null;
  12655. }
  12656. initialise() {
  12657. super.initialise();
  12658. const { importSource } = (this.jsxMode = this.getRenderingMode());
  12659. if (importSource) {
  12660. this.scope.context.addImportSource(importSource);
  12661. }
  12662. }
  12663. include(context, includeChildrenRecursively) {
  12664. if (!this.included)
  12665. this.includeNode(context);
  12666. for (const child of this.children) {
  12667. child.include(context, includeChildrenRecursively);
  12668. }
  12669. }
  12670. includeNode(context) {
  12671. this.included = true;
  12672. const { factory, importSource, mode } = this.jsxMode;
  12673. if (factory) {
  12674. this.factory = factory;
  12675. this.factoryVariable = getAndIncludeFactoryVariable(factory, mode === 'preserve', importSource, this, context);
  12676. }
  12677. }
  12678. getRenderingMode() {
  12679. const jsx = this.scope.context.options.jsx;
  12680. const { mode, factory, importSource } = jsx;
  12681. if (mode === 'automatic') {
  12682. return {
  12683. factory: getRenderedJsxChildren(this.children) > 1 ? 'jsxs' : 'jsx',
  12684. importSource: jsx.jsxImportSource,
  12685. mode
  12686. };
  12687. }
  12688. return { factory, importSource, mode };
  12689. }
  12690. renderChildren(code, options, openingEnd) {
  12691. const { children } = this;
  12692. let hasMultipleChildren = false;
  12693. let childrenEnd = openingEnd;
  12694. let firstChild = null;
  12695. for (const child of children) {
  12696. if (child instanceof JSXExpressionContainer &&
  12697. child.expression instanceof JSXEmptyExpression) {
  12698. code.remove(childrenEnd, child.end);
  12699. }
  12700. else {
  12701. code.appendLeft(childrenEnd, ', ');
  12702. child.render(code, options);
  12703. if (firstChild) {
  12704. hasMultipleChildren = true;
  12705. }
  12706. else {
  12707. firstChild = child;
  12708. }
  12709. }
  12710. childrenEnd = child.end;
  12711. }
  12712. return { childrenEnd, firstChild, hasMultipleChildren };
  12713. }
  12714. }
  12715. JSXElementBase.prototype.applyDeoptimizations = doNotDeoptimize;
  12716. class JSXElement extends JSXElementBase {
  12717. include(context, includeChildrenRecursively) {
  12718. super.include(context, includeChildrenRecursively);
  12719. this.openingElement.include(context, includeChildrenRecursively);
  12720. this.closingElement?.include(context, includeChildrenRecursively);
  12721. }
  12722. render(code, options) {
  12723. switch (this.jsxMode.mode) {
  12724. case 'classic': {
  12725. this.renderClassicMode(code, options);
  12726. break;
  12727. }
  12728. case 'automatic': {
  12729. this.renderAutomaticMode(code, options);
  12730. break;
  12731. }
  12732. default: {
  12733. super.render(code, options);
  12734. }
  12735. }
  12736. }
  12737. getRenderingMode() {
  12738. const jsx = this.scope.context.options.jsx;
  12739. const { mode, factory, importSource } = jsx;
  12740. if (mode === 'automatic') {
  12741. // In the case there is a key after a spread attribute, we fall back to
  12742. // classic mode, see https://github.com/facebook/react/issues/20031#issuecomment-710346866
  12743. // for reasoning.
  12744. let hasSpread = false;
  12745. for (const attribute of this.openingElement.attributes) {
  12746. if (attribute instanceof JSXSpreadAttribute) {
  12747. hasSpread = true;
  12748. }
  12749. else if (hasSpread && attribute.name.name === 'key') {
  12750. return { factory, importSource, mode: 'classic' };
  12751. }
  12752. }
  12753. }
  12754. return super.getRenderingMode();
  12755. }
  12756. renderClassicMode(code, options) {
  12757. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12758. const { closingElement, end, factory, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  12759. const [, ...nestedName] = factory.split('.');
  12760. const { firstAttribute, hasAttributes, hasSpread, inObject, previousEnd } = this.renderAttributes(code, options, [factoryVariable.getName(getPropertyAccess, useOriginalName), ...nestedName].join('.'), false);
  12761. this.wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, 'null', previousEnd);
  12762. this.renderChildren(code, options, openingEnd);
  12763. if (selfClosing) {
  12764. code.appendLeft(end, ')');
  12765. }
  12766. else {
  12767. closingElement.render(code, options);
  12768. }
  12769. }
  12770. renderAutomaticMode(code, options) {
  12771. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12772. const { closingElement, end, factoryVariable, openingElement: { end: openindEnd, selfClosing } } = this;
  12773. let { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd } = this.renderAttributes(code, options, factoryVariable.getName(getPropertyAccess, useOriginalName), true);
  12774. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openindEnd);
  12775. if (firstChild) {
  12776. code.prependRight(firstChild.start, `children: ${hasMultipleChildren ? '[' : ''}`);
  12777. if (!inObject) {
  12778. code.prependRight(firstChild.start, '{ ');
  12779. inObject = true;
  12780. }
  12781. previousEnd = closingElement.start;
  12782. if (hasMultipleChildren) {
  12783. code.appendLeft(previousEnd, ']');
  12784. }
  12785. }
  12786. this.wrapAttributes(code, inObject, hasAttributes || !!firstChild, hasSpread, firstAttribute || firstChild, '{}', childrenEnd);
  12787. if (keyAttribute) {
  12788. const { value } = keyAttribute;
  12789. // This will appear to the left of the moved code...
  12790. code.appendLeft(childrenEnd, ', ');
  12791. if (value) {
  12792. code.move(value.start, value.end, childrenEnd);
  12793. }
  12794. else {
  12795. code.appendLeft(childrenEnd, 'true');
  12796. }
  12797. }
  12798. if (selfClosing) {
  12799. // Moving the key attribute will also move the parenthesis to the right position
  12800. code.appendLeft(keyAttribute?.value?.end || end, ')');
  12801. }
  12802. else {
  12803. closingElement.render(code, options);
  12804. }
  12805. }
  12806. renderAttributes(code, options, factoryName, extractKeyAttribute) {
  12807. const { jsxMode: { mode }, openingElement } = this;
  12808. const { attributes, end: openingEnd, start: openingStart, name: { start: nameStart, end: nameEnd } } = openingElement;
  12809. code.update(openingStart, nameStart, `/*#__PURE__*/${factoryName}(`);
  12810. openingElement.render(code, options, { jsxMode: mode });
  12811. let keyAttribute = null;
  12812. let hasSpread = false;
  12813. let inObject = false;
  12814. let previousEnd = nameEnd;
  12815. let hasAttributes = false;
  12816. let firstAttribute = null;
  12817. for (const attribute of attributes) {
  12818. if (attribute instanceof JSXAttribute) {
  12819. if (extractKeyAttribute && attribute.name.name === 'key') {
  12820. keyAttribute = attribute;
  12821. code.remove(previousEnd, attribute.value?.start || attribute.end);
  12822. continue;
  12823. }
  12824. code.appendLeft(previousEnd, ',');
  12825. if (!inObject) {
  12826. code.prependRight(attribute.start, '{ ');
  12827. inObject = true;
  12828. }
  12829. hasAttributes = true;
  12830. }
  12831. else {
  12832. if (inObject) {
  12833. if (hasAttributes) {
  12834. code.appendLeft(previousEnd, ' ');
  12835. }
  12836. code.appendLeft(previousEnd, '},');
  12837. inObject = false;
  12838. }
  12839. else {
  12840. code.appendLeft(previousEnd, ',');
  12841. }
  12842. hasSpread = true;
  12843. }
  12844. previousEnd = attribute.end;
  12845. if (!firstAttribute) {
  12846. firstAttribute = attribute;
  12847. }
  12848. }
  12849. code.remove(attributes.at(-1)?.end || previousEnd, openingEnd);
  12850. return { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd };
  12851. }
  12852. wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, missingAttributesFallback, attributesEnd) {
  12853. if (inObject) {
  12854. code.appendLeft(attributesEnd, ' }');
  12855. }
  12856. if (hasSpread) {
  12857. if (hasAttributes) {
  12858. const { start } = firstAttribute;
  12859. if (firstAttribute instanceof JSXSpreadAttribute) {
  12860. code.prependRight(start, '{}, ');
  12861. }
  12862. code.prependRight(start, 'Object.assign(');
  12863. code.appendLeft(attributesEnd, ')');
  12864. }
  12865. }
  12866. else if (!hasAttributes) {
  12867. code.appendLeft(attributesEnd, `, ${missingAttributesFallback}`);
  12868. }
  12869. }
  12870. }
  12871. class JSXFragment extends JSXElementBase {
  12872. include(context, includeChildrenRecursively) {
  12873. super.include(context, includeChildrenRecursively);
  12874. this.openingFragment.include(context, includeChildrenRecursively);
  12875. this.closingFragment.include(context, includeChildrenRecursively);
  12876. }
  12877. render(code, options) {
  12878. switch (this.jsxMode.mode) {
  12879. case 'classic': {
  12880. this.renderClassicMode(code, options);
  12881. break;
  12882. }
  12883. case 'automatic': {
  12884. this.renderAutomaticMode(code, options);
  12885. break;
  12886. }
  12887. default: {
  12888. super.render(code, options);
  12889. }
  12890. }
  12891. }
  12892. renderClassicMode(code, options) {
  12893. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12894. const { closingFragment, factory, factoryVariable, openingFragment, start } = this;
  12895. const [, ...nestedName] = factory.split('.');
  12896. openingFragment.render(code, options);
  12897. code.prependRight(start, `/*#__PURE__*/${[
  12898. factoryVariable.getName(getPropertyAccess, useOriginalName),
  12899. ...nestedName
  12900. ].join('.')}(`);
  12901. code.appendLeft(openingFragment.end, ', null');
  12902. this.renderChildren(code, options, openingFragment.end);
  12903. closingFragment.render(code, options);
  12904. }
  12905. renderAutomaticMode(code, options) {
  12906. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12907. const { closingFragment, factoryVariable, openingFragment, start } = this;
  12908. openingFragment.render(code, options);
  12909. code.prependRight(start, `/*#__PURE__*/${factoryVariable.getName(getPropertyAccess, useOriginalName)}(`);
  12910. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingFragment.end);
  12911. if (firstChild) {
  12912. code.prependRight(firstChild.start, `{ children: ${hasMultipleChildren ? '[' : ''}`);
  12913. if (hasMultipleChildren) {
  12914. code.appendLeft(closingFragment.start, ']');
  12915. }
  12916. code.appendLeft(childrenEnd, ' }');
  12917. }
  12918. else {
  12919. code.appendLeft(openingFragment.end, ', {}');
  12920. }
  12921. closingFragment.render(code, options);
  12922. }
  12923. }
  12924. class JSXMemberExpression extends NodeBase {
  12925. includeNode(context) {
  12926. this.included = true;
  12927. if (!this.deoptimized)
  12928. this.applyDeoptimizations();
  12929. this.object.includePath([this.property.name], context);
  12930. }
  12931. includePath(path, context) {
  12932. if (!this.included)
  12933. this.includeNode(context);
  12934. this.object.includePath([this.property.name, ...path], context);
  12935. }
  12936. }
  12937. class JSXNamespacedName extends NodeBase {
  12938. }
  12939. JSXNamespacedName.prototype.includeNode = onlyIncludeSelf;
  12940. class JSXOpeningElement extends NodeBase {
  12941. render(code, options, { jsxMode = this.scope.context.options.jsx.mode } = {}) {
  12942. this.name.render(code, options);
  12943. for (const attribute of this.attributes) {
  12944. attribute.render(code, options, { jsxMode });
  12945. }
  12946. }
  12947. }
  12948. JSXOpeningElement.prototype.includeNode = onlyIncludeSelf;
  12949. class JSXOpeningFragment extends NodeBase {
  12950. constructor() {
  12951. super(...arguments);
  12952. this.fragment = null;
  12953. this.fragmentVariable = null;
  12954. }
  12955. includeNode(context) {
  12956. this.included = true;
  12957. if (!this.deoptimized)
  12958. this.applyDeoptimizations();
  12959. const jsx = this.scope.context.options.jsx;
  12960. if (jsx.mode === 'automatic') {
  12961. this.fragment = 'Fragment';
  12962. this.fragmentVariable = getAndIncludeFactoryVariable('Fragment', false, jsx.jsxImportSource, this, context);
  12963. }
  12964. else {
  12965. const { fragment, importSource, mode } = jsx;
  12966. if (fragment != null) {
  12967. this.fragment = fragment;
  12968. this.fragmentVariable = getAndIncludeFactoryVariable(fragment, mode === 'preserve', importSource, this, context);
  12969. }
  12970. }
  12971. }
  12972. render(code, options) {
  12973. const { mode } = this.scope.context.options.jsx;
  12974. if (mode !== 'preserve') {
  12975. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12976. const [, ...nestedFragment] = this.fragment.split('.');
  12977. const fragment = [
  12978. this.fragmentVariable.getName(getPropertyAccess, useOriginalName),
  12979. ...nestedFragment
  12980. ].join('.');
  12981. code.update(this.start, this.end, fragment);
  12982. }
  12983. }
  12984. }
  12985. class JSXSpreadChild extends NodeBase {
  12986. render(code, options) {
  12987. super.render(code, options);
  12988. const { mode } = this.scope.context.options.jsx;
  12989. if (mode !== 'preserve') {
  12990. code.overwrite(this.start, this.expression.start, '...', { contentOnly: true });
  12991. code.overwrite(this.expression.end, this.end, '', { contentOnly: true });
  12992. }
  12993. }
  12994. }
  12995. class JSXText extends NodeBase {
  12996. render(code) {
  12997. const { mode } = this.scope.context.options.jsx;
  12998. if (mode !== 'preserve') {
  12999. code.overwrite(this.start, this.end, JSON.stringify(this.value), {
  13000. contentOnly: true
  13001. });
  13002. }
  13003. }
  13004. }
  13005. JSXText.prototype.includeNode = onlyIncludeSelf;
  13006. class LabeledStatement extends NodeBase {
  13007. hasEffects(context) {
  13008. const { brokenFlow, includedLabels } = context;
  13009. context.ignore.labels.add(this.label.name);
  13010. context.includedLabels = new Set();
  13011. let bodyHasEffects = false;
  13012. if (this.body.hasEffects(context)) {
  13013. bodyHasEffects = true;
  13014. }
  13015. else {
  13016. context.ignore.labels.delete(this.label.name);
  13017. if (context.includedLabels.has(this.label.name)) {
  13018. context.includedLabels.delete(this.label.name);
  13019. context.brokenFlow = brokenFlow;
  13020. }
  13021. }
  13022. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  13023. return bodyHasEffects;
  13024. }
  13025. include(context, includeChildrenRecursively) {
  13026. if (!this.included)
  13027. this.includeNode(context);
  13028. const { brokenFlow, includedLabels } = context;
  13029. context.includedLabels = new Set();
  13030. this.body.include(context, includeChildrenRecursively);
  13031. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  13032. this.label.include(context, includeChildrenRecursively);
  13033. context.includedLabels.delete(this.label.name);
  13034. context.brokenFlow = brokenFlow;
  13035. }
  13036. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  13037. }
  13038. includeNode(context) {
  13039. this.included = true;
  13040. this.body.includePath(UNKNOWN_PATH, context);
  13041. }
  13042. render(code, options) {
  13043. if (this.label.included) {
  13044. this.label.render(code, options);
  13045. }
  13046. else {
  13047. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  13048. }
  13049. this.body.render(code, options);
  13050. }
  13051. }
  13052. LabeledStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13053. class LogicalExpression extends NodeBase {
  13054. constructor() {
  13055. super(...arguments);
  13056. // We collect deoptimization information if usedBranch !== null
  13057. this.expressionsToBeDeoptimized = [];
  13058. this.usedBranch = null;
  13059. }
  13060. //private isBranchResolutionAnalysed = false;
  13061. get isBranchResolutionAnalysed() {
  13062. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  13063. }
  13064. set isBranchResolutionAnalysed(value) {
  13065. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  13066. }
  13067. get hasDeoptimizedCache() {
  13068. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  13069. }
  13070. set hasDeoptimizedCache(value) {
  13071. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  13072. }
  13073. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13074. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13075. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13076. }
  13077. deoptimizeCache() {
  13078. if (this.hasDeoptimizedCache)
  13079. return;
  13080. this.hasDeoptimizedCache = true;
  13081. if (this.usedBranch) {
  13082. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  13083. this.usedBranch = null;
  13084. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  13085. if (this.included) {
  13086. // As we are not tracking inclusions, we just include everything
  13087. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  13088. }
  13089. }
  13090. const { scope: { context }, expressionsToBeDeoptimized } = this;
  13091. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  13092. for (const expression of expressionsToBeDeoptimized) {
  13093. expression.deoptimizeCache();
  13094. }
  13095. // Request another pass because we need to ensure "include" runs again if
  13096. // it is rendered
  13097. context.requestTreeshakingPass();
  13098. }
  13099. deoptimizePath(path) {
  13100. const usedBranch = this.getUsedBranch();
  13101. if (usedBranch) {
  13102. usedBranch.deoptimizePath(path);
  13103. }
  13104. else {
  13105. this.left.deoptimizePath(path);
  13106. this.right.deoptimizePath(path);
  13107. }
  13108. }
  13109. getLiteralValueAtPath(path, recursionTracker, origin) {
  13110. if (origin === this)
  13111. return UnknownValue;
  13112. const usedBranch = this.getUsedBranch();
  13113. if (usedBranch) {
  13114. this.expressionsToBeDeoptimized.push(origin);
  13115. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  13116. }
  13117. else if (!this.hasDeoptimizedCache && !path.length) {
  13118. const rightValue = this.right.getLiteralValueAtPath(path, recursionTracker, origin);
  13119. const booleanOrUnknown = tryCastLiteralValueToBoolean(rightValue);
  13120. if (typeof booleanOrUnknown !== 'symbol') {
  13121. if (!booleanOrUnknown && this.operator === '&&') {
  13122. this.expressionsToBeDeoptimized.push(origin);
  13123. return UnknownFalsyValue;
  13124. }
  13125. if (booleanOrUnknown && this.operator === '||') {
  13126. this.expressionsToBeDeoptimized.push(origin);
  13127. return UnknownTruthyValue;
  13128. }
  13129. }
  13130. }
  13131. return UnknownValue;
  13132. }
  13133. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13134. const usedBranch = this.getUsedBranch();
  13135. if (usedBranch) {
  13136. this.expressionsToBeDeoptimized.push(origin);
  13137. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13138. }
  13139. return [
  13140. new MultiExpression([
  13141. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  13142. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  13143. ]),
  13144. false
  13145. ];
  13146. }
  13147. hasEffects(context) {
  13148. if (this.left.hasEffects(context)) {
  13149. return true;
  13150. }
  13151. if (this.getUsedBranch() !== this.left) {
  13152. return this.right.hasEffects(context);
  13153. }
  13154. return false;
  13155. }
  13156. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13157. const usedBranch = this.getUsedBranch();
  13158. if (usedBranch) {
  13159. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  13160. }
  13161. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  13162. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  13163. }
  13164. include(context, includeChildrenRecursively) {
  13165. this.included = true;
  13166. const usedBranch = this.getUsedBranch();
  13167. if (includeChildrenRecursively ||
  13168. !usedBranch ||
  13169. (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  13170. this.left.include(context, includeChildrenRecursively);
  13171. this.right.include(context, includeChildrenRecursively);
  13172. }
  13173. else {
  13174. usedBranch.include(context, includeChildrenRecursively);
  13175. }
  13176. }
  13177. includePath(path, context) {
  13178. this.included = true;
  13179. const usedBranch = this.getUsedBranch();
  13180. if (!usedBranch || (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  13181. this.left.includePath(path, context);
  13182. this.right.includePath(path, context);
  13183. }
  13184. else {
  13185. usedBranch.includePath(path, context);
  13186. }
  13187. }
  13188. removeAnnotations(code) {
  13189. this.left.removeAnnotations(code);
  13190. }
  13191. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  13192. if (!this.left.included || !this.right.included) {
  13193. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  13194. if (this.right.included) {
  13195. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  13196. code.remove(this.start, removePos);
  13197. if (preventASI) {
  13198. removeLineBreaks(code, removePos, this.right.start);
  13199. }
  13200. this.left.removeAnnotations(code);
  13201. }
  13202. else {
  13203. code.remove(findLastWhiteSpaceReverse(code.original, this.left.end, operatorPos), this.end);
  13204. }
  13205. this.getUsedBranch().render(code, options, {
  13206. isCalleeOfRenderedParent,
  13207. preventASI,
  13208. renderedParentType: renderedParentType || this.parent.type,
  13209. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  13210. });
  13211. }
  13212. else {
  13213. this.left.render(code, options, {
  13214. preventASI,
  13215. renderedSurroundingElement
  13216. });
  13217. this.right.render(code, options);
  13218. }
  13219. }
  13220. getUsedBranch() {
  13221. if (!this.isBranchResolutionAnalysed) {
  13222. this.isBranchResolutionAnalysed = true;
  13223. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  13224. const booleanOrUnknown = tryCastLiteralValueToBoolean(leftValue);
  13225. if (typeof booleanOrUnknown === 'symbol') {
  13226. return null;
  13227. }
  13228. else {
  13229. this.usedBranch =
  13230. (this.operator === '||' && booleanOrUnknown) ||
  13231. (this.operator === '&&' && !booleanOrUnknown) ||
  13232. (this.operator === '??' && leftValue != null)
  13233. ? this.left
  13234. : this.right;
  13235. }
  13236. }
  13237. return this.usedBranch;
  13238. }
  13239. }
  13240. LogicalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13241. LogicalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13242. class NewExpression extends NodeBase {
  13243. hasEffects(context) {
  13244. if (!this.deoptimized)
  13245. this.applyDeoptimizations();
  13246. for (const argument of this.arguments) {
  13247. if (argument.hasEffects(context))
  13248. return true;
  13249. }
  13250. if (this.annotationPure) {
  13251. return false;
  13252. }
  13253. return (this.callee.hasEffects(context) ||
  13254. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  13255. }
  13256. hasEffectsOnInteractionAtPath(path, { type }) {
  13257. return path.length > 0 || type !== INTERACTION_ACCESSED;
  13258. }
  13259. include(context, includeChildrenRecursively) {
  13260. if (!this.included)
  13261. this.includeNode(context);
  13262. if (includeChildrenRecursively) {
  13263. super.include(context, true);
  13264. }
  13265. else {
  13266. this.callee.include(context, false);
  13267. this.callee.includeCallArguments(this.interaction, context);
  13268. }
  13269. }
  13270. includeNode(context) {
  13271. this.included = true;
  13272. if (!this.deoptimized)
  13273. this.applyDeoptimizations();
  13274. this.callee.includePath(UNKNOWN_PATH, context);
  13275. }
  13276. initialise() {
  13277. super.initialise();
  13278. this.interaction = {
  13279. args: [null, ...this.arguments],
  13280. type: INTERACTION_CALLED,
  13281. withNew: true
  13282. };
  13283. if (this.annotations &&
  13284. this.scope.context.options.treeshake.annotations) {
  13285. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  13286. }
  13287. }
  13288. render(code, options) {
  13289. this.callee.render(code, options);
  13290. renderCallArguments(code, options, this);
  13291. }
  13292. applyDeoptimizations() {
  13293. this.deoptimized = true;
  13294. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  13295. this.scope.context.requestTreeshakingPass();
  13296. }
  13297. }
  13298. class ObjectExpression extends NodeBase {
  13299. constructor() {
  13300. super(...arguments);
  13301. this.objectEntity = null;
  13302. this.protoProp = null;
  13303. }
  13304. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13305. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13306. }
  13307. deoptimizeCache() {
  13308. this.getObjectEntity().deoptimizeAllProperties();
  13309. }
  13310. deoptimizePath(path) {
  13311. this.getObjectEntity().deoptimizePath(path);
  13312. }
  13313. getLiteralValueAtPath(path, recursionTracker, origin) {
  13314. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  13315. }
  13316. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13317. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13318. }
  13319. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13320. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  13321. }
  13322. include(context, includeChildrenRecursively) {
  13323. if (!this.included)
  13324. this.includeNode(context);
  13325. this.getObjectEntity().include(context, includeChildrenRecursively);
  13326. this.protoProp?.include(context, includeChildrenRecursively);
  13327. }
  13328. includeNode(context) {
  13329. this.included = true;
  13330. this.protoProp?.includePath(UNKNOWN_PATH, context);
  13331. }
  13332. includePath(path, context) {
  13333. if (!this.included)
  13334. this.includeNode(context);
  13335. this.getObjectEntity().includePath(path, context);
  13336. }
  13337. render(code, options, { renderedSurroundingElement } = BLANK) {
  13338. if (renderedSurroundingElement === ExpressionStatement$1 ||
  13339. renderedSurroundingElement === ArrowFunctionExpression$1) {
  13340. code.appendRight(this.start, '(');
  13341. code.prependLeft(this.end, ')');
  13342. }
  13343. if (this.properties.length > 0) {
  13344. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  13345. let lastSeparatorPos = null;
  13346. for (const { node, separator, start, end } of separatedNodes) {
  13347. if (!node.included) {
  13348. treeshakeNode(node, code, start, end);
  13349. continue;
  13350. }
  13351. lastSeparatorPos = separator;
  13352. node.render(code, options);
  13353. }
  13354. if (lastSeparatorPos) {
  13355. code.remove(lastSeparatorPos, this.end - 1);
  13356. }
  13357. }
  13358. }
  13359. getObjectEntity() {
  13360. if (this.objectEntity !== null) {
  13361. return this.objectEntity;
  13362. }
  13363. let prototype = OBJECT_PROTOTYPE;
  13364. const properties = [];
  13365. for (const property of this.properties) {
  13366. if (property instanceof SpreadElement) {
  13367. properties.push({ key: UnknownKey, kind: 'init', property });
  13368. continue;
  13369. }
  13370. let key;
  13371. if (property.computed) {
  13372. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  13373. if (typeof keyValue === 'symbol') {
  13374. properties.push({ key: UnknownKey, kind: property.kind, property });
  13375. continue;
  13376. }
  13377. else {
  13378. key = String(keyValue);
  13379. }
  13380. }
  13381. else {
  13382. key =
  13383. property.key instanceof Identifier
  13384. ? property.key.name
  13385. : String(property.key.value);
  13386. if (key === '__proto__' && property.kind === 'init') {
  13387. this.protoProp = property;
  13388. prototype =
  13389. property.value instanceof Literal && property.value.value === null
  13390. ? null
  13391. : property.value;
  13392. continue;
  13393. }
  13394. }
  13395. properties.push({ key, kind: property.kind, property });
  13396. }
  13397. return (this.objectEntity = new ObjectEntity(properties, prototype));
  13398. }
  13399. }
  13400. ObjectExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13401. class PanicError extends NodeBase {
  13402. initialise() {
  13403. const id = this.scope.context.module.id;
  13404. // This simulates the current nested error structure. We could also just
  13405. // replace it with a flat error.
  13406. const parseError = getRollupError(logParseError(this.message));
  13407. const moduleParseError = logModuleParseError(parseError, id);
  13408. return error(moduleParseError);
  13409. }
  13410. }
  13411. class ParseError extends NodeBase {
  13412. initialise() {
  13413. const pos = this.start;
  13414. const id = this.scope.context.module.id;
  13415. // This simulates the current nested error structure. We could also just
  13416. // replace it with a flat error.
  13417. const parseError = getRollupError(logParseError(this.message, pos));
  13418. const moduleParseError = logModuleParseError(parseError, id);
  13419. this.scope.context.error(moduleParseError, pos);
  13420. }
  13421. }
  13422. class PrivateIdentifier extends NodeBase {
  13423. }
  13424. PrivateIdentifier.prototype.includeNode = onlyIncludeSelf;
  13425. class Program extends NodeBase {
  13426. constructor() {
  13427. super(...arguments);
  13428. this.hasCachedEffect = null;
  13429. this.hasLoggedEffect = false;
  13430. }
  13431. hasCachedEffects() {
  13432. if (!this.included) {
  13433. return false;
  13434. }
  13435. return this.hasCachedEffect === null
  13436. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  13437. : this.hasCachedEffect;
  13438. }
  13439. hasEffects(context) {
  13440. for (const node of this.body) {
  13441. if (node.hasEffects(context)) {
  13442. if (this.scope.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  13443. this.hasLoggedEffect = true;
  13444. const { code, log, module } = this.scope.context;
  13445. log(LOGLEVEL_INFO, logFirstSideEffect(code, module.id, locate(code, node.start, { offsetLine: 1 })), node.start);
  13446. }
  13447. return (this.hasCachedEffect = true);
  13448. }
  13449. }
  13450. return false;
  13451. }
  13452. include(context, includeChildrenRecursively) {
  13453. this.included = true;
  13454. for (const node of this.body) {
  13455. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  13456. node.include(context, includeChildrenRecursively);
  13457. }
  13458. }
  13459. }
  13460. initialise() {
  13461. super.initialise();
  13462. if (this.invalidAnnotations)
  13463. for (const { start, end, type } of this.invalidAnnotations) {
  13464. this.scope.context.magicString.remove(start, end);
  13465. if (type === 'pure' || type === 'noSideEffects') {
  13466. this.scope.context.log(LOGLEVEL_WARN, logInvalidAnnotation(this.scope.context.code.slice(start, end), this.scope.context.module.id, type), start);
  13467. }
  13468. }
  13469. }
  13470. render(code, options) {
  13471. let start = this.start;
  13472. if (code.original.startsWith('#!')) {
  13473. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  13474. code.remove(0, start);
  13475. }
  13476. if (this.body.length > 0) {
  13477. // Keep all consecutive lines that start with a comment
  13478. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  13479. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  13480. if (firstLineBreak[0] === -1) {
  13481. break;
  13482. }
  13483. start += firstLineBreak[1];
  13484. }
  13485. renderStatementList(this.body, code, start, this.end, options);
  13486. }
  13487. else {
  13488. super.render(code, options);
  13489. }
  13490. }
  13491. }
  13492. Program.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13493. Program.prototype.applyDeoptimizations = doNotDeoptimize;
  13494. class Property extends MethodBase {
  13495. //declare method: boolean;
  13496. get method() {
  13497. return isFlagSet(this.flags, 262144 /* Flag.method */);
  13498. }
  13499. set method(value) {
  13500. this.flags = setFlag(this.flags, 262144 /* Flag.method */, value);
  13501. }
  13502. //declare shorthand: boolean;
  13503. get shorthand() {
  13504. return isFlagSet(this.flags, 524288 /* Flag.shorthand */);
  13505. }
  13506. set shorthand(value) {
  13507. this.flags = setFlag(this.flags, 524288 /* Flag.shorthand */, value);
  13508. }
  13509. declare(kind, destructuredInitPath, init) {
  13510. return this.value.declare(kind, this.getPathInProperty(destructuredInitPath), init);
  13511. }
  13512. deoptimizeAssignment(destructuredInitPath, init) {
  13513. this.value.deoptimizeAssignment?.(this.getPathInProperty(destructuredInitPath), init);
  13514. }
  13515. hasEffects(context) {
  13516. return this.key.hasEffects(context) || this.value.hasEffects(context);
  13517. }
  13518. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  13519. return this.value.hasEffectsWhenDestructuring?.(context, this.getPathInProperty(destructuredInitPath), init);
  13520. }
  13521. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  13522. const path = this.getPathInProperty(destructuredInitPath);
  13523. let included = this.value.includeDestructuredIfNecessary(context, path, init) ||
  13524. this.included;
  13525. if ((included ||= this.key.hasEffects(createHasEffectsContext()))) {
  13526. this.key.include(context, false);
  13527. if (!this.value.included) {
  13528. this.value.included = true;
  13529. // Unfortunately, we need to include the value again now, so that any
  13530. // declared variables are properly included.
  13531. this.value.includeDestructuredIfNecessary(context, path, init);
  13532. }
  13533. }
  13534. return (this.included = included);
  13535. }
  13536. include(context, includeChildrenRecursively) {
  13537. this.included = true;
  13538. this.key.include(context, includeChildrenRecursively);
  13539. this.value.include(context, includeChildrenRecursively);
  13540. }
  13541. includePath(path, context) {
  13542. this.included = true;
  13543. this.value.includePath(path, context);
  13544. }
  13545. markDeclarationReached() {
  13546. this.value.markDeclarationReached();
  13547. }
  13548. render(code, options) {
  13549. if (!this.shorthand) {
  13550. this.key.render(code, options);
  13551. }
  13552. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  13553. }
  13554. getPathInProperty(destructuredInitPath) {
  13555. return destructuredInitPath.at(-1) === UnknownKey
  13556. ? destructuredInitPath
  13557. : // For now, we only consider static paths as we do not know how to
  13558. // deoptimize the path in the dynamic case.
  13559. this.computed
  13560. ? [...destructuredInitPath, UnknownKey]
  13561. : this.key instanceof Identifier
  13562. ? [...destructuredInitPath, this.key.name]
  13563. : [...destructuredInitPath, String(this.key.value)];
  13564. }
  13565. }
  13566. Property.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13567. Property.prototype.applyDeoptimizations = doNotDeoptimize;
  13568. class PropertyDefinition extends NodeBase {
  13569. get computed() {
  13570. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  13571. }
  13572. set computed(value) {
  13573. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  13574. }
  13575. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13576. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13577. }
  13578. deoptimizePath(path) {
  13579. this.value?.deoptimizePath(path);
  13580. }
  13581. getLiteralValueAtPath(path, recursionTracker, origin) {
  13582. return this.value
  13583. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  13584. : UnknownValue;
  13585. }
  13586. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13587. return this.value
  13588. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  13589. : UNKNOWN_RETURN_EXPRESSION;
  13590. }
  13591. hasEffects(context) {
  13592. return (this.key.hasEffects(context) ||
  13593. (this.static && !!this.value?.hasEffects(context)) ||
  13594. checkEffectForNodes(this.decorators, context));
  13595. }
  13596. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13597. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  13598. }
  13599. includeNode(context) {
  13600. this.included = true;
  13601. this.value?.includePath(UNKNOWN_PATH, context);
  13602. for (const decorator of this.decorators) {
  13603. decorator.includePath(UNKNOWN_PATH, context);
  13604. }
  13605. }
  13606. }
  13607. PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
  13608. class ReturnStatement extends NodeBase {
  13609. hasEffects(context) {
  13610. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  13611. return true;
  13612. context.brokenFlow = true;
  13613. return false;
  13614. }
  13615. include(context, includeChildrenRecursively) {
  13616. if (!this.included)
  13617. this.includeNode(context);
  13618. this.argument?.include(context, includeChildrenRecursively);
  13619. context.brokenFlow = true;
  13620. }
  13621. includeNode(context) {
  13622. this.included = true;
  13623. this.argument?.includePath(UNKNOWN_PATH, context);
  13624. }
  13625. initialise() {
  13626. super.initialise();
  13627. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  13628. }
  13629. render(code, options) {
  13630. if (this.argument) {
  13631. this.argument.render(code, options, { preventASI: true });
  13632. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  13633. code.prependLeft(this.start + 6, ' ');
  13634. }
  13635. }
  13636. }
  13637. }
  13638. ReturnStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13639. class SequenceExpression extends NodeBase {
  13640. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13641. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13642. }
  13643. deoptimizePath(path) {
  13644. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  13645. }
  13646. getLiteralValueAtPath(path, recursionTracker, origin) {
  13647. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  13648. }
  13649. hasEffects(context) {
  13650. for (const expression of this.expressions) {
  13651. if (expression.hasEffects(context))
  13652. return true;
  13653. }
  13654. return false;
  13655. }
  13656. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13657. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  13658. }
  13659. include(context, includeChildrenRecursively) {
  13660. this.included = true;
  13661. const lastExpression = this.expressions[this.expressions.length - 1];
  13662. for (const expression of this.expressions) {
  13663. if (includeChildrenRecursively ||
  13664. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  13665. expression.shouldBeIncluded(context)) {
  13666. expression.include(context, includeChildrenRecursively);
  13667. }
  13668. }
  13669. }
  13670. includePath(path, context) {
  13671. this.included = true;
  13672. this.expressions[this.expressions.length - 1].includePath(path, context);
  13673. }
  13674. removeAnnotations(code) {
  13675. this.expressions[0].removeAnnotations(code);
  13676. }
  13677. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  13678. let includedNodes = 0;
  13679. let lastSeparatorPos = null;
  13680. const lastNode = this.expressions[this.expressions.length - 1];
  13681. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  13682. if (!node.included) {
  13683. treeshakeNode(node, code, start, end);
  13684. continue;
  13685. }
  13686. includedNodes++;
  13687. lastSeparatorPos = separator;
  13688. if (includedNodes === 1 && preventASI) {
  13689. removeLineBreaks(code, start, node.start);
  13690. }
  13691. if (includedNodes === 1) {
  13692. const parentType = renderedParentType || this.parent.type;
  13693. node.render(code, options, {
  13694. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  13695. renderedParentType: parentType,
  13696. renderedSurroundingElement: parentType
  13697. });
  13698. }
  13699. else {
  13700. node.render(code, options);
  13701. }
  13702. }
  13703. if (lastSeparatorPos) {
  13704. code.remove(lastSeparatorPos, this.end);
  13705. }
  13706. }
  13707. }
  13708. SequenceExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13709. SequenceExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13710. class Super extends NodeBase {
  13711. bind() {
  13712. this.variable = this.scope.findVariable('this');
  13713. }
  13714. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13715. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13716. }
  13717. deoptimizePath(path) {
  13718. this.variable.deoptimizePath(path);
  13719. }
  13720. include(context) {
  13721. if (!this.included)
  13722. this.includeNode(context);
  13723. }
  13724. includeNode(context) {
  13725. this.included = true;
  13726. if (!this.deoptimized)
  13727. this.applyDeoptimizations();
  13728. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  13729. }
  13730. }
  13731. class SwitchCase extends NodeBase {
  13732. hasEffects(context) {
  13733. if (this.test?.hasEffects(context))
  13734. return true;
  13735. for (const node of this.consequent) {
  13736. if (context.brokenFlow)
  13737. break;
  13738. if (node.hasEffects(context))
  13739. return true;
  13740. }
  13741. return false;
  13742. }
  13743. include(context, includeChildrenRecursively) {
  13744. this.included = true;
  13745. this.test?.include(context, includeChildrenRecursively);
  13746. for (const node of this.consequent) {
  13747. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  13748. node.include(context, includeChildrenRecursively);
  13749. }
  13750. }
  13751. render(code, options, nodeRenderOptions) {
  13752. if (this.test) {
  13753. this.test.render(code, options);
  13754. if (this.test.start === this.start + 4) {
  13755. code.prependLeft(this.test.start, ' ');
  13756. }
  13757. }
  13758. if (this.consequent.length > 0) {
  13759. const testEnd = this.test
  13760. ? this.test.end
  13761. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  13762. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  13763. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  13764. }
  13765. }
  13766. }
  13767. SwitchCase.prototype.needsBoundaries = true;
  13768. SwitchCase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13769. SwitchCase.prototype.applyDeoptimizations = doNotDeoptimize;
  13770. class SwitchStatement extends NodeBase {
  13771. createScope(parentScope) {
  13772. this.parentScope = parentScope;
  13773. this.scope = new BlockScope(parentScope);
  13774. }
  13775. hasEffects(context) {
  13776. if (this.discriminant.hasEffects(context))
  13777. return true;
  13778. const { brokenFlow, hasBreak, ignore } = context;
  13779. const { breaks } = ignore;
  13780. ignore.breaks = true;
  13781. context.hasBreak = false;
  13782. let onlyHasBrokenFlow = true;
  13783. for (const switchCase of this.cases) {
  13784. if (switchCase.hasEffects(context))
  13785. return true;
  13786. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  13787. context.hasBreak = false;
  13788. context.brokenFlow = brokenFlow;
  13789. }
  13790. if (this.defaultCase !== null) {
  13791. context.brokenFlow = onlyHasBrokenFlow;
  13792. }
  13793. ignore.breaks = breaks;
  13794. context.hasBreak = hasBreak;
  13795. return false;
  13796. }
  13797. include(context, includeChildrenRecursively) {
  13798. this.included = true;
  13799. this.discriminant.include(context, includeChildrenRecursively);
  13800. const { brokenFlow, hasBreak } = context;
  13801. context.hasBreak = false;
  13802. let onlyHasBrokenFlow = true;
  13803. let isCaseIncluded = includeChildrenRecursively ||
  13804. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  13805. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  13806. const switchCase = this.cases[caseIndex];
  13807. if (switchCase.included) {
  13808. isCaseIncluded = true;
  13809. }
  13810. if (!isCaseIncluded) {
  13811. const hasEffectsContext = createHasEffectsContext();
  13812. hasEffectsContext.ignore.breaks = true;
  13813. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  13814. }
  13815. if (isCaseIncluded) {
  13816. switchCase.include(context, includeChildrenRecursively);
  13817. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  13818. context.hasBreak = false;
  13819. context.brokenFlow = brokenFlow;
  13820. }
  13821. else {
  13822. onlyHasBrokenFlow = brokenFlow;
  13823. }
  13824. }
  13825. if (isCaseIncluded && this.defaultCase !== null) {
  13826. context.brokenFlow = onlyHasBrokenFlow;
  13827. }
  13828. context.hasBreak = hasBreak;
  13829. }
  13830. initialise() {
  13831. super.initialise();
  13832. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  13833. if (this.cases[caseIndex].test === null) {
  13834. this.defaultCase = caseIndex;
  13835. return;
  13836. }
  13837. }
  13838. this.defaultCase = null;
  13839. }
  13840. parseNode(esTreeNode) {
  13841. this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
  13842. return super.parseNode(esTreeNode);
  13843. }
  13844. render(code, options) {
  13845. this.discriminant.render(code, options);
  13846. if (this.cases.length > 0) {
  13847. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  13848. }
  13849. }
  13850. }
  13851. SwitchStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13852. SwitchStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13853. class TaggedTemplateExpression extends CallExpressionBase {
  13854. get hasCheckedForWarnings() {
  13855. return isFlagSet(this.flags, 268435456 /* Flag.checkedForWarnings */);
  13856. }
  13857. set hasCheckedForWarnings(value) {
  13858. this.flags = setFlag(this.flags, 268435456 /* Flag.checkedForWarnings */, value);
  13859. }
  13860. bind() {
  13861. super.bind();
  13862. }
  13863. hasEffects(context) {
  13864. if (!this.deoptimized)
  13865. this.applyDeoptimizations();
  13866. for (const argument of this.quasi.expressions) {
  13867. if (argument.hasEffects(context))
  13868. return true;
  13869. }
  13870. return (this.tag.hasEffects(context) ||
  13871. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  13872. }
  13873. include(context, includeChildrenRecursively) {
  13874. if (!this.included)
  13875. this.includeNode(context);
  13876. if (includeChildrenRecursively) {
  13877. super.include(context, true);
  13878. }
  13879. else {
  13880. this.quasi.include(context, false);
  13881. this.tag.include(context, false);
  13882. this.tag.includeCallArguments(this.interaction, context);
  13883. }
  13884. }
  13885. initialise() {
  13886. super.initialise();
  13887. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  13888. this.interaction = {
  13889. args: [
  13890. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  13891. ...this.args
  13892. ],
  13893. type: INTERACTION_CALLED,
  13894. withNew: false
  13895. };
  13896. }
  13897. render(code, options) {
  13898. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  13899. this.quasi.render(code, options);
  13900. if (!this.hasCheckedForWarnings && this.tag.type === Identifier$1) {
  13901. this.hasCheckedForWarnings = true;
  13902. const name = this.tag.name;
  13903. const variable = this.scope.findVariable(name);
  13904. if (variable.isNamespace) {
  13905. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(name), this.start);
  13906. }
  13907. }
  13908. }
  13909. applyDeoptimizations() {
  13910. this.deoptimized = true;
  13911. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  13912. this.scope.context.requestTreeshakingPass();
  13913. }
  13914. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  13915. if (this.returnExpression === null) {
  13916. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  13917. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  13918. }
  13919. return this.returnExpression;
  13920. }
  13921. }
  13922. TaggedTemplateExpression.prototype.includeNode = onlyIncludeSelf;
  13923. class TemplateElement extends NodeBase {
  13924. get tail() {
  13925. return isFlagSet(this.flags, 1048576 /* Flag.tail */);
  13926. }
  13927. set tail(value) {
  13928. this.flags = setFlag(this.flags, 1048576 /* Flag.tail */, value);
  13929. }
  13930. // Do not try to bind value
  13931. bind() { }
  13932. hasEffects() {
  13933. return false;
  13934. }
  13935. parseNode(esTreeNode) {
  13936. this.value = esTreeNode.value;
  13937. return super.parseNode(esTreeNode);
  13938. }
  13939. render() { }
  13940. }
  13941. TemplateElement.prototype.includeNode = onlyIncludeSelf;
  13942. class TemplateLiteral extends NodeBase {
  13943. deoptimizeArgumentsOnInteractionAtPath() { }
  13944. getLiteralValueAtPath(path) {
  13945. if (path.length > 0 || this.quasis.length !== 1) {
  13946. return UnknownValue;
  13947. }
  13948. return this.quasis[0].value.cooked;
  13949. }
  13950. getReturnExpressionWhenCalledAtPath(path) {
  13951. if (path.length !== 1) {
  13952. return UNKNOWN_RETURN_EXPRESSION;
  13953. }
  13954. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  13955. }
  13956. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13957. if (interaction.type === INTERACTION_ACCESSED) {
  13958. return path.length > 1;
  13959. }
  13960. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  13961. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  13962. }
  13963. return true;
  13964. }
  13965. includeNode(context) {
  13966. this.included = true;
  13967. if (!this.deoptimized)
  13968. this.applyDeoptimizations();
  13969. for (const node of this.expressions) {
  13970. node.includePath(UNKNOWN_PATH, context);
  13971. }
  13972. }
  13973. render(code, options) {
  13974. code.indentExclusionRanges.push([this.start, this.end]);
  13975. super.render(code, options);
  13976. }
  13977. }
  13978. class ModuleScope extends ChildScope {
  13979. constructor(parent, context) {
  13980. super(parent, context);
  13981. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, EMPTY_PATH, context, 'other'));
  13982. }
  13983. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  13984. if (this.context.module.importDescriptions.has(identifier.name)) {
  13985. context.error(logRedeclarationError(identifier.name), identifier.start);
  13986. }
  13987. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  13988. }
  13989. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  13990. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  13991. this.variables.set('default', variable);
  13992. return variable;
  13993. }
  13994. addNamespaceMemberAccess() { }
  13995. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  13996. // all module level variables are already deconflicted when deconflicting the chunk
  13997. for (const scope of this.children)
  13998. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  13999. }
  14000. findLexicalBoundary() {
  14001. return this;
  14002. }
  14003. findVariable(name) {
  14004. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  14005. if (knownVariable) {
  14006. return knownVariable;
  14007. }
  14008. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  14009. if (variable instanceof GlobalVariable) {
  14010. this.accessedOutsideVariables.set(name, variable);
  14011. }
  14012. return variable;
  14013. }
  14014. }
  14015. class ThisExpression extends NodeBase {
  14016. bind() {
  14017. this.variable = this.scope.findVariable('this');
  14018. }
  14019. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14020. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14021. }
  14022. deoptimizePath(path) {
  14023. this.variable.deoptimizePath(path);
  14024. }
  14025. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14026. if (path.length === 0) {
  14027. return interaction.type !== INTERACTION_ACCESSED;
  14028. }
  14029. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  14030. }
  14031. include(context) {
  14032. if (!this.included)
  14033. this.includeNode(context);
  14034. }
  14035. includeNode(context) {
  14036. this.included = true;
  14037. if (!this.deoptimized)
  14038. this.applyDeoptimizations();
  14039. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  14040. }
  14041. includePath(path, context) {
  14042. if (!this.included) {
  14043. this.included = true;
  14044. this.scope.context.includeVariableInModule(this.variable, path, context);
  14045. }
  14046. else if (path.length > 0) {
  14047. this.variable.includePath(path, context);
  14048. }
  14049. const functionScope = findFunctionScope(this.scope, this.variable);
  14050. if (functionScope &&
  14051. functionScope.functionNode.parent instanceof Property &&
  14052. functionScope.functionNode.parent.parent instanceof ObjectExpression) {
  14053. functionScope.functionNode.parent.parent.includePath(path, context);
  14054. }
  14055. }
  14056. initialise() {
  14057. super.initialise();
  14058. this.alias =
  14059. this.scope.findLexicalBoundary() instanceof ModuleScope
  14060. ? this.scope.context.moduleContext
  14061. : null;
  14062. if (this.alias === 'undefined') {
  14063. this.scope.context.log(LOGLEVEL_WARN, logThisIsUndefined(), this.start);
  14064. }
  14065. }
  14066. render(code) {
  14067. if (this.alias !== null) {
  14068. code.overwrite(this.start, this.end, this.alias, {
  14069. contentOnly: false,
  14070. storeName: true
  14071. });
  14072. }
  14073. }
  14074. }
  14075. function findFunctionScope(scope, thisVariable) {
  14076. while (!(scope instanceof FunctionScope && scope.thisVariable === thisVariable)) {
  14077. if (!(scope instanceof ChildScope)) {
  14078. return null;
  14079. }
  14080. scope = scope.parent;
  14081. }
  14082. return scope;
  14083. }
  14084. class ThrowStatement extends NodeBase {
  14085. hasEffects() {
  14086. return true;
  14087. }
  14088. include(context, includeChildrenRecursively) {
  14089. if (!this.included)
  14090. this.includeNode(context);
  14091. this.argument.include(context, includeChildrenRecursively);
  14092. context.brokenFlow = true;
  14093. }
  14094. includeNode(context) {
  14095. if (!this.included) {
  14096. this.included = true;
  14097. this.argument.includePath(UNKNOWN_PATH, context);
  14098. }
  14099. }
  14100. render(code, options) {
  14101. this.argument.render(code, options, { preventASI: true });
  14102. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  14103. code.prependLeft(this.start + 5, ' ');
  14104. }
  14105. }
  14106. }
  14107. class TryStatement extends NodeBase {
  14108. constructor() {
  14109. super(...arguments);
  14110. this.directlyIncluded = false;
  14111. this.includedLabelsAfterBlock = null;
  14112. }
  14113. hasEffects(context) {
  14114. return ((this.scope.context.options.treeshake.tryCatchDeoptimization
  14115. ? this.block.body.length > 0
  14116. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  14117. }
  14118. include(context, includeChildrenRecursively) {
  14119. const tryCatchDeoptimization = this.scope.context.options.treeshake?.tryCatchDeoptimization;
  14120. const { brokenFlow, includedLabels } = context;
  14121. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  14122. this.included = true;
  14123. this.directlyIncluded = true;
  14124. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  14125. if (includedLabels.size > 0) {
  14126. this.includedLabelsAfterBlock = [...includedLabels];
  14127. }
  14128. context.brokenFlow = brokenFlow;
  14129. }
  14130. else if (this.includedLabelsAfterBlock) {
  14131. for (const label of this.includedLabelsAfterBlock) {
  14132. includedLabels.add(label);
  14133. }
  14134. }
  14135. if (this.handler !== null) {
  14136. this.handler.include(context, includeChildrenRecursively);
  14137. context.brokenFlow = brokenFlow;
  14138. }
  14139. this.finalizer?.include(context, includeChildrenRecursively);
  14140. }
  14141. }
  14142. TryStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14143. TryStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14144. const unaryOperators = {
  14145. '!': value => !value,
  14146. '+': value => +value,
  14147. '-': value => -value,
  14148. delete: () => UnknownValue,
  14149. typeof: value => typeof value,
  14150. void: () => undefined,
  14151. '~': value => ~value
  14152. };
  14153. const UNASSIGNED = Symbol('Unassigned');
  14154. class UnaryExpression extends NodeBase {
  14155. constructor() {
  14156. super(...arguments);
  14157. this.renderedLiteralValue = UNASSIGNED;
  14158. }
  14159. get prefix() {
  14160. return isFlagSet(this.flags, 2097152 /* Flag.prefix */);
  14161. }
  14162. set prefix(value) {
  14163. this.flags = setFlag(this.flags, 2097152 /* Flag.prefix */, value);
  14164. }
  14165. deoptimizeCache() {
  14166. this.renderedLiteralValue = UnknownValue;
  14167. }
  14168. getLiteralValueAtPath(path, recursionTracker, origin) {
  14169. if (path.length > 0)
  14170. return UnknownValue;
  14171. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  14172. if (typeof argumentValue === 'symbol') {
  14173. if (this.operator === 'void')
  14174. return undefined;
  14175. if (this.operator === '!') {
  14176. if (argumentValue === UnknownFalsyValue)
  14177. return true;
  14178. if (argumentValue === UnknownTruthyValue)
  14179. return false;
  14180. }
  14181. return UnknownValue;
  14182. }
  14183. return unaryOperators[this.operator](argumentValue);
  14184. }
  14185. hasEffects(context) {
  14186. if (!this.deoptimized)
  14187. this.applyDeoptimizations();
  14188. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  14189. return false;
  14190. return (this.argument.hasEffects(context) ||
  14191. (this.operator === 'delete' &&
  14192. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  14193. }
  14194. hasEffectsOnInteractionAtPath(path, { type }) {
  14195. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  14196. }
  14197. applyDeoptimizations() {
  14198. this.deoptimized = true;
  14199. if (this.operator === 'delete') {
  14200. this.argument.deoptimizePath(EMPTY_PATH);
  14201. this.scope.context.requestTreeshakingPass();
  14202. }
  14203. }
  14204. getRenderedLiteralValue(includeChildrenRecursively) {
  14205. if (this.renderedLiteralValue !== UNASSIGNED)
  14206. return this.renderedLiteralValue;
  14207. return (this.renderedLiteralValue = includeChildrenRecursively
  14208. ? UnknownValue
  14209. : getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  14210. }
  14211. include(context, includeChildrenRecursively, _options) {
  14212. if (!this.deoptimized)
  14213. this.applyDeoptimizations();
  14214. this.included = true;
  14215. if (typeof this.getRenderedLiteralValue(includeChildrenRecursively) === 'symbol' ||
  14216. this.argument.shouldBeIncluded(context)) {
  14217. this.argument.include(context, includeChildrenRecursively);
  14218. this.renderedLiteralValue = UnknownValue;
  14219. }
  14220. }
  14221. render(code, options) {
  14222. if (typeof this.renderedLiteralValue === 'symbol') {
  14223. super.render(code, options);
  14224. }
  14225. else {
  14226. let value = this.renderedLiteralValue;
  14227. if (!CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE.test(code.original[this.start - 1])) {
  14228. value = ` ${value}`;
  14229. }
  14230. code.overwrite(this.start, this.end, value);
  14231. }
  14232. }
  14233. }
  14234. const CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE = /[\s([=%&*+-/<>^|,?:;]/;
  14235. function getRenderedLiteralValue(value) {
  14236. if (value === undefined) {
  14237. // At the moment, the undefined only happens when the operator is void
  14238. return 'void 0';
  14239. }
  14240. if (typeof value === 'boolean') {
  14241. return String(value);
  14242. }
  14243. if (typeof value === 'string') {
  14244. return JSON.stringify(value);
  14245. }
  14246. if (typeof value === 'number') {
  14247. return getSimplifiedNumber(value);
  14248. }
  14249. return UnknownValue;
  14250. }
  14251. function getSimplifiedNumber(value) {
  14252. if (Object.is(-0, value)) {
  14253. return '-0';
  14254. }
  14255. const exp = value.toExponential();
  14256. const [base, exponent] = exp.split('e');
  14257. const floatLength = base.split('.')[1]?.length || 0;
  14258. const finalizedExp = `${base.replace('.', '')}e${parseInt(exponent) - floatLength}`;
  14259. const stringifiedValue = String(value).replace('+', '');
  14260. return finalizedExp.length < stringifiedValue.length ? finalizedExp : stringifiedValue;
  14261. }
  14262. UnaryExpression.prototype.includeNode = onlyIncludeSelf;
  14263. class UpdateExpression extends NodeBase {
  14264. hasEffects(context) {
  14265. if (!this.deoptimized)
  14266. this.applyDeoptimizations();
  14267. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  14268. }
  14269. hasEffectsOnInteractionAtPath(path, { type }) {
  14270. return path.length > 1 || type !== INTERACTION_ACCESSED;
  14271. }
  14272. include(context, includeChildrenRecursively) {
  14273. if (!this.included)
  14274. this.includeNode(context);
  14275. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  14276. }
  14277. initialise() {
  14278. super.initialise();
  14279. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  14280. }
  14281. render(code, options) {
  14282. const { exportNamesByVariable, format, snippets: { _ } } = options;
  14283. this.argument.render(code, options);
  14284. if (format === 'system') {
  14285. const variable = this.argument.variable;
  14286. const exportNames = exportNamesByVariable.get(variable);
  14287. if (exportNames) {
  14288. if (this.prefix) {
  14289. if (exportNames.length === 1) {
  14290. renderSystemExportExpression(variable, this.start, this.end, code, options);
  14291. }
  14292. else {
  14293. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  14294. }
  14295. }
  14296. else {
  14297. const operator = this.operator[0];
  14298. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  14299. }
  14300. }
  14301. }
  14302. }
  14303. applyDeoptimizations() {
  14304. this.deoptimized = true;
  14305. this.argument.deoptimizePath(EMPTY_PATH);
  14306. if (this.argument instanceof Identifier) {
  14307. const variable = this.scope.findVariable(this.argument.name);
  14308. variable.markReassigned();
  14309. }
  14310. this.scope.context.requestTreeshakingPass();
  14311. }
  14312. }
  14313. UpdateExpression.prototype.includeNode = onlyIncludeSelf;
  14314. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  14315. for (const declarator of declarations) {
  14316. if (!declarator.id.included)
  14317. return false;
  14318. if (declarator.id.type === Identifier$1) {
  14319. if (exportNamesByVariable.has(declarator.id.variable))
  14320. return false;
  14321. }
  14322. else {
  14323. const exportedVariables = [];
  14324. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  14325. if (exportedVariables.length > 0)
  14326. return false;
  14327. }
  14328. }
  14329. return true;
  14330. }
  14331. class VariableDeclaration extends NodeBase {
  14332. deoptimizePath() {
  14333. for (const declarator of this.declarations) {
  14334. declarator.deoptimizePath(EMPTY_PATH);
  14335. }
  14336. }
  14337. hasEffectsOnInteractionAtPath() {
  14338. return false;
  14339. }
  14340. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  14341. this.included = true;
  14342. for (const declarator of this.declarations) {
  14343. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  14344. declarator.include(context, includeChildrenRecursively);
  14345. }
  14346. const { id, init } = declarator;
  14347. if (asSingleStatement) {
  14348. id.include(context, includeChildrenRecursively);
  14349. }
  14350. if (init &&
  14351. id.included &&
  14352. !init.included &&
  14353. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  14354. init.include(context, includeChildrenRecursively);
  14355. }
  14356. }
  14357. }
  14358. initialise() {
  14359. super.initialise();
  14360. this.isUsingDeclaration = this.kind === 'await using' || this.kind === 'using';
  14361. for (const declarator of this.declarations) {
  14362. declarator.declareDeclarator(this.kind, this.isUsingDeclaration);
  14363. }
  14364. }
  14365. removeAnnotations(code) {
  14366. this.declarations[0].removeAnnotations(code);
  14367. }
  14368. render(code, options, nodeRenderOptions = BLANK) {
  14369. if (this.isUsingDeclaration ||
  14370. areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  14371. for (const declarator of this.declarations) {
  14372. declarator.render(code, options);
  14373. }
  14374. if (!nodeRenderOptions.isNoStatement &&
  14375. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  14376. code.appendLeft(this.end, ';');
  14377. }
  14378. }
  14379. else {
  14380. this.renderReplacedDeclarations(code, options);
  14381. }
  14382. }
  14383. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  14384. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  14385. code.remove(this.end - 1, this.end);
  14386. }
  14387. separatorString += ';';
  14388. if (lastSeparatorPos === null) {
  14389. code.appendLeft(renderedContentEnd, separatorString);
  14390. }
  14391. else {
  14392. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  14393. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  14394. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  14395. actualContentEnd--;
  14396. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  14397. actualContentEnd--;
  14398. }
  14399. }
  14400. if (actualContentEnd === lastSeparatorPos + 1) {
  14401. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  14402. }
  14403. else {
  14404. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  14405. code.remove(actualContentEnd, renderedContentEnd);
  14406. }
  14407. }
  14408. if (systemPatternExports.length > 0) {
  14409. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  14410. }
  14411. }
  14412. renderReplacedDeclarations(code, options) {
  14413. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  14414. let actualContentEnd, renderedContentEnd;
  14415. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  14416. let lastSeparatorPos = renderedContentEnd - 1;
  14417. code.remove(this.start, lastSeparatorPos);
  14418. let isInDeclaration = false;
  14419. let hasRenderedContent = false;
  14420. let separatorString = '', leadingString, nextSeparatorString;
  14421. const aggregatedSystemExports = [];
  14422. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  14423. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  14424. if (!node.included) {
  14425. treeshakeNode(node, code, start, end);
  14426. continue;
  14427. }
  14428. node.render(code, options);
  14429. leadingString = '';
  14430. nextSeparatorString = '';
  14431. if (!node.id.included ||
  14432. (node.id instanceof Identifier &&
  14433. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  14434. if (hasRenderedContent) {
  14435. separatorString += ';';
  14436. }
  14437. isInDeclaration = false;
  14438. }
  14439. else {
  14440. if (singleSystemExport && singleSystemExport === node.id.variable) {
  14441. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  14442. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  14443. }
  14444. if (isInDeclaration) {
  14445. separatorString += ',';
  14446. }
  14447. else {
  14448. if (hasRenderedContent) {
  14449. separatorString += ';';
  14450. }
  14451. leadingString += `${this.kind} `;
  14452. isInDeclaration = true;
  14453. }
  14454. }
  14455. if (renderedContentEnd === lastSeparatorPos + 1) {
  14456. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  14457. }
  14458. else {
  14459. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  14460. code.appendLeft(renderedContentEnd, leadingString);
  14461. }
  14462. actualContentEnd = contentEnd;
  14463. renderedContentEnd = end;
  14464. hasRenderedContent = true;
  14465. lastSeparatorPos = separator;
  14466. separatorString = nextSeparatorString;
  14467. }
  14468. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  14469. }
  14470. }
  14471. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  14472. let singleSystemExport = null;
  14473. if (options.format === 'system') {
  14474. for (const { node } of separatedNodes) {
  14475. if (node.id instanceof Identifier &&
  14476. node.init &&
  14477. aggregatedSystemExports.length === 0 &&
  14478. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  14479. singleSystemExport = node.id.variable;
  14480. aggregatedSystemExports.push(singleSystemExport);
  14481. }
  14482. else {
  14483. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  14484. }
  14485. }
  14486. if (aggregatedSystemExports.length > 1) {
  14487. singleSystemExport = null;
  14488. }
  14489. else if (singleSystemExport) {
  14490. aggregatedSystemExports.length = 0;
  14491. }
  14492. }
  14493. return singleSystemExport;
  14494. }
  14495. VariableDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14496. VariableDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  14497. class WhileStatement extends NodeBase {
  14498. hasEffects(context) {
  14499. if (this.test.hasEffects(context))
  14500. return true;
  14501. return hasLoopBodyEffects(context, this.body);
  14502. }
  14503. include(context, includeChildrenRecursively) {
  14504. this.included = true;
  14505. this.test.include(context, includeChildrenRecursively);
  14506. includeLoopBody(context, this.body, includeChildrenRecursively);
  14507. }
  14508. }
  14509. WhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14510. WhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14511. class YieldExpression extends NodeBase {
  14512. applyDeoptimizations() {
  14513. this.deoptimized = true;
  14514. this.argument?.deoptimizePath(UNKNOWN_PATH);
  14515. }
  14516. hasEffects(context) {
  14517. if (!this.deoptimized)
  14518. this.applyDeoptimizations();
  14519. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  14520. }
  14521. includeNode(context) {
  14522. this.included = true;
  14523. if (!this.deoptimized)
  14524. this.applyDeoptimizations();
  14525. this.argument?.includePath(UNKNOWN_PATH, context);
  14526. }
  14527. render(code, options) {
  14528. if (this.argument) {
  14529. this.argument.render(code, options, { preventASI: true });
  14530. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  14531. code.prependLeft(this.start + 5, ' ');
  14532. }
  14533. }
  14534. }
  14535. }
  14536. // This file is generated by scripts/generate-buffer-parsers.js.
  14537. // Do not edit this file directly.
  14538. function convertProgram(buffer, parent, parentScope) {
  14539. return convertNode(parent, parentScope, 0, getAstBuffer(buffer));
  14540. }
  14541. const nodeTypeStrings = [
  14542. 'PanicError',
  14543. 'ParseError',
  14544. 'ArrayExpression',
  14545. 'ArrayPattern',
  14546. 'ArrowFunctionExpression',
  14547. 'AssignmentExpression',
  14548. 'AssignmentPattern',
  14549. 'AwaitExpression',
  14550. 'BinaryExpression',
  14551. 'BlockStatement',
  14552. 'BreakStatement',
  14553. 'CallExpression',
  14554. 'CatchClause',
  14555. 'ChainExpression',
  14556. 'ClassBody',
  14557. 'ClassDeclaration',
  14558. 'ClassExpression',
  14559. 'ConditionalExpression',
  14560. 'ContinueStatement',
  14561. 'DebuggerStatement',
  14562. 'Decorator',
  14563. 'ExpressionStatement',
  14564. 'DoWhileStatement',
  14565. 'EmptyStatement',
  14566. 'ExportAllDeclaration',
  14567. 'ExportDefaultDeclaration',
  14568. 'ExportNamedDeclaration',
  14569. 'ExportSpecifier',
  14570. 'ExpressionStatement',
  14571. 'ForInStatement',
  14572. 'ForOfStatement',
  14573. 'ForStatement',
  14574. 'FunctionDeclaration',
  14575. 'FunctionExpression',
  14576. 'Identifier',
  14577. 'IfStatement',
  14578. 'ImportAttribute',
  14579. 'ImportDeclaration',
  14580. 'ImportDefaultSpecifier',
  14581. 'ImportExpression',
  14582. 'ImportNamespaceSpecifier',
  14583. 'ImportSpecifier',
  14584. 'JSXAttribute',
  14585. 'JSXClosingElement',
  14586. 'JSXClosingFragment',
  14587. 'JSXElement',
  14588. 'JSXEmptyExpression',
  14589. 'JSXExpressionContainer',
  14590. 'JSXFragment',
  14591. 'JSXIdentifier',
  14592. 'JSXMemberExpression',
  14593. 'JSXNamespacedName',
  14594. 'JSXOpeningElement',
  14595. 'JSXOpeningFragment',
  14596. 'JSXSpreadAttribute',
  14597. 'JSXSpreadChild',
  14598. 'JSXText',
  14599. 'LabeledStatement',
  14600. 'Literal',
  14601. 'Literal',
  14602. 'Literal',
  14603. 'Literal',
  14604. 'Literal',
  14605. 'Literal',
  14606. 'LogicalExpression',
  14607. 'MemberExpression',
  14608. 'MetaProperty',
  14609. 'MethodDefinition',
  14610. 'NewExpression',
  14611. 'ObjectExpression',
  14612. 'ObjectPattern',
  14613. 'PrivateIdentifier',
  14614. 'Program',
  14615. 'Property',
  14616. 'PropertyDefinition',
  14617. 'RestElement',
  14618. 'ReturnStatement',
  14619. 'SequenceExpression',
  14620. 'SpreadElement',
  14621. 'StaticBlock',
  14622. 'Super',
  14623. 'SwitchCase',
  14624. 'SwitchStatement',
  14625. 'TaggedTemplateExpression',
  14626. 'TemplateElement',
  14627. 'TemplateLiteral',
  14628. 'ThisExpression',
  14629. 'ThrowStatement',
  14630. 'TryStatement',
  14631. 'UnaryExpression',
  14632. 'UpdateExpression',
  14633. 'VariableDeclaration',
  14634. 'VariableDeclarator',
  14635. 'WhileStatement',
  14636. 'YieldExpression'
  14637. ];
  14638. const nodeConstructors$1 = [
  14639. PanicError,
  14640. ParseError,
  14641. ArrayExpression,
  14642. ArrayPattern,
  14643. ArrowFunctionExpression,
  14644. AssignmentExpression,
  14645. AssignmentPattern,
  14646. AwaitExpression,
  14647. BinaryExpression,
  14648. BlockStatement,
  14649. BreakStatement,
  14650. CallExpression,
  14651. CatchClause,
  14652. ChainExpression,
  14653. ClassBody,
  14654. ClassDeclaration,
  14655. ClassExpression,
  14656. ConditionalExpression,
  14657. ContinueStatement,
  14658. DebuggerStatement,
  14659. Decorator,
  14660. ExpressionStatement,
  14661. DoWhileStatement,
  14662. EmptyStatement,
  14663. ExportAllDeclaration,
  14664. ExportDefaultDeclaration,
  14665. ExportNamedDeclaration,
  14666. ExportSpecifier,
  14667. ExpressionStatement,
  14668. ForInStatement,
  14669. ForOfStatement,
  14670. ForStatement,
  14671. FunctionDeclaration,
  14672. FunctionExpression,
  14673. Identifier,
  14674. IfStatement,
  14675. ImportAttribute,
  14676. ImportDeclaration,
  14677. ImportDefaultSpecifier,
  14678. ImportExpression,
  14679. ImportNamespaceSpecifier,
  14680. ImportSpecifier,
  14681. JSXAttribute,
  14682. JSXClosingElement,
  14683. JSXClosingFragment,
  14684. JSXElement,
  14685. JSXEmptyExpression,
  14686. JSXExpressionContainer,
  14687. JSXFragment,
  14688. JSXIdentifier,
  14689. JSXMemberExpression,
  14690. JSXNamespacedName,
  14691. JSXOpeningElement,
  14692. JSXOpeningFragment,
  14693. JSXSpreadAttribute,
  14694. JSXSpreadChild,
  14695. JSXText,
  14696. LabeledStatement,
  14697. Literal,
  14698. Literal,
  14699. Literal,
  14700. Literal,
  14701. Literal,
  14702. Literal,
  14703. LogicalExpression,
  14704. MemberExpression,
  14705. MetaProperty,
  14706. MethodDefinition,
  14707. NewExpression,
  14708. ObjectExpression,
  14709. ObjectPattern,
  14710. PrivateIdentifier,
  14711. Program,
  14712. Property,
  14713. PropertyDefinition,
  14714. RestElement,
  14715. ReturnStatement,
  14716. SequenceExpression,
  14717. SpreadElement,
  14718. StaticBlock,
  14719. Super,
  14720. SwitchCase,
  14721. SwitchStatement,
  14722. TaggedTemplateExpression,
  14723. TemplateElement,
  14724. TemplateLiteral,
  14725. ThisExpression,
  14726. ThrowStatement,
  14727. TryStatement,
  14728. UnaryExpression,
  14729. UpdateExpression,
  14730. VariableDeclaration,
  14731. VariableDeclarator,
  14732. WhileStatement,
  14733. YieldExpression
  14734. ];
  14735. const bufferParsers = [
  14736. function panicError(node, position, buffer) {
  14737. node.message = buffer.convertString(buffer[position]);
  14738. },
  14739. function parseError(node, position, buffer) {
  14740. node.message = buffer.convertString(buffer[position]);
  14741. },
  14742. function arrayExpression(node, position, buffer) {
  14743. const { scope } = node;
  14744. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  14745. },
  14746. function arrayPattern(node, position, buffer) {
  14747. const { scope } = node;
  14748. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  14749. },
  14750. function arrowFunctionExpression(node, position, buffer) {
  14751. const { scope } = node;
  14752. const flags = buffer[position];
  14753. node.async = (flags & 1) === 1;
  14754. node.expression = (flags & 2) === 2;
  14755. node.generator = (flags & 4) === 4;
  14756. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  14757. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  14758. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 2], buffer));
  14759. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  14760. node.body = convertNode(node, scope.bodyScope, buffer[position + 3], buffer);
  14761. },
  14762. function assignmentExpression(node, position, buffer) {
  14763. const { scope } = node;
  14764. node.operator = FIXED_STRINGS[buffer[position]];
  14765. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  14766. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  14767. },
  14768. function assignmentPattern(node, position, buffer) {
  14769. const { scope } = node;
  14770. node.left = convertNode(node, scope, buffer[position], buffer);
  14771. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  14772. },
  14773. function awaitExpression(node, position, buffer) {
  14774. const { scope } = node;
  14775. node.argument = convertNode(node, scope, buffer[position], buffer);
  14776. },
  14777. function binaryExpression(node, position, buffer) {
  14778. const { scope } = node;
  14779. node.operator = FIXED_STRINGS[buffer[position]];
  14780. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  14781. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  14782. },
  14783. function blockStatement(node, position, buffer) {
  14784. const { scope } = node;
  14785. node.body = convertNodeList(node, scope, buffer[position], buffer);
  14786. },
  14787. function breakStatement(node, position, buffer) {
  14788. const { scope } = node;
  14789. const labelPosition = buffer[position];
  14790. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  14791. },
  14792. function callExpression(node, position, buffer) {
  14793. const { scope } = node;
  14794. const flags = buffer[position];
  14795. node.optional = (flags & 1) === 1;
  14796. node.annotations = convertAnnotations(buffer[position + 1], buffer);
  14797. node.callee = convertNode(node, scope, buffer[position + 2], buffer);
  14798. node.arguments = convertNodeList(node, scope, buffer[position + 3], buffer);
  14799. },
  14800. function catchClause(node, position, buffer) {
  14801. const { scope } = node;
  14802. const parameterPosition = buffer[position];
  14803. const parameter = (node.param =
  14804. parameterPosition === 0 ? null : convertNode(node, scope, parameterPosition, buffer));
  14805. parameter?.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  14806. node.body = convertNode(node, scope.bodyScope, buffer[position + 1], buffer);
  14807. },
  14808. function chainExpression(node, position, buffer) {
  14809. const { scope } = node;
  14810. node.expression = convertNode(node, scope, buffer[position], buffer);
  14811. },
  14812. function classBody(node, position, buffer) {
  14813. const { scope } = node;
  14814. const bodyPosition = buffer[position];
  14815. if (bodyPosition) {
  14816. const length = buffer[bodyPosition];
  14817. const body = (node.body = new Array(length));
  14818. for (let index = 0; index < length; index++) {
  14819. const nodePosition = buffer[bodyPosition + 1 + index];
  14820. body[index] = convertNode(node, (buffer[nodePosition + 3] & 1) === 0 ? scope.instanceScope : scope, nodePosition, buffer);
  14821. }
  14822. }
  14823. else {
  14824. node.body = [];
  14825. }
  14826. },
  14827. function classDeclaration(node, position, buffer) {
  14828. const { scope } = node;
  14829. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  14830. const idPosition = buffer[position + 1];
  14831. node.id =
  14832. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  14833. const superClassPosition = buffer[position + 2];
  14834. node.superClass =
  14835. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  14836. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  14837. },
  14838. function classExpression(node, position, buffer) {
  14839. const { scope } = node;
  14840. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  14841. const idPosition = buffer[position + 1];
  14842. node.id = idPosition === 0 ? null : convertNode(node, scope, idPosition, buffer);
  14843. const superClassPosition = buffer[position + 2];
  14844. node.superClass =
  14845. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  14846. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  14847. },
  14848. function conditionalExpression(node, position, buffer) {
  14849. const { scope } = node;
  14850. node.test = convertNode(node, scope, buffer[position], buffer);
  14851. node.consequent = convertNode(node, scope, buffer[position + 1], buffer);
  14852. node.alternate = convertNode(node, scope, buffer[position + 2], buffer);
  14853. },
  14854. function continueStatement(node, position, buffer) {
  14855. const { scope } = node;
  14856. const labelPosition = buffer[position];
  14857. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  14858. },
  14859. function debuggerStatement() { },
  14860. function decorator(node, position, buffer) {
  14861. const { scope } = node;
  14862. node.expression = convertNode(node, scope, buffer[position], buffer);
  14863. },
  14864. function directive(node, position, buffer) {
  14865. const { scope } = node;
  14866. node.directive = buffer.convertString(buffer[position]);
  14867. node.expression = convertNode(node, scope, buffer[position + 1], buffer);
  14868. },
  14869. function doWhileStatement(node, position, buffer) {
  14870. const { scope } = node;
  14871. node.body = convertNode(node, scope, buffer[position], buffer);
  14872. node.test = convertNode(node, scope, buffer[position + 1], buffer);
  14873. },
  14874. function emptyStatement() { },
  14875. function exportAllDeclaration(node, position, buffer) {
  14876. const { scope } = node;
  14877. const exportedPosition = buffer[position];
  14878. node.exported =
  14879. exportedPosition === 0 ? null : convertNode(node, scope, exportedPosition, buffer);
  14880. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  14881. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  14882. },
  14883. function exportDefaultDeclaration(node, position, buffer) {
  14884. const { scope } = node;
  14885. node.declaration = convertNode(node, scope, buffer[position], buffer);
  14886. },
  14887. function exportNamedDeclaration(node, position, buffer) {
  14888. const { scope } = node;
  14889. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  14890. const sourcePosition = buffer[position + 1];
  14891. node.source = sourcePosition === 0 ? null : convertNode(node, scope, sourcePosition, buffer);
  14892. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  14893. const declarationPosition = buffer[position + 3];
  14894. node.declaration =
  14895. declarationPosition === 0 ? null : convertNode(node, scope, declarationPosition, buffer);
  14896. },
  14897. function exportSpecifier(node, position, buffer) {
  14898. const { scope } = node;
  14899. node.local = convertNode(node, scope, buffer[position], buffer);
  14900. const exportedPosition = buffer[position + 1];
  14901. node.exported =
  14902. exportedPosition === 0 ? node.local : convertNode(node, scope, exportedPosition, buffer);
  14903. },
  14904. function expressionStatement(node, position, buffer) {
  14905. const { scope } = node;
  14906. node.expression = convertNode(node, scope, buffer[position], buffer);
  14907. },
  14908. function forInStatement(node, position, buffer) {
  14909. const { scope } = node;
  14910. node.left = convertNode(node, scope, buffer[position], buffer);
  14911. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  14912. node.body = convertNode(node, scope, buffer[position + 2], buffer);
  14913. },
  14914. function forOfStatement(node, position, buffer) {
  14915. const { scope } = node;
  14916. const flags = buffer[position];
  14917. node.await = (flags & 1) === 1;
  14918. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  14919. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  14920. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  14921. },
  14922. function forStatement(node, position, buffer) {
  14923. const { scope } = node;
  14924. const initPosition = buffer[position];
  14925. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  14926. const testPosition = buffer[position + 1];
  14927. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  14928. const updatePosition = buffer[position + 2];
  14929. node.update = updatePosition === 0 ? null : convertNode(node, scope, updatePosition, buffer);
  14930. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  14931. },
  14932. function functionDeclaration(node, position, buffer) {
  14933. const { scope } = node;
  14934. const flags = buffer[position];
  14935. node.async = (flags & 1) === 1;
  14936. node.generator = (flags & 2) === 2;
  14937. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  14938. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  14939. const idPosition = buffer[position + 2];
  14940. node.id =
  14941. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  14942. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  14943. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  14944. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  14945. },
  14946. function functionExpression(node, position, buffer) {
  14947. const { scope } = node;
  14948. const flags = buffer[position];
  14949. node.async = (flags & 1) === 1;
  14950. node.generator = (flags & 2) === 2;
  14951. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  14952. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  14953. const idPosition = buffer[position + 2];
  14954. node.id = idPosition === 0 ? null : convertNode(node, node.idScope, idPosition, buffer);
  14955. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  14956. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  14957. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  14958. },
  14959. function identifier(node, position, buffer) {
  14960. node.name = buffer.convertString(buffer[position]);
  14961. },
  14962. function ifStatement(node, position, buffer) {
  14963. const { scope } = node;
  14964. node.test = convertNode(node, scope, buffer[position], buffer);
  14965. node.consequent = convertNode(node, (node.consequentScope = new TrackingScope(scope)), buffer[position + 1], buffer);
  14966. const alternatePosition = buffer[position + 2];
  14967. node.alternate =
  14968. alternatePosition === 0
  14969. ? null
  14970. : convertNode(node, (node.alternateScope = new TrackingScope(scope)), alternatePosition, buffer);
  14971. },
  14972. function importAttribute(node, position, buffer) {
  14973. const { scope } = node;
  14974. node.key = convertNode(node, scope, buffer[position], buffer);
  14975. node.value = convertNode(node, scope, buffer[position + 1], buffer);
  14976. },
  14977. function importDeclaration(node, position, buffer) {
  14978. const { scope } = node;
  14979. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  14980. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  14981. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  14982. },
  14983. function importDefaultSpecifier(node, position, buffer) {
  14984. const { scope } = node;
  14985. node.local = convertNode(node, scope, buffer[position], buffer);
  14986. },
  14987. function importExpression(node, position, buffer) {
  14988. const { scope } = node;
  14989. node.source = convertNode(node, scope, buffer[position], buffer);
  14990. node.sourceAstNode = convertNode$1(buffer[position], buffer);
  14991. const optionsPosition = buffer[position + 1];
  14992. node.options = optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer);
  14993. },
  14994. function importNamespaceSpecifier(node, position, buffer) {
  14995. const { scope } = node;
  14996. node.local = convertNode(node, scope, buffer[position], buffer);
  14997. },
  14998. function importSpecifier(node, position, buffer) {
  14999. const { scope } = node;
  15000. const importedPosition = buffer[position];
  15001. node.local = convertNode(node, scope, buffer[position + 1], buffer);
  15002. node.imported =
  15003. importedPosition === 0 ? node.local : convertNode(node, scope, importedPosition, buffer);
  15004. },
  15005. function jsxAttribute(node, position, buffer) {
  15006. const { scope } = node;
  15007. node.name = convertNode(node, scope, buffer[position], buffer);
  15008. const valuePosition = buffer[position + 1];
  15009. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  15010. },
  15011. function jsxClosingElement(node, position, buffer) {
  15012. const { scope } = node;
  15013. node.name = convertNode(node, scope, buffer[position], buffer);
  15014. },
  15015. function jsxClosingFragment() { },
  15016. function jsxElement(node, position, buffer) {
  15017. const { scope } = node;
  15018. node.openingElement = convertNode(node, scope, buffer[position], buffer);
  15019. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  15020. const closingElementPosition = buffer[position + 2];
  15021. node.closingElement =
  15022. closingElementPosition === 0
  15023. ? null
  15024. : convertNode(node, scope, closingElementPosition, buffer);
  15025. },
  15026. function jsxEmptyExpression() { },
  15027. function jsxExpressionContainer(node, position, buffer) {
  15028. const { scope } = node;
  15029. node.expression = convertNode(node, scope, buffer[position], buffer);
  15030. },
  15031. function jsxFragment(node, position, buffer) {
  15032. const { scope } = node;
  15033. node.openingFragment = convertNode(node, scope, buffer[position], buffer);
  15034. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  15035. node.closingFragment = convertNode(node, scope, buffer[position + 2], buffer);
  15036. },
  15037. function jsxIdentifier(node, position, buffer) {
  15038. node.name = buffer.convertString(buffer[position]);
  15039. },
  15040. function jsxMemberExpression(node, position, buffer) {
  15041. const { scope } = node;
  15042. node.object = convertNode(node, scope, buffer[position], buffer);
  15043. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  15044. },
  15045. function jsxNamespacedName(node, position, buffer) {
  15046. const { scope } = node;
  15047. node.namespace = convertNode(node, scope, buffer[position], buffer);
  15048. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  15049. },
  15050. function jsxOpeningElement(node, position, buffer) {
  15051. const { scope } = node;
  15052. const flags = buffer[position];
  15053. node.selfClosing = (flags & 1) === 1;
  15054. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  15055. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15056. },
  15057. function jsxOpeningFragment(node) {
  15058. node.attributes = [];
  15059. node.selfClosing = false;
  15060. },
  15061. function jsxSpreadAttribute(node, position, buffer) {
  15062. const { scope } = node;
  15063. node.argument = convertNode(node, scope, buffer[position], buffer);
  15064. },
  15065. function jsxSpreadChild(node, position, buffer) {
  15066. const { scope } = node;
  15067. node.expression = convertNode(node, scope, buffer[position], buffer);
  15068. },
  15069. function jsxText(node, position, buffer) {
  15070. node.value = buffer.convertString(buffer[position]);
  15071. node.raw = buffer.convertString(buffer[position + 1]);
  15072. },
  15073. function labeledStatement(node, position, buffer) {
  15074. const { scope } = node;
  15075. node.label = convertNode(node, scope, buffer[position], buffer);
  15076. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  15077. },
  15078. function literalBigInt(node, position, buffer) {
  15079. const bigint = (node.bigint = buffer.convertString(buffer[position]));
  15080. node.raw = buffer.convertString(buffer[position + 1]);
  15081. node.value = BigInt(bigint);
  15082. },
  15083. function literalBoolean(node, position, buffer) {
  15084. const flags = buffer[position];
  15085. const value = (node.value = (flags & 1) === 1);
  15086. node.raw = value ? 'true' : 'false';
  15087. },
  15088. function literalNull(node) {
  15089. node.value = null;
  15090. },
  15091. function literalNumber(node, position, buffer) {
  15092. const rawPosition = buffer[position];
  15093. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  15094. node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
  15095. },
  15096. function literalRegExp(node, position, buffer) {
  15097. const flags = buffer.convertString(buffer[position]);
  15098. const pattern = buffer.convertString(buffer[position + 1]);
  15099. node.raw = `/${pattern}/${flags}`;
  15100. node.regex = { flags, pattern };
  15101. node.value = new RegExp(pattern, flags);
  15102. },
  15103. function literalString(node, position, buffer) {
  15104. node.value = buffer.convertString(buffer[position]);
  15105. const rawPosition = buffer[position + 1];
  15106. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  15107. },
  15108. function logicalExpression(node, position, buffer) {
  15109. const { scope } = node;
  15110. node.operator = FIXED_STRINGS[buffer[position]];
  15111. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15112. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15113. },
  15114. function memberExpression(node, position, buffer) {
  15115. const { scope } = node;
  15116. const flags = buffer[position];
  15117. node.computed = (flags & 1) === 1;
  15118. node.optional = (flags & 2) === 2;
  15119. node.object = convertNode(node, scope, buffer[position + 1], buffer);
  15120. node.property = convertNode(node, scope, buffer[position + 2], buffer);
  15121. },
  15122. function metaProperty(node, position, buffer) {
  15123. const { scope } = node;
  15124. node.meta = convertNode(node, scope, buffer[position], buffer);
  15125. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  15126. },
  15127. function methodDefinition(node, position, buffer) {
  15128. const { scope } = node;
  15129. const flags = buffer[position];
  15130. node.static = (flags & 1) === 1;
  15131. node.computed = (flags & 2) === 2;
  15132. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  15133. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  15134. node.value = convertNode(node, scope, buffer[position + 3], buffer);
  15135. node.kind = FIXED_STRINGS[buffer[position + 4]];
  15136. },
  15137. function newExpression(node, position, buffer) {
  15138. const { scope } = node;
  15139. node.annotations = convertAnnotations(buffer[position], buffer);
  15140. node.callee = convertNode(node, scope, buffer[position + 1], buffer);
  15141. node.arguments = convertNodeList(node, scope, buffer[position + 2], buffer);
  15142. },
  15143. function objectExpression(node, position, buffer) {
  15144. const { scope } = node;
  15145. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  15146. },
  15147. function objectPattern(node, position, buffer) {
  15148. const { scope } = node;
  15149. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  15150. },
  15151. function privateIdentifier(node, position, buffer) {
  15152. node.name = buffer.convertString(buffer[position]);
  15153. },
  15154. function program(node, position, buffer) {
  15155. const { scope } = node;
  15156. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15157. node.invalidAnnotations = convertAnnotations(buffer[position + 1], buffer);
  15158. },
  15159. function property(node, position, buffer) {
  15160. const { scope } = node;
  15161. const flags = buffer[position];
  15162. node.method = (flags & 1) === 1;
  15163. node.shorthand = (flags & 2) === 2;
  15164. node.computed = (flags & 4) === 4;
  15165. const keyPosition = buffer[position + 1];
  15166. node.value = convertNode(node, scope, buffer[position + 2], buffer);
  15167. node.kind = FIXED_STRINGS[buffer[position + 3]];
  15168. node.key = keyPosition === 0 ? node.value : convertNode(node, scope, keyPosition, buffer);
  15169. },
  15170. function propertyDefinition(node, position, buffer) {
  15171. const { scope } = node;
  15172. const flags = buffer[position];
  15173. node.static = (flags & 1) === 1;
  15174. node.computed = (flags & 2) === 2;
  15175. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  15176. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  15177. const valuePosition = buffer[position + 3];
  15178. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  15179. },
  15180. function restElement(node, position, buffer) {
  15181. const { scope } = node;
  15182. node.argument = convertNode(node, scope, buffer[position], buffer);
  15183. },
  15184. function returnStatement(node, position, buffer) {
  15185. const { scope } = node;
  15186. const argumentPosition = buffer[position];
  15187. node.argument =
  15188. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  15189. },
  15190. function sequenceExpression(node, position, buffer) {
  15191. const { scope } = node;
  15192. node.expressions = convertNodeList(node, scope, buffer[position], buffer);
  15193. },
  15194. function spreadElement(node, position, buffer) {
  15195. const { scope } = node;
  15196. node.argument = convertNode(node, scope, buffer[position], buffer);
  15197. },
  15198. function staticBlock(node, position, buffer) {
  15199. const { scope } = node;
  15200. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15201. },
  15202. function superElement() { },
  15203. function switchCase(node, position, buffer) {
  15204. const { scope } = node;
  15205. const testPosition = buffer[position];
  15206. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  15207. node.consequent = convertNodeList(node, scope, buffer[position + 1], buffer);
  15208. },
  15209. function switchStatement(node, position, buffer) {
  15210. const { scope } = node;
  15211. node.discriminant = convertNode(node, node.parentScope, buffer[position], buffer);
  15212. node.cases = convertNodeList(node, scope, buffer[position + 1], buffer);
  15213. },
  15214. function taggedTemplateExpression(node, position, buffer) {
  15215. const { scope } = node;
  15216. node.tag = convertNode(node, scope, buffer[position], buffer);
  15217. node.quasi = convertNode(node, scope, buffer[position + 1], buffer);
  15218. },
  15219. function templateElement(node, position, buffer) {
  15220. const flags = buffer[position];
  15221. node.tail = (flags & 1) === 1;
  15222. const cookedPosition = buffer[position + 1];
  15223. const cooked = cookedPosition === 0 ? undefined : buffer.convertString(cookedPosition);
  15224. const raw = buffer.convertString(buffer[position + 2]);
  15225. node.value = { cooked, raw };
  15226. },
  15227. function templateLiteral(node, position, buffer) {
  15228. const { scope } = node;
  15229. node.quasis = convertNodeList(node, scope, buffer[position], buffer);
  15230. node.expressions = convertNodeList(node, scope, buffer[position + 1], buffer);
  15231. },
  15232. function thisExpression() { },
  15233. function throwStatement(node, position, buffer) {
  15234. const { scope } = node;
  15235. node.argument = convertNode(node, scope, buffer[position], buffer);
  15236. },
  15237. function tryStatement(node, position, buffer) {
  15238. const { scope } = node;
  15239. node.block = convertNode(node, scope, buffer[position], buffer);
  15240. const handlerPosition = buffer[position + 1];
  15241. node.handler = handlerPosition === 0 ? null : convertNode(node, scope, handlerPosition, buffer);
  15242. const finalizerPosition = buffer[position + 2];
  15243. node.finalizer =
  15244. finalizerPosition === 0 ? null : convertNode(node, scope, finalizerPosition, buffer);
  15245. },
  15246. function unaryExpression(node, position, buffer) {
  15247. const { scope } = node;
  15248. node.operator = FIXED_STRINGS[buffer[position]];
  15249. node.argument = convertNode(node, scope, buffer[position + 1], buffer);
  15250. },
  15251. function updateExpression(node, position, buffer) {
  15252. const { scope } = node;
  15253. const flags = buffer[position];
  15254. node.prefix = (flags & 1) === 1;
  15255. node.operator = FIXED_STRINGS[buffer[position + 1]];
  15256. node.argument = convertNode(node, scope, buffer[position + 2], buffer);
  15257. },
  15258. function variableDeclaration(node, position, buffer) {
  15259. const { scope } = node;
  15260. node.kind = FIXED_STRINGS[buffer[position]];
  15261. node.declarations = convertNodeList(node, scope, buffer[position + 1], buffer);
  15262. },
  15263. function variableDeclarator(node, position, buffer) {
  15264. const { scope } = node;
  15265. node.id = convertNode(node, scope, buffer[position], buffer);
  15266. const initPosition = buffer[position + 1];
  15267. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  15268. },
  15269. function whileStatement(node, position, buffer) {
  15270. const { scope } = node;
  15271. node.test = convertNode(node, scope, buffer[position], buffer);
  15272. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  15273. },
  15274. function yieldExpression(node, position, buffer) {
  15275. const { scope } = node;
  15276. const flags = buffer[position];
  15277. node.delegate = (flags & 1) === 1;
  15278. const argumentPosition = buffer[position + 1];
  15279. node.argument =
  15280. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  15281. }
  15282. ];
  15283. function convertNode(parent, parentScope, position, buffer) {
  15284. const nodeType = buffer[position];
  15285. const NodeConstructor = nodeConstructors$1[nodeType];
  15286. /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
  15287. if (!NodeConstructor) {
  15288. console.trace();
  15289. throw new Error(`Unknown node type: ${nodeType}`);
  15290. }
  15291. const node = new NodeConstructor(parent, parentScope);
  15292. node.type = nodeTypeStrings[nodeType];
  15293. node.start = buffer[position + 1];
  15294. node.end = buffer[position + 2];
  15295. bufferParsers[nodeType](node, position + 3, buffer);
  15296. node.initialise();
  15297. return node;
  15298. }
  15299. function convertNodeList(parent, parentScope, position, buffer) {
  15300. if (position === 0)
  15301. return EMPTY_ARRAY;
  15302. const length = buffer[position++];
  15303. const list = new Array(length);
  15304. for (let index = 0; index < length; index++) {
  15305. const nodePosition = buffer[position++];
  15306. list[index] = nodePosition ? convertNode(parent, parentScope, nodePosition, buffer) : null;
  15307. }
  15308. return list;
  15309. }
  15310. class UnknownNode extends NodeBase {
  15311. hasEffects() {
  15312. return true;
  15313. }
  15314. include(context) {
  15315. super.include(context, true);
  15316. }
  15317. }
  15318. // This file is generated by scripts/generate-node-index.js.
  15319. // Do not edit this file directly.
  15320. const nodeConstructors = {
  15321. ArrayExpression,
  15322. ArrayPattern,
  15323. ArrowFunctionExpression,
  15324. AssignmentExpression,
  15325. AssignmentPattern,
  15326. AwaitExpression,
  15327. BinaryExpression,
  15328. BlockStatement,
  15329. BreakStatement,
  15330. CallExpression,
  15331. CatchClause,
  15332. ChainExpression,
  15333. ClassBody,
  15334. ClassDeclaration,
  15335. ClassExpression,
  15336. ConditionalExpression,
  15337. ContinueStatement,
  15338. DebuggerStatement,
  15339. Decorator,
  15340. DoWhileStatement,
  15341. EmptyStatement,
  15342. ExportAllDeclaration,
  15343. ExportDefaultDeclaration,
  15344. ExportNamedDeclaration,
  15345. ExportSpecifier,
  15346. ExpressionStatement,
  15347. ForInStatement,
  15348. ForOfStatement,
  15349. ForStatement,
  15350. FunctionDeclaration,
  15351. FunctionExpression,
  15352. Identifier,
  15353. IfStatement,
  15354. ImportAttribute,
  15355. ImportDeclaration,
  15356. ImportDefaultSpecifier,
  15357. ImportExpression,
  15358. ImportNamespaceSpecifier,
  15359. ImportSpecifier,
  15360. JSXAttribute,
  15361. JSXClosingElement,
  15362. JSXClosingFragment,
  15363. JSXElement,
  15364. JSXEmptyExpression,
  15365. JSXExpressionContainer,
  15366. JSXFragment,
  15367. JSXIdentifier,
  15368. JSXMemberExpression,
  15369. JSXNamespacedName,
  15370. JSXOpeningElement,
  15371. JSXOpeningFragment,
  15372. JSXSpreadAttribute,
  15373. JSXSpreadChild,
  15374. JSXText,
  15375. LabeledStatement,
  15376. Literal,
  15377. LogicalExpression,
  15378. MemberExpression,
  15379. MetaProperty,
  15380. MethodDefinition,
  15381. NewExpression,
  15382. ObjectExpression,
  15383. ObjectPattern,
  15384. PanicError,
  15385. ParseError,
  15386. PrivateIdentifier,
  15387. Program,
  15388. Property,
  15389. PropertyDefinition,
  15390. RestElement,
  15391. ReturnStatement,
  15392. SequenceExpression,
  15393. SpreadElement,
  15394. StaticBlock,
  15395. Super,
  15396. SwitchCase,
  15397. SwitchStatement,
  15398. TaggedTemplateExpression,
  15399. TemplateElement,
  15400. TemplateLiteral,
  15401. ThisExpression,
  15402. ThrowStatement,
  15403. TryStatement,
  15404. UnaryExpression,
  15405. UnknownNode,
  15406. UpdateExpression,
  15407. VariableDeclaration,
  15408. VariableDeclarator,
  15409. WhileStatement,
  15410. YieldExpression
  15411. };
  15412. class ExportShimVariable extends Variable {
  15413. constructor(module) {
  15414. super(MISSING_EXPORT_SHIM_VARIABLE);
  15415. this.module = module;
  15416. }
  15417. includePath(path, context) {
  15418. super.includePath(path, context);
  15419. this.module.needsExportShim = true;
  15420. }
  15421. }
  15422. var BuildPhase;
  15423. (function (BuildPhase) {
  15424. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  15425. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  15426. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  15427. })(BuildPhase || (BuildPhase = {}));
  15428. const sourceMapCache = new WeakMap();
  15429. /**
  15430. * This clears the decoded array and falls back to the encoded string form.
  15431. * Sourcemap mappings arrays can be very large and holding on to them for longer
  15432. * than is necessary leads to poor heap utilization.
  15433. */
  15434. function resetCacheToEncoded(cache) {
  15435. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  15436. cache.encodedMappings = encode(cache.decodedMappings);
  15437. }
  15438. cache.decodedMappings = undefined;
  15439. }
  15440. function resetSourcemapCache(map, sourcemapChain) {
  15441. if (map) {
  15442. const cache = sourceMapCache.get(map);
  15443. if (cache) {
  15444. resetCacheToEncoded(cache);
  15445. }
  15446. }
  15447. if (!sourcemapChain) {
  15448. return;
  15449. }
  15450. for (const map of sourcemapChain) {
  15451. if (map.missing)
  15452. continue;
  15453. resetSourcemapCache(map);
  15454. }
  15455. }
  15456. function decodedSourcemap(map) {
  15457. if (!map)
  15458. return null;
  15459. if (typeof map === 'string') {
  15460. map = JSON.parse(map);
  15461. }
  15462. if (!map.mappings) {
  15463. return {
  15464. mappings: [],
  15465. names: [],
  15466. sources: [],
  15467. version: 3
  15468. };
  15469. }
  15470. const originalMappings = map.mappings;
  15471. const isAlreadyDecoded = Array.isArray(originalMappings);
  15472. const cache = {
  15473. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  15474. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  15475. };
  15476. const decodedMap = {
  15477. ...map,
  15478. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  15479. // where the mappings field is never actually accessed. This appears to greatly reduce
  15480. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  15481. get mappings() {
  15482. if (cache.decodedMappings) {
  15483. return cache.decodedMappings;
  15484. }
  15485. // If decodedMappings doesn't exist then encodedMappings should.
  15486. // The only scenario where cache.encodedMappings should be undefined is if the map
  15487. // this was constructed from was already decoded, or if mappings was set to a new
  15488. // decoded string. In either case, this line shouldn't get hit.
  15489. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  15490. cache.encodedMappings = undefined;
  15491. return cache.decodedMappings;
  15492. }
  15493. };
  15494. sourceMapCache.set(decodedMap, cache);
  15495. return decodedMap;
  15496. }
  15497. function getId(m) {
  15498. return m.id;
  15499. }
  15500. function getOriginalLocation(sourcemapChain, location) {
  15501. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  15502. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  15503. const sourcemap = filteredSourcemapChain.pop();
  15504. const line = sourcemap.mappings[location.line - 1];
  15505. if (line) {
  15506. const filteredLine = line.filter((segment) => segment.length > 1);
  15507. const lastSegment = filteredLine[filteredLine.length - 1];
  15508. for (const segment of filteredLine) {
  15509. if (segment[0] >= location.column || segment === lastSegment) {
  15510. location = {
  15511. column: segment[3],
  15512. line: segment[2] + 1
  15513. };
  15514. continue traceSourcemap;
  15515. }
  15516. }
  15517. }
  15518. throw new Error("Can't resolve original location of error.");
  15519. }
  15520. return location;
  15521. }
  15522. const ATTRIBUTE_KEYWORDS = new Set(['assert', 'with']);
  15523. function getAttributesFromImportExpression(node) {
  15524. const { scope: { context }, options, start } = node;
  15525. if (!(options instanceof ObjectExpression)) {
  15526. if (options) {
  15527. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), start);
  15528. }
  15529. return EMPTY_OBJECT;
  15530. }
  15531. const assertProperty = options.properties.find((property) => ATTRIBUTE_KEYWORDS.has(getPropertyKey(property)))?.value;
  15532. if (!assertProperty) {
  15533. return EMPTY_OBJECT;
  15534. }
  15535. if (!(assertProperty instanceof ObjectExpression)) {
  15536. context.module.log(LOGLEVEL_WARN, logImportOptionsAreInvalid(context.module.id), start);
  15537. return EMPTY_OBJECT;
  15538. }
  15539. const assertFields = assertProperty.properties
  15540. .map(property => {
  15541. const key = getPropertyKey(property);
  15542. if (typeof key === 'string' &&
  15543. typeof property.value.value === 'string') {
  15544. return [key, property.value.value];
  15545. }
  15546. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), property.start);
  15547. return null;
  15548. })
  15549. .filter((property) => !!property);
  15550. if (assertFields.length > 0) {
  15551. return Object.fromEntries(assertFields);
  15552. }
  15553. return EMPTY_OBJECT;
  15554. }
  15555. const getPropertyKey = (property) => {
  15556. const key = property.key;
  15557. return (key &&
  15558. !property.computed &&
  15559. (key.name || key.value));
  15560. };
  15561. function getAttributesFromImportExportDeclaration(attributes) {
  15562. return attributes?.length
  15563. ? Object.fromEntries(attributes.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  15564. : EMPTY_OBJECT;
  15565. }
  15566. function doAttributesDiffer(assertionA, assertionB) {
  15567. const keysA = Object.keys(assertionA);
  15568. return (keysA.length !== Object.keys(assertionB).length ||
  15569. keysA.some(key => assertionA[key] !== assertionB[key]));
  15570. }
  15571. let timers = new Map();
  15572. function getPersistedLabel(label, level) {
  15573. switch (level) {
  15574. case 1: {
  15575. return `# ${label}`;
  15576. }
  15577. case 2: {
  15578. return `## ${label}`;
  15579. }
  15580. case 3: {
  15581. return label;
  15582. }
  15583. default: {
  15584. return `- ${label}`;
  15585. }
  15586. }
  15587. }
  15588. function timeStartImpl(label, level = 3) {
  15589. label = getPersistedLabel(label, level);
  15590. const startMemory = process$1.memoryUsage().heapUsed;
  15591. const startTime = performance.now();
  15592. const timer = timers.get(label);
  15593. if (timer === undefined) {
  15594. timers.set(label, {
  15595. memory: 0,
  15596. startMemory,
  15597. startTime,
  15598. time: 0,
  15599. totalMemory: 0
  15600. });
  15601. }
  15602. else {
  15603. timer.startMemory = startMemory;
  15604. timer.startTime = startTime;
  15605. }
  15606. }
  15607. function timeEndImpl(label, level = 3) {
  15608. label = getPersistedLabel(label, level);
  15609. const timer = timers.get(label);
  15610. if (timer !== undefined) {
  15611. const currentMemory = process$1.memoryUsage().heapUsed;
  15612. timer.memory += currentMemory - timer.startMemory;
  15613. timer.time += performance.now() - timer.startTime;
  15614. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  15615. }
  15616. }
  15617. function getTimings() {
  15618. const newTimings = {};
  15619. for (const [label, { memory, time, totalMemory }] of timers) {
  15620. newTimings[label] = [time, memory, totalMemory];
  15621. }
  15622. return newTimings;
  15623. }
  15624. let timeStart = doNothing;
  15625. let timeEnd = doNothing;
  15626. const TIMED_PLUGIN_HOOKS = [
  15627. 'augmentChunkHash',
  15628. 'buildEnd',
  15629. 'buildStart',
  15630. 'generateBundle',
  15631. 'load',
  15632. 'moduleParsed',
  15633. 'options',
  15634. 'outputOptions',
  15635. 'renderChunk',
  15636. 'renderDynamicImport',
  15637. 'renderStart',
  15638. 'resolveDynamicImport',
  15639. 'resolveFileUrl',
  15640. 'resolveId',
  15641. 'resolveImportMeta',
  15642. 'shouldTransformCachedModule',
  15643. 'transform',
  15644. 'writeBundle'
  15645. ];
  15646. function getPluginWithTimers(plugin, index) {
  15647. if (plugin._hasTimer)
  15648. return plugin;
  15649. plugin._hasTimer = true;
  15650. for (const hook of TIMED_PLUGIN_HOOKS) {
  15651. if (hook in plugin) {
  15652. let timerLabel = `plugin ${index}`;
  15653. if (plugin.name) {
  15654. timerLabel += ` (${plugin.name})`;
  15655. }
  15656. timerLabel += ` - ${hook}`;
  15657. const handler = function (...parameters) {
  15658. timeStart(timerLabel, 4);
  15659. const result = hookFunction.apply(this, parameters);
  15660. timeEnd(timerLabel, 4);
  15661. return result;
  15662. };
  15663. let hookFunction;
  15664. if (typeof plugin[hook].handler === 'function') {
  15665. hookFunction = plugin[hook].handler;
  15666. plugin[hook].handler = handler;
  15667. }
  15668. else {
  15669. hookFunction = plugin[hook];
  15670. plugin[hook] = handler;
  15671. }
  15672. }
  15673. }
  15674. return plugin;
  15675. }
  15676. function initialiseTimers(inputOptions) {
  15677. if (inputOptions.perf) {
  15678. timers = new Map();
  15679. timeStart = timeStartImpl;
  15680. timeEnd = timeEndImpl;
  15681. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  15682. }
  15683. else {
  15684. timeStart = doNothing;
  15685. timeEnd = doNothing;
  15686. }
  15687. }
  15688. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  15689. identifier: null,
  15690. localName: MISSING_EXPORT_SHIM_VARIABLE
  15691. };
  15692. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  15693. const searchedModules = searchedNamesAndModules.get(name);
  15694. if (searchedModules) {
  15695. if (searchedModules.has(target)) {
  15696. return isExportAllSearch ? [null] : error(logCircularReexport(name, target.id));
  15697. }
  15698. searchedModules.add(target);
  15699. }
  15700. else {
  15701. searchedNamesAndModules.set(name, new Set([target]));
  15702. }
  15703. return target.getVariableForExportName(name, {
  15704. importerForSideEffects,
  15705. isExportAllSearch,
  15706. searchedNamesAndModules
  15707. });
  15708. }
  15709. function getAndExtendSideEffectModules(variable, module) {
  15710. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  15711. let currentVariable = variable;
  15712. const referencedVariables = new Set([currentVariable]);
  15713. while (true) {
  15714. const importingModule = currentVariable.module;
  15715. currentVariable =
  15716. currentVariable instanceof ExportDefaultVariable
  15717. ? currentVariable.getDirectOriginalVariable()
  15718. : currentVariable instanceof SyntheticNamedExportVariable
  15719. ? currentVariable.syntheticNamespace
  15720. : null;
  15721. if (!currentVariable || referencedVariables.has(currentVariable)) {
  15722. break;
  15723. }
  15724. referencedVariables.add(currentVariable);
  15725. sideEffectModules.add(importingModule);
  15726. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  15727. if (originalSideEffects) {
  15728. for (const module of originalSideEffects) {
  15729. sideEffectModules.add(module);
  15730. }
  15731. }
  15732. }
  15733. return sideEffectModules;
  15734. }
  15735. class Module {
  15736. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
  15737. this.graph = graph;
  15738. this.id = id;
  15739. this.options = options;
  15740. this.alternativeReexportModules = new Map();
  15741. this.chunkFileNames = new Set();
  15742. this.chunkNames = [];
  15743. this.cycles = new Set();
  15744. this.dependencies = new Set();
  15745. this.dynamicDependencies = new Set();
  15746. this.dynamicImporters = [];
  15747. this.dynamicImports = [];
  15748. this.execIndex = Infinity;
  15749. this.hasTreeShakingPassStarted = false;
  15750. this.implicitlyLoadedAfter = new Set();
  15751. this.implicitlyLoadedBefore = new Set();
  15752. this.importDescriptions = new Map();
  15753. this.importMetas = [];
  15754. this.importedFromNotTreeshaken = false;
  15755. this.importers = [];
  15756. this.includedDynamicImporters = [];
  15757. this.includedDirectTopLevelAwaitingDynamicImporters = new Set();
  15758. this.includedImports = new Set();
  15759. this.isExecuted = false;
  15760. this.isUserDefinedEntryPoint = false;
  15761. this.needsExportShim = false;
  15762. this.sideEffectDependenciesByVariable = new Map();
  15763. this.sourcesWithAttributes = new Map();
  15764. this.allExportNames = null;
  15765. this.allExportsIncluded = false;
  15766. this.ast = null;
  15767. this.exportAllModules = [];
  15768. this.exportAllSources = new Set();
  15769. this.exportNamesByVariable = null;
  15770. this.exportShimVariable = new ExportShimVariable(this);
  15771. this.exports = new Map();
  15772. this.namespaceReexportsByName = new Map();
  15773. this.reexportDescriptions = new Map();
  15774. this.relevantDependencies = null;
  15775. this.syntheticExports = new Map();
  15776. this.syntheticNamespace = null;
  15777. this.transformDependencies = [];
  15778. this.transitiveReexports = null;
  15779. this.excludeFromSourcemap = /\0/.test(id);
  15780. this.context = options.moduleContext(id);
  15781. this.preserveSignature = this.options.preserveEntrySignatures;
  15782. // eslint-disable-next-line @typescript-eslint/no-this-alias
  15783. const module = this;
  15784. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
  15785. this.info = {
  15786. ast: null,
  15787. attributes,
  15788. code: null,
  15789. get dynamicallyImportedIdResolutions() {
  15790. return dynamicImports
  15791. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  15792. .filter(Boolean);
  15793. },
  15794. get dynamicallyImportedIds() {
  15795. // We cannot use this.dynamicDependencies because this is needed before
  15796. // dynamicDependencies are populated
  15797. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  15798. },
  15799. get dynamicImporters() {
  15800. return dynamicImporters.sort();
  15801. },
  15802. get exportedBindings() {
  15803. const exportBindings = { '.': [...exports.keys()] };
  15804. for (const [name, { source }] of reexportDescriptions) {
  15805. (exportBindings[source] ??= []).push(name);
  15806. }
  15807. for (const source of exportAllSources) {
  15808. (exportBindings[source] ??= []).push('*');
  15809. }
  15810. return exportBindings;
  15811. },
  15812. get exports() {
  15813. return [
  15814. ...exports.keys(),
  15815. ...reexportDescriptions.keys(),
  15816. ...[...exportAllSources].map(() => '*')
  15817. ];
  15818. },
  15819. get hasDefaultExport() {
  15820. // This information is only valid after parsing
  15821. if (!module.ast) {
  15822. return null;
  15823. }
  15824. return module.exports.has('default') || reexportDescriptions.has('default');
  15825. },
  15826. id,
  15827. get implicitlyLoadedAfterOneOf() {
  15828. return Array.from(implicitlyLoadedAfter, getId).sort();
  15829. },
  15830. get implicitlyLoadedBefore() {
  15831. return Array.from(implicitlyLoadedBefore, getId).sort();
  15832. },
  15833. get importedIdResolutions() {
  15834. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
  15835. },
  15836. get importedIds() {
  15837. // We cannot use this.dependencies because this is needed before
  15838. // dependencies are populated
  15839. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  15840. },
  15841. get importers() {
  15842. return importers.sort();
  15843. },
  15844. isEntry,
  15845. isExternal: false,
  15846. get isIncluded() {
  15847. if (graph.phase !== BuildPhase.GENERATE) {
  15848. return null;
  15849. }
  15850. return module.isIncluded();
  15851. },
  15852. meta: { ...meta },
  15853. moduleSideEffects,
  15854. syntheticNamedExports
  15855. };
  15856. }
  15857. basename() {
  15858. const base = basename(this.id);
  15859. const extension = extname(this.id);
  15860. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  15861. }
  15862. bindReferences() {
  15863. this.ast.bind();
  15864. }
  15865. cacheInfoGetters() {
  15866. cacheObjectGetters(this.info, [
  15867. 'dynamicallyImportedIdResolutions',
  15868. 'dynamicallyImportedIds',
  15869. 'dynamicImporters',
  15870. 'exportedBindings',
  15871. 'exports',
  15872. 'hasDefaultExport',
  15873. 'implicitlyLoadedAfterOneOf',
  15874. 'implicitlyLoadedBefore',
  15875. 'importedIdResolutions',
  15876. 'importedIds',
  15877. 'importers'
  15878. ]);
  15879. }
  15880. error(properties, pos) {
  15881. if (pos !== undefined) {
  15882. this.addLocationToLogProps(properties, pos);
  15883. }
  15884. return error(properties);
  15885. }
  15886. // sum up the length of all ast nodes that are included
  15887. estimateSize() {
  15888. let size = 0;
  15889. for (const node of this.ast.body) {
  15890. if (node.included) {
  15891. size += node.end - node.start;
  15892. }
  15893. }
  15894. return size;
  15895. }
  15896. getAllExportNames() {
  15897. if (this.allExportNames) {
  15898. return this.allExportNames;
  15899. }
  15900. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  15901. for (const module of this.exportAllModules) {
  15902. if (module instanceof ExternalModule) {
  15903. this.allExportNames.add(`*${module.id}`);
  15904. continue;
  15905. }
  15906. for (const name of module.getAllExportNames()) {
  15907. if (name !== 'default')
  15908. this.allExportNames.add(name);
  15909. }
  15910. }
  15911. // We do not count the synthetic namespace as a regular export to hide it
  15912. // from entry signatures and namespace objects
  15913. if (typeof this.info.syntheticNamedExports === 'string') {
  15914. this.allExportNames.delete(this.info.syntheticNamedExports);
  15915. }
  15916. return this.allExportNames;
  15917. }
  15918. getDependenciesToBeIncluded() {
  15919. if (this.relevantDependencies)
  15920. return this.relevantDependencies;
  15921. this.relevantDependencies = new Set();
  15922. const necessaryDependencies = new Set();
  15923. const alwaysCheckedDependencies = new Set();
  15924. const dependencyVariables = new Set(this.includedImports);
  15925. if (this.info.isEntry ||
  15926. this.includedDynamicImporters.length > 0 ||
  15927. this.namespace.included ||
  15928. this.implicitlyLoadedAfter.size > 0) {
  15929. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  15930. const [exportedVariable] = this.getVariableForExportName(exportName);
  15931. if (exportedVariable?.included) {
  15932. dependencyVariables.add(exportedVariable);
  15933. }
  15934. }
  15935. }
  15936. for (let variable of dependencyVariables) {
  15937. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  15938. if (sideEffectDependencies) {
  15939. for (const module of sideEffectDependencies) {
  15940. alwaysCheckedDependencies.add(module);
  15941. }
  15942. }
  15943. if (variable instanceof SyntheticNamedExportVariable) {
  15944. variable = variable.getBaseVariable();
  15945. }
  15946. else if (variable instanceof ExportDefaultVariable) {
  15947. variable = variable.getOriginalVariable();
  15948. }
  15949. necessaryDependencies.add(variable.module);
  15950. }
  15951. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  15952. for (const dependency of this.dependencies) {
  15953. this.relevantDependencies.add(dependency);
  15954. }
  15955. }
  15956. else {
  15957. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  15958. }
  15959. for (const dependency of necessaryDependencies) {
  15960. this.relevantDependencies.add(dependency);
  15961. }
  15962. return this.relevantDependencies;
  15963. }
  15964. getExportNamesByVariable() {
  15965. if (this.exportNamesByVariable) {
  15966. return this.exportNamesByVariable;
  15967. }
  15968. const exportNamesByVariable = new Map();
  15969. for (const exportName of this.getAllExportNames()) {
  15970. let [tracedVariable] = this.getVariableForExportName(exportName);
  15971. if (tracedVariable instanceof ExportDefaultVariable) {
  15972. tracedVariable = tracedVariable.getOriginalVariable();
  15973. }
  15974. if (!tracedVariable ||
  15975. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  15976. continue;
  15977. }
  15978. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  15979. if (existingExportNames) {
  15980. existingExportNames.push(exportName);
  15981. }
  15982. else {
  15983. exportNamesByVariable.set(tracedVariable, [exportName]);
  15984. }
  15985. }
  15986. return (this.exportNamesByVariable = exportNamesByVariable);
  15987. }
  15988. getExports() {
  15989. return [...this.exports.keys()];
  15990. }
  15991. getReexports() {
  15992. if (this.transitiveReexports) {
  15993. return this.transitiveReexports;
  15994. }
  15995. // to avoid infinite recursion when using circular `export * from X`
  15996. this.transitiveReexports = [];
  15997. const reexports = new Set(this.reexportDescriptions.keys());
  15998. for (const module of this.exportAllModules) {
  15999. if (module instanceof ExternalModule) {
  16000. reexports.add(`*${module.id}`);
  16001. }
  16002. else {
  16003. for (const name of [...module.getReexports(), ...module.getExports()]) {
  16004. if (name !== 'default')
  16005. reexports.add(name);
  16006. }
  16007. }
  16008. }
  16009. return (this.transitiveReexports = [...reexports]);
  16010. }
  16011. getRenderedExports() {
  16012. // only direct exports are counted here, not reexports at all
  16013. const renderedExports = [];
  16014. const removedExports = [];
  16015. for (const exportName of this.exports.keys()) {
  16016. const [variable] = this.getVariableForExportName(exportName);
  16017. (variable?.included ? renderedExports : removedExports).push(exportName);
  16018. }
  16019. return { removedExports, renderedExports };
  16020. }
  16021. getSyntheticNamespace() {
  16022. if (this.syntheticNamespace === null) {
  16023. this.syntheticNamespace = undefined;
  16024. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  16025. ? this.info.syntheticNamedExports
  16026. : 'default', { onlyExplicit: true });
  16027. }
  16028. if (!this.syntheticNamespace) {
  16029. return error(logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  16030. }
  16031. return this.syntheticNamespace;
  16032. }
  16033. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  16034. if (name[0] === '*') {
  16035. if (name.length === 1) {
  16036. // export * from './other'
  16037. return [this.namespace];
  16038. }
  16039. // export * from 'external'
  16040. const module = this.graph.modulesById.get(name.slice(1));
  16041. return module.getVariableForExportName('*');
  16042. }
  16043. // export { foo } from './other'
  16044. const reexportDeclaration = this.reexportDescriptions.get(name);
  16045. if (reexportDeclaration) {
  16046. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  16047. if (!variable) {
  16048. return this.error(logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  16049. }
  16050. if (importerForSideEffects) {
  16051. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  16052. if (this.info.moduleSideEffects) {
  16053. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  16054. }
  16055. }
  16056. return [variable];
  16057. }
  16058. const exportDeclaration = this.exports.get(name);
  16059. if (exportDeclaration) {
  16060. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  16061. return [this.exportShimVariable];
  16062. }
  16063. const name = exportDeclaration.localName;
  16064. const variable = this.traceVariable(name, {
  16065. importerForSideEffects,
  16066. searchedNamesAndModules
  16067. });
  16068. if (importerForSideEffects) {
  16069. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  16070. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  16071. }
  16072. return [variable];
  16073. }
  16074. if (onlyExplicit) {
  16075. return [null];
  16076. }
  16077. if (name !== 'default') {
  16078. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  16079. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  16080. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  16081. if (foundNamespaceReexport[0]) {
  16082. return foundNamespaceReexport;
  16083. }
  16084. }
  16085. if (this.info.syntheticNamedExports) {
  16086. return [
  16087. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  16088. ];
  16089. }
  16090. // we don't want to create shims when we are just
  16091. // probing export * modules for exports
  16092. if (!isExportAllSearch && this.options.shimMissingExports) {
  16093. this.shimMissingExport(name);
  16094. return [this.exportShimVariable];
  16095. }
  16096. return [null];
  16097. }
  16098. hasEffects() {
  16099. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  16100. }
  16101. include() {
  16102. const context = createInclusionContext();
  16103. if (this.ast.shouldBeIncluded(context))
  16104. this.ast.include(context, false);
  16105. }
  16106. includeAllExports(includeNamespaceMembers) {
  16107. if (includeNamespaceMembers) {
  16108. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  16109. }
  16110. if (this.allExportsIncluded)
  16111. return;
  16112. this.allExportsIncluded = true;
  16113. if (!this.isExecuted) {
  16114. markModuleAndImpureDependenciesAsExecuted(this);
  16115. this.graph.needsTreeshakingPass = true;
  16116. }
  16117. const inclusionContext = createInclusionContext();
  16118. for (const exportName of this.exports.keys()) {
  16119. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  16120. const variable = this.getVariableForExportName(exportName)[0];
  16121. if (!variable) {
  16122. return error(logMissingEntryExport(exportName, this.id));
  16123. }
  16124. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  16125. variable.deoptimizePath(UNKNOWN_PATH);
  16126. }
  16127. }
  16128. for (const name of this.getReexports()) {
  16129. const [variable] = this.getVariableForExportName(name);
  16130. if (variable) {
  16131. variable.deoptimizePath(UNKNOWN_PATH);
  16132. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  16133. if (variable instanceof ExternalVariable) {
  16134. variable.module.reexported = true;
  16135. }
  16136. }
  16137. }
  16138. }
  16139. includeAllInBundle() {
  16140. this.ast.include(createInclusionContext(), true);
  16141. this.includeAllExports(false);
  16142. }
  16143. includeExportsByNames(names) {
  16144. if (!this.isExecuted) {
  16145. markModuleAndImpureDependenciesAsExecuted(this);
  16146. this.graph.needsTreeshakingPass = true;
  16147. }
  16148. let includeNamespaceMembers = false;
  16149. const inclusionContext = createInclusionContext();
  16150. for (const name of names) {
  16151. const variable = this.getVariableForExportName(name)[0];
  16152. if (variable) {
  16153. variable.deoptimizePath(UNKNOWN_PATH);
  16154. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  16155. }
  16156. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  16157. includeNamespaceMembers = true;
  16158. }
  16159. }
  16160. if (includeNamespaceMembers) {
  16161. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  16162. }
  16163. }
  16164. isIncluded() {
  16165. // Modules where this.ast is missing have been loaded via this.load and are
  16166. // not yet fully processed, hence they cannot be included.
  16167. return (this.ast &&
  16168. (this.ast.included ||
  16169. this.namespace.included ||
  16170. this.importedFromNotTreeshaken ||
  16171. this.exportShimVariable.included));
  16172. }
  16173. linkImports() {
  16174. this.addModulesToImportDescriptions(this.importDescriptions);
  16175. this.addModulesToImportDescriptions(this.reexportDescriptions);
  16176. const externalExportAllModules = [];
  16177. for (const source of this.exportAllSources) {
  16178. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  16179. if (module instanceof ExternalModule) {
  16180. externalExportAllModules.push(module);
  16181. continue;
  16182. }
  16183. this.exportAllModules.push(module);
  16184. }
  16185. this.exportAllModules.push(...externalExportAllModules);
  16186. }
  16187. log(level, properties, pos) {
  16188. this.addLocationToLogProps(properties, pos);
  16189. this.options.onLog(level, properties);
  16190. }
  16191. render(options) {
  16192. const source = this.magicString.clone();
  16193. this.ast.render(source, options);
  16194. source.trim();
  16195. const { usesTopLevelAwait } = this.astContext;
  16196. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  16197. return error(logInvalidFormatForTopLevelAwait(this.id, options.format));
  16198. }
  16199. return { source, usesTopLevelAwait };
  16200. }
  16201. async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  16202. timeStart('generate ast', 3);
  16203. if (code.startsWith('#!')) {
  16204. const shebangEndPosition = code.indexOf('\n');
  16205. this.shebang = code.slice(2, shebangEndPosition);
  16206. }
  16207. this.info.code = code;
  16208. this.originalCode = originalCode;
  16209. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  16210. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  16211. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  16212. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  16213. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  16214. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  16215. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  16216. if (transformFiles) {
  16217. this.transformFiles = transformFiles;
  16218. }
  16219. this.transformDependencies = transformDependencies;
  16220. this.customTransformCache = customTransformCache;
  16221. this.updateOptions(moduleOptions);
  16222. this.resolvedIds = resolvedIds ?? Object.create(null);
  16223. // By default, `id` is the file name. Custom resolvers and loaders
  16224. // can change that, but it makes sense to use it for the source file name
  16225. const fileName = this.id;
  16226. this.magicString = new MagicString(code, {
  16227. filename: (this.excludeFromSourcemap ? null : fileName), // don't include plugin helpers in sourcemap
  16228. indentExclusionRanges: []
  16229. });
  16230. this.astContext = {
  16231. addDynamicImport: this.addDynamicImport.bind(this),
  16232. addExport: this.addExport.bind(this),
  16233. addImport: this.addImport.bind(this),
  16234. addImportMeta: this.addImportMeta.bind(this),
  16235. addImportSource: this.addImportSource.bind(this),
  16236. code, // Only needed for debugging
  16237. deoptimizationTracker: this.graph.deoptimizationTracker,
  16238. error: this.error.bind(this),
  16239. fileName, // Needed for warnings
  16240. getExports: this.getExports.bind(this),
  16241. getImportedJsxFactoryVariable: this.getImportedJsxFactoryVariable.bind(this),
  16242. getModuleExecIndex: () => this.execIndex,
  16243. getModuleName: this.basename.bind(this),
  16244. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  16245. getReexports: this.getReexports.bind(this),
  16246. importDescriptions: this.importDescriptions,
  16247. includeAllExports: () => this.includeAllExports(true),
  16248. includeDynamicImport: this.includeDynamicImport.bind(this),
  16249. includeVariableInModule: this.includeVariableInModule.bind(this),
  16250. log: this.log.bind(this),
  16251. magicString: this.magicString,
  16252. manualPureFunctions: this.graph.pureFunctions,
  16253. module: this,
  16254. moduleContext: this.context,
  16255. newlyIncludedVariableInits: this.graph.newlyIncludedVariableInits,
  16256. options: this.options,
  16257. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  16258. traceExport: (name) => this.getVariableForExportName(name)[0],
  16259. traceVariable: this.traceVariable.bind(this),
  16260. usesTopLevelAwait: false
  16261. };
  16262. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  16263. this.namespace = new NamespaceVariable(this.astContext);
  16264. const programParent = { context: this.astContext, type: 'Module' };
  16265. if (ast) {
  16266. this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
  16267. this.info.ast = ast;
  16268. }
  16269. else {
  16270. // Measuring asynchronous code does not provide reasonable results
  16271. timeEnd('generate ast', 3);
  16272. const astBuffer = await parseAsync(code, false, this.options.jsx !== false);
  16273. timeStart('generate ast', 3);
  16274. this.ast = convertProgram(astBuffer, programParent, this.scope);
  16275. // Make lazy and apply LRU cache to not hog the memory
  16276. Object.defineProperty(this.info, 'ast', {
  16277. get: () => {
  16278. if (this.graph.astLru.has(fileName)) {
  16279. return this.graph.astLru.get(fileName);
  16280. }
  16281. else {
  16282. const parsedAst = this.tryParse();
  16283. // If the cache is not disabled, we need to keep the AST in memory
  16284. // until the end when the cache is generated
  16285. if (this.options.cache !== false) {
  16286. Object.defineProperty(this.info, 'ast', {
  16287. value: parsedAst
  16288. });
  16289. return parsedAst;
  16290. }
  16291. // Otherwise, we keep it in a small LRU cache to not hog too much
  16292. // memory but allow the same AST to be requested several times.
  16293. this.graph.astLru.set(fileName, parsedAst);
  16294. return parsedAst;
  16295. }
  16296. }
  16297. });
  16298. }
  16299. timeEnd('generate ast', 3);
  16300. }
  16301. toJSON() {
  16302. return {
  16303. ast: this.info.ast,
  16304. attributes: this.info.attributes,
  16305. code: this.info.code,
  16306. customTransformCache: this.customTransformCache,
  16307. dependencies: Array.from(this.dependencies, getId),
  16308. id: this.id,
  16309. meta: this.info.meta,
  16310. moduleSideEffects: this.info.moduleSideEffects,
  16311. originalCode: this.originalCode,
  16312. originalSourcemap: this.originalSourcemap,
  16313. resolvedIds: this.resolvedIds,
  16314. sourcemapChain: this.sourcemapChain,
  16315. syntheticNamedExports: this.info.syntheticNamedExports,
  16316. transformDependencies: this.transformDependencies,
  16317. transformFiles: this.transformFiles
  16318. };
  16319. }
  16320. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  16321. const localVariable = this.scope.variables.get(name);
  16322. if (localVariable) {
  16323. return localVariable;
  16324. }
  16325. const importDescription = this.importDescriptions.get(name);
  16326. if (importDescription) {
  16327. const otherModule = importDescription.module;
  16328. if (otherModule instanceof Module && importDescription.name === '*') {
  16329. return otherModule.namespace;
  16330. }
  16331. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  16332. if (!declaration) {
  16333. return this.error(logMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  16334. }
  16335. return declaration;
  16336. }
  16337. return null;
  16338. }
  16339. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  16340. if (moduleSideEffects != null) {
  16341. this.info.moduleSideEffects = moduleSideEffects;
  16342. }
  16343. if (syntheticNamedExports != null) {
  16344. this.info.syntheticNamedExports = syntheticNamedExports;
  16345. }
  16346. if (meta != null) {
  16347. Object.assign(this.info.meta, meta);
  16348. }
  16349. }
  16350. addDynamicImport(node) {
  16351. let argument = node.sourceAstNode;
  16352. if (argument.type === TemplateLiteral$1) {
  16353. if (argument.quasis.length === 1 &&
  16354. typeof argument.quasis[0].value.cooked === 'string') {
  16355. argument = argument.quasis[0].value.cooked;
  16356. }
  16357. }
  16358. else if (argument.type === Literal$1 &&
  16359. typeof argument.value === 'string') {
  16360. argument = argument.value;
  16361. }
  16362. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  16363. }
  16364. assertUniqueExportName(name, nodeStart) {
  16365. if (this.exports.has(name) || this.reexportDescriptions.has(name)) {
  16366. this.error(logDuplicateExportError(name), nodeStart);
  16367. }
  16368. }
  16369. addExport(node) {
  16370. if (node instanceof ExportDefaultDeclaration) {
  16371. // export default foo;
  16372. this.assertUniqueExportName('default', node.start);
  16373. this.exports.set('default', {
  16374. identifier: node.variable.getAssignedVariableName(),
  16375. localName: 'default'
  16376. });
  16377. }
  16378. else if (node instanceof ExportAllDeclaration) {
  16379. const source = node.source.value;
  16380. this.addSource(source, node);
  16381. if (node.exported) {
  16382. // export * as name from './other'
  16383. const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
  16384. this.assertUniqueExportName(name, node.exported.start);
  16385. this.reexportDescriptions.set(name, {
  16386. localName: '*',
  16387. module: null, // filled in later,
  16388. source,
  16389. start: node.start
  16390. });
  16391. }
  16392. else {
  16393. // export * from './other'
  16394. this.exportAllSources.add(source);
  16395. }
  16396. }
  16397. else if (node.source instanceof Literal) {
  16398. // export { name } from './other'
  16399. const source = node.source.value;
  16400. this.addSource(source, node);
  16401. for (const { exported, local, start } of node.specifiers) {
  16402. const name = exported instanceof Literal ? exported.value : exported.name;
  16403. this.assertUniqueExportName(name, start);
  16404. this.reexportDescriptions.set(name, {
  16405. localName: local instanceof Literal ? local.value : local.name,
  16406. module: null, // filled in later,
  16407. source,
  16408. start
  16409. });
  16410. }
  16411. }
  16412. else if (node.declaration) {
  16413. const declaration = node.declaration;
  16414. if (declaration instanceof VariableDeclaration) {
  16415. // export var { foo, bar } = ...
  16416. // export var foo = 1, bar = 2;
  16417. for (const declarator of declaration.declarations) {
  16418. for (const localName of extractAssignedNames(declarator.id)) {
  16419. this.assertUniqueExportName(localName, declarator.id.start);
  16420. this.exports.set(localName, { identifier: null, localName });
  16421. }
  16422. }
  16423. }
  16424. else {
  16425. // export function foo () {}
  16426. const localName = declaration.id.name;
  16427. this.assertUniqueExportName(localName, declaration.id.start);
  16428. this.exports.set(localName, { identifier: null, localName });
  16429. }
  16430. }
  16431. else {
  16432. // export { foo, bar, baz }
  16433. for (const { local, exported } of node.specifiers) {
  16434. // except for reexports, local must be an Identifier
  16435. const localName = local.name;
  16436. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  16437. this.assertUniqueExportName(exportedName, exported.start);
  16438. this.exports.set(exportedName, { identifier: null, localName });
  16439. }
  16440. }
  16441. }
  16442. addImport(node) {
  16443. const source = node.source.value;
  16444. this.addSource(source, node);
  16445. for (const specifier of node.specifiers) {
  16446. const localName = specifier.local.name;
  16447. if (this.scope.variables.has(localName) || this.importDescriptions.has(localName)) {
  16448. this.error(logRedeclarationError(localName), specifier.local.start);
  16449. }
  16450. const name = specifier instanceof ImportDefaultSpecifier
  16451. ? 'default'
  16452. : specifier instanceof ImportNamespaceSpecifier
  16453. ? '*'
  16454. : specifier.imported instanceof Identifier
  16455. ? specifier.imported.name
  16456. : specifier.imported.value;
  16457. this.importDescriptions.set(localName, {
  16458. module: null, // filled in later
  16459. name,
  16460. source,
  16461. start: specifier.start
  16462. });
  16463. }
  16464. }
  16465. addImportSource(importSource) {
  16466. if (importSource && !this.sourcesWithAttributes.has(importSource)) {
  16467. this.sourcesWithAttributes.set(importSource, EMPTY_OBJECT);
  16468. }
  16469. }
  16470. addImportMeta(node) {
  16471. this.importMetas.push(node);
  16472. }
  16473. addLocationToLogProps(properties, pos) {
  16474. properties.id = this.id;
  16475. properties.pos = pos;
  16476. let code = this.info.code;
  16477. const location = locate(code, pos, { offsetLine: 1 });
  16478. if (location) {
  16479. let { column, line } = location;
  16480. try {
  16481. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  16482. code = this.originalCode;
  16483. }
  16484. catch (error_) {
  16485. this.options.onLog(LOGLEVEL_WARN, logInvalidSourcemapForError(error_, this.id, column, line, pos));
  16486. }
  16487. augmentCodeLocation(properties, { column, line }, code, this.id);
  16488. }
  16489. }
  16490. addModulesToImportDescriptions(importDescription) {
  16491. for (const specifier of importDescription.values()) {
  16492. const { id } = this.resolvedIds[specifier.source];
  16493. specifier.module = this.graph.modulesById.get(id);
  16494. }
  16495. }
  16496. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  16497. const handledDependencies = new Set();
  16498. const addSideEffectDependencies = (possibleDependencies) => {
  16499. for (const dependency of possibleDependencies) {
  16500. if (handledDependencies.has(dependency)) {
  16501. continue;
  16502. }
  16503. handledDependencies.add(dependency);
  16504. if (necessaryDependencies.has(dependency)) {
  16505. relevantDependencies.add(dependency);
  16506. continue;
  16507. }
  16508. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  16509. continue;
  16510. }
  16511. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  16512. relevantDependencies.add(dependency);
  16513. continue;
  16514. }
  16515. addSideEffectDependencies(dependency.dependencies);
  16516. }
  16517. };
  16518. addSideEffectDependencies(this.dependencies);
  16519. addSideEffectDependencies(alwaysCheckedDependencies);
  16520. }
  16521. addSource(source, declaration) {
  16522. const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
  16523. const existingAttributes = this.sourcesWithAttributes.get(source);
  16524. if (existingAttributes) {
  16525. if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
  16526. this.log(LOGLEVEL_WARN, logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
  16527. }
  16528. }
  16529. else {
  16530. this.sourcesWithAttributes.set(source, parsedAttributes);
  16531. }
  16532. }
  16533. getImportedJsxFactoryVariable(baseName, nodeStart, importSource) {
  16534. const { id } = this.resolvedIds[importSource];
  16535. const module = this.graph.modulesById.get(id);
  16536. const [variable] = module.getVariableForExportName(baseName);
  16537. if (!variable) {
  16538. return this.error(logMissingJsxExport(baseName, id, this.id), nodeStart);
  16539. }
  16540. return variable;
  16541. }
  16542. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  16543. let foundSyntheticDeclaration = null;
  16544. const foundInternalDeclarations = new Map();
  16545. const foundExternalDeclarations = new Set();
  16546. for (const module of this.exportAllModules) {
  16547. // Synthetic namespaces should not hide "regular" exports of the same name
  16548. if (module.info.syntheticNamedExports === name) {
  16549. continue;
  16550. }
  16551. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  16552. // We are creating a copy to handle the case where the same binding is
  16553. // imported through different namespace reexports gracefully
  16554. copyNameToModulesMap(searchedNamesAndModules));
  16555. if (module instanceof ExternalModule || indirectExternal) {
  16556. foundExternalDeclarations.add(variable);
  16557. }
  16558. else if (variable instanceof SyntheticNamedExportVariable) {
  16559. if (!foundSyntheticDeclaration) {
  16560. foundSyntheticDeclaration = variable;
  16561. }
  16562. }
  16563. else if (variable) {
  16564. foundInternalDeclarations.set(variable, module);
  16565. }
  16566. }
  16567. if (foundInternalDeclarations.size > 0) {
  16568. const foundDeclarationList = [...foundInternalDeclarations];
  16569. const usedDeclaration = foundDeclarationList[0][0];
  16570. if (foundDeclarationList.length === 1) {
  16571. return [usedDeclaration];
  16572. }
  16573. this.options.onLog(LOGLEVEL_WARN, logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  16574. // TODO we are pretending it was not found while it should behave like "undefined"
  16575. return [null];
  16576. }
  16577. if (foundExternalDeclarations.size > 0) {
  16578. const foundDeclarationList = [...foundExternalDeclarations];
  16579. const usedDeclaration = foundDeclarationList[0];
  16580. if (foundDeclarationList.length > 1) {
  16581. this.options.onLog(LOGLEVEL_WARN, logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  16582. }
  16583. return [usedDeclaration, true];
  16584. }
  16585. if (foundSyntheticDeclaration) {
  16586. return [foundSyntheticDeclaration];
  16587. }
  16588. return [null];
  16589. }
  16590. includeAndGetAdditionalMergedNamespaces() {
  16591. const externalNamespaces = new Set();
  16592. const syntheticNamespaces = new Set();
  16593. for (const module of [this, ...this.exportAllModules]) {
  16594. if (module instanceof ExternalModule) {
  16595. const [externalVariable] = module.getVariableForExportName('*');
  16596. externalVariable.includePath(UNKNOWN_PATH, createInclusionContext());
  16597. this.includedImports.add(externalVariable);
  16598. externalNamespaces.add(externalVariable);
  16599. }
  16600. else if (module.info.syntheticNamedExports) {
  16601. const syntheticNamespace = module.getSyntheticNamespace();
  16602. syntheticNamespace.includePath(UNKNOWN_PATH, createInclusionContext());
  16603. this.includedImports.add(syntheticNamespace);
  16604. syntheticNamespaces.add(syntheticNamespace);
  16605. }
  16606. }
  16607. return [...syntheticNamespaces, ...externalNamespaces];
  16608. }
  16609. includeDynamicImport(node) {
  16610. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  16611. if (resolution instanceof Module) {
  16612. if (!resolution.includedDynamicImporters.includes(this)) {
  16613. resolution.includedDynamicImporters.push(this);
  16614. if (node.withinTopLevelAwait) {
  16615. resolution.includedDirectTopLevelAwaitingDynamicImporters.add(this);
  16616. }
  16617. }
  16618. const importedNames = this.options.treeshake
  16619. ? node.getDeterministicImportedNames()
  16620. : undefined;
  16621. if (importedNames) {
  16622. resolution.includeExportsByNames(importedNames);
  16623. }
  16624. else {
  16625. resolution.includeAllExports(true);
  16626. }
  16627. }
  16628. }
  16629. includeVariable(variable, path, context) {
  16630. const { included, module: variableModule } = variable;
  16631. variable.includePath(path, context);
  16632. if (included) {
  16633. if (variableModule instanceof Module && variableModule !== this) {
  16634. getAndExtendSideEffectModules(variable, this);
  16635. }
  16636. }
  16637. else {
  16638. this.graph.needsTreeshakingPass = true;
  16639. if (variableModule instanceof Module) {
  16640. if (!variableModule.isExecuted) {
  16641. markModuleAndImpureDependenciesAsExecuted(variableModule);
  16642. }
  16643. if (variableModule !== this) {
  16644. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  16645. for (const module of sideEffectModules) {
  16646. if (!module.isExecuted) {
  16647. markModuleAndImpureDependenciesAsExecuted(module);
  16648. }
  16649. }
  16650. }
  16651. }
  16652. }
  16653. }
  16654. includeVariableInModule(variable, path, context) {
  16655. this.includeVariable(variable, path, context);
  16656. const variableModule = variable.module;
  16657. if (variableModule && variableModule !== this) {
  16658. this.includedImports.add(variable);
  16659. }
  16660. }
  16661. shimMissingExport(name) {
  16662. this.options.onLog(LOGLEVEL_WARN, logShimmedExport(this.id, name));
  16663. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  16664. }
  16665. tryParse() {
  16666. try {
  16667. return parseAst(this.info.code, { jsx: this.options.jsx !== false });
  16668. }
  16669. catch (error_) {
  16670. return this.error(logModuleParseError(error_, this.id), error_.pos);
  16671. }
  16672. }
  16673. }
  16674. // if there is a cyclic import in the reexport chain, we should not
  16675. // import from the original module but from the cyclic module to not
  16676. // mess up execution order.
  16677. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  16678. if (variable.module instanceof Module && variable.module !== reexporter) {
  16679. const exporterCycles = variable.module.cycles;
  16680. if (exporterCycles.size > 0) {
  16681. const importerCycles = reexporter.cycles;
  16682. for (const cycleSymbol of importerCycles) {
  16683. if (exporterCycles.has(cycleSymbol)) {
  16684. importer.alternativeReexportModules.set(variable, reexporter);
  16685. break;
  16686. }
  16687. }
  16688. }
  16689. }
  16690. }
  16691. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  16692. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  16693. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  16694. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  16695. async function createAddons(options, outputPluginDriver, chunk) {
  16696. try {
  16697. let [banner, footer, intro, outro] = await Promise.all([
  16698. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  16699. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  16700. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  16701. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  16702. ]);
  16703. if (intro)
  16704. intro += '\n\n';
  16705. if (outro)
  16706. outro = `\n\n${outro}`;
  16707. if (banner)
  16708. banner += '\n';
  16709. if (footer)
  16710. footer = '\n' + footer;
  16711. return { banner, footer, intro, outro };
  16712. }
  16713. catch (error_) {
  16714. return error(logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  16715. }
  16716. }
  16717. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  16718. amd: deconflictImportsOther,
  16719. cjs: deconflictImportsOther,
  16720. es: deconflictImportsEsmOrSystem,
  16721. iife: deconflictImportsOther,
  16722. system: deconflictImportsEsmOrSystem,
  16723. umd: deconflictImportsOther
  16724. };
  16725. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  16726. const reversedModules = [...modules].reverse();
  16727. for (const module of reversedModules) {
  16728. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  16729. }
  16730. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  16731. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  16732. for (const module of reversedModules) {
  16733. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  16734. }
  16735. }
  16736. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  16737. // This is needed for namespace reexports
  16738. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  16739. if (preserveModules || dependency instanceof ExternalChunk) {
  16740. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  16741. }
  16742. }
  16743. for (const variable of imports) {
  16744. const module = variable.module;
  16745. const name = variable.name;
  16746. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  16747. variable.setRenderNames(null, (module instanceof ExternalModule
  16748. ? externalChunkByModule.get(module)
  16749. : chunkByModule.get(module)).variableName);
  16750. }
  16751. else if (module instanceof ExternalModule && name === 'default') {
  16752. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  16753. ? module.suggestedVariableName + '__default'
  16754. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  16755. }
  16756. else {
  16757. variable.setRenderNames(null, getSafeName(makeLegal(name), usedNames, variable.forbiddenNames));
  16758. }
  16759. }
  16760. for (const variable of syntheticExports) {
  16761. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  16762. }
  16763. }
  16764. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  16765. for (const chunk of dependencies) {
  16766. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  16767. }
  16768. for (const chunk of deconflictedNamespace) {
  16769. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  16770. }
  16771. for (const externalModule of deconflictedDefault) {
  16772. externalModule.defaultVariableName =
  16773. deconflictedNamespace.has(externalModule) &&
  16774. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  16775. ? externalModule.namespaceVariableName
  16776. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  16777. }
  16778. for (const variable of imports) {
  16779. const module = variable.module;
  16780. if (module instanceof ExternalModule) {
  16781. const chunk = externalChunkByModule.get(module);
  16782. const name = variable.name;
  16783. if (name === 'default') {
  16784. const moduleInterop = interop(module.id);
  16785. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  16786. ? chunk.defaultVariableName
  16787. : chunk.variableName;
  16788. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  16789. variable.setRenderNames(variableName, 'default');
  16790. }
  16791. else {
  16792. variable.setRenderNames(null, variableName);
  16793. }
  16794. }
  16795. else if (name === '*') {
  16796. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  16797. ? chunk.namespaceVariableName
  16798. : chunk.variableName);
  16799. }
  16800. else {
  16801. // if the second parameter is `null`, it uses its "name" for the property name
  16802. variable.setRenderNames(chunk.variableName, null);
  16803. }
  16804. }
  16805. else {
  16806. const chunk = chunkByModule.get(module);
  16807. if (preserveModules && variable.isNamespace) {
  16808. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  16809. }
  16810. else if (chunk.exportMode === 'default') {
  16811. variable.setRenderNames(null, chunk.variableName);
  16812. }
  16813. else {
  16814. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  16815. }
  16816. }
  16817. }
  16818. }
  16819. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  16820. for (const module of modules) {
  16821. for (const variable of module.scope.variables.values()) {
  16822. if (variable.included &&
  16823. // this will only happen for exports in some formats
  16824. !(variable.renderBaseName ||
  16825. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  16826. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  16827. }
  16828. }
  16829. if (includedNamespaces.has(module)) {
  16830. const namespace = module.namespace;
  16831. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  16832. }
  16833. }
  16834. }
  16835. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  16836. let nameIndex = 0;
  16837. for (const variable of exports) {
  16838. let [exportName] = variable.name;
  16839. if (exportsByName.has(exportName)) {
  16840. do {
  16841. exportName = toBase64(++nameIndex);
  16842. // skip past leading number identifiers
  16843. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  16844. nameIndex += 9 * 64 ** (exportName.length - 1);
  16845. exportName = toBase64(nameIndex);
  16846. }
  16847. } while (RESERVED_NAMES.has(exportName) || exportsByName.has(exportName));
  16848. }
  16849. exportsByName.set(exportName, variable);
  16850. exportNamesByVariable.set(variable, [exportName]);
  16851. }
  16852. }
  16853. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  16854. for (const variable of exports) {
  16855. let nameIndex = 0;
  16856. let exportName = variable.name;
  16857. while (exportsByName.has(exportName)) {
  16858. exportName = variable.name + '$' + ++nameIndex;
  16859. }
  16860. exportsByName.set(exportName, variable);
  16861. exportNamesByVariable.set(variable, [exportName]);
  16862. }
  16863. }
  16864. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  16865. const exportKeys = chunk.getExportNames();
  16866. if (exportMode === 'default') {
  16867. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  16868. return error(logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  16869. }
  16870. }
  16871. else if (exportMode === 'none' && exportKeys.length > 0) {
  16872. return error(logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  16873. }
  16874. if (exportMode === 'auto') {
  16875. if (exportKeys.length === 0) {
  16876. exportMode = 'none';
  16877. }
  16878. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  16879. exportMode = 'default';
  16880. }
  16881. else {
  16882. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  16883. log(LOGLEVEL_WARN, logMixedExport(facadeModuleId, name));
  16884. }
  16885. exportMode = 'named';
  16886. }
  16887. }
  16888. return exportMode;
  16889. }
  16890. function guessIndentString(code) {
  16891. const lines = code.split('\n');
  16892. const tabbed = lines.filter(line => /^\t+/.test(line));
  16893. const spaced = lines.filter(line => /^ {2,}/.test(line));
  16894. if (tabbed.length === 0 && spaced.length === 0) {
  16895. return null;
  16896. }
  16897. // More lines tabbed than spaced? Assume tabs, and
  16898. // default to tabs in the case of a tie (or nothing
  16899. // to go on)
  16900. if (tabbed.length >= spaced.length) {
  16901. return '\t';
  16902. }
  16903. // Otherwise, we need to guess the multiple
  16904. const min = spaced.reduce((previous, current) => {
  16905. const numberSpaces = /^ +/.exec(current)[0].length;
  16906. return Math.min(numberSpaces, previous);
  16907. }, Infinity);
  16908. return ' '.repeat(min);
  16909. }
  16910. function getIndentString(modules, options) {
  16911. if (options.indent !== true)
  16912. return options.indent;
  16913. for (const module of modules) {
  16914. const indent = guessIndentString(module.originalCode);
  16915. if (indent !== null)
  16916. return indent;
  16917. }
  16918. return '\t';
  16919. }
  16920. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  16921. const staticDependencyBlocks = [];
  16922. const handledDependencies = new Set();
  16923. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  16924. const module = orderedModules[modulePos];
  16925. if (!handledDependencies.has(module)) {
  16926. const staticDependencies = [];
  16927. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  16928. staticDependencyBlocks.unshift(staticDependencies);
  16929. }
  16930. }
  16931. const dependencies = new Set();
  16932. for (const block of staticDependencyBlocks) {
  16933. for (const dependency of block) {
  16934. dependencies.add(dependency);
  16935. }
  16936. }
  16937. return dependencies;
  16938. }
  16939. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  16940. const dependencies = module.getDependenciesToBeIncluded();
  16941. for (const dependency of dependencies) {
  16942. if (dependency instanceof ExternalModule) {
  16943. staticDependencies.push(externalChunkByModule.get(dependency));
  16944. continue;
  16945. }
  16946. const dependencyChunk = chunkByModule.get(dependency);
  16947. if (dependencyChunk !== chunk) {
  16948. staticDependencies.push(dependencyChunk);
  16949. continue;
  16950. }
  16951. if (!handledModules.has(dependency)) {
  16952. handledModules.add(dependency);
  16953. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  16954. }
  16955. }
  16956. }
  16957. // Four random characters from the private use area to minimize risk of
  16958. // conflicts
  16959. const hashPlaceholderLeft = '!~{';
  16960. const hashPlaceholderRight = '}~';
  16961. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  16962. // This is the size of a 128-bits xxhash with base64url encoding
  16963. const MAX_HASH_SIZE = 21;
  16964. const DEFAULT_HASH_SIZE = 8;
  16965. const getHashPlaceholderGenerator = () => {
  16966. let nextIndex = 0;
  16967. return (optionName, hashSize) => {
  16968. if (hashSize > MAX_HASH_SIZE) {
  16969. return error(logFailedValidation(`Hashes cannot be longer than ${MAX_HASH_SIZE} characters, received ${hashSize}. Check the "${optionName}" option.`));
  16970. }
  16971. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  16972. if (placeholder.length > hashSize) {
  16973. 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.`));
  16974. }
  16975. return placeholder;
  16976. };
  16977. };
  16978. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${MAX_HASH_SIZE - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  16979. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  16980. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  16981. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  16982. const containedPlaceholders = new Set();
  16983. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  16984. if (placeholders.has(placeholder)) {
  16985. containedPlaceholders.add(placeholder);
  16986. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  16987. }
  16988. return placeholder;
  16989. });
  16990. return { containedPlaceholders, transformedCode };
  16991. };
  16992. const lowercaseBundleKeys = Symbol('bundleKeys');
  16993. const FILE_PLACEHOLDER = {
  16994. type: 'placeholder'
  16995. };
  16996. const getOutputBundle = (outputBundleBase) => {
  16997. const reservedLowercaseBundleKeys = new Set();
  16998. return new Proxy(outputBundleBase, {
  16999. deleteProperty(target, key) {
  17000. if (typeof key === 'string') {
  17001. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  17002. }
  17003. return Reflect.deleteProperty(target, key);
  17004. },
  17005. get(target, key) {
  17006. if (key === lowercaseBundleKeys) {
  17007. return reservedLowercaseBundleKeys;
  17008. }
  17009. return Reflect.get(target, key);
  17010. },
  17011. set(target, key, value) {
  17012. if (typeof key === 'string') {
  17013. reservedLowercaseBundleKeys.add(key.toLowerCase());
  17014. }
  17015. return Reflect.set(target, key, value);
  17016. }
  17017. });
  17018. };
  17019. const removeUnreferencedAssets = (outputBundle) => {
  17020. const unreferencedAssets = new Set();
  17021. const bundleEntries = Object.values(outputBundle);
  17022. for (const asset of bundleEntries) {
  17023. if (asset.type === 'asset' && asset.needsCodeReference) {
  17024. unreferencedAssets.add(asset.fileName);
  17025. }
  17026. }
  17027. for (const chunk of bundleEntries) {
  17028. if (chunk.type === 'chunk') {
  17029. for (const referencedFile of chunk.referencedFiles) {
  17030. if (unreferencedAssets.has(referencedFile)) {
  17031. unreferencedAssets.delete(referencedFile);
  17032. }
  17033. }
  17034. }
  17035. }
  17036. for (const file of unreferencedAssets) {
  17037. delete outputBundle[file];
  17038. }
  17039. };
  17040. function renderNamePattern(pattern, patternName, replacements) {
  17041. if (isPathFragment(pattern))
  17042. 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.`));
  17043. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  17044. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  17045. return error(logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  17046. }
  17047. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  17048. if (isPathFragment(replacement))
  17049. return error(logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  17050. return replacement;
  17051. });
  17052. }
  17053. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  17054. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  17055. return name;
  17056. const extension = extname(name);
  17057. name = name.slice(0, Math.max(0, name.length - extension.length));
  17058. let uniqueName, uniqueIndex = 1;
  17059. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  17060. ;
  17061. return uniqueName;
  17062. }
  17063. const NON_ASSET_EXTENSIONS = new Set([
  17064. '.js',
  17065. '.jsx',
  17066. '.ts',
  17067. '.tsx',
  17068. '.mjs',
  17069. '.mts',
  17070. '.cjs',
  17071. '.cts'
  17072. ]);
  17073. function getGlobalName(chunk, globals, hasExports, log) {
  17074. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  17075. if (globalName) {
  17076. return globalName;
  17077. }
  17078. if (hasExports) {
  17079. log(LOGLEVEL_WARN, logMissingGlobalName(chunk.id, chunk.variableName));
  17080. return chunk.variableName;
  17081. }
  17082. }
  17083. class Chunk {
  17084. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  17085. this.orderedModules = orderedModules;
  17086. this.inputOptions = inputOptions;
  17087. this.outputOptions = outputOptions;
  17088. this.unsetOptions = unsetOptions;
  17089. this.pluginDriver = pluginDriver;
  17090. this.modulesById = modulesById;
  17091. this.chunkByModule = chunkByModule;
  17092. this.externalChunkByModule = externalChunkByModule;
  17093. this.facadeChunkByModule = facadeChunkByModule;
  17094. this.includedNamespaces = includedNamespaces;
  17095. this.manualChunkAlias = manualChunkAlias;
  17096. this.getPlaceholder = getPlaceholder;
  17097. this.bundle = bundle;
  17098. this.inputBase = inputBase;
  17099. this.snippets = snippets;
  17100. this.dependencies = new Set();
  17101. this.entryModules = [];
  17102. this.exportMode = 'named';
  17103. this.facadeModule = null;
  17104. this.namespaceVariableName = '';
  17105. this.variableName = '';
  17106. this.accessedGlobalsByScope = new Map();
  17107. this.dynamicEntryModules = [];
  17108. this.dynamicName = null;
  17109. this.exportNamesByVariable = new Map();
  17110. this.exports = new Set();
  17111. this.exportsByName = new Map();
  17112. this.fileName = null;
  17113. this.implicitEntryModules = [];
  17114. this.implicitlyLoadedBefore = new Set();
  17115. this.imports = new Set();
  17116. this.includedDynamicImports = null;
  17117. this.includedReexportsByModule = new Map();
  17118. // This may be updated in the constructor
  17119. this.isEmpty = true;
  17120. this.name = null;
  17121. this.needsExportsShim = false;
  17122. this.preRenderedChunkInfo = null;
  17123. this.preliminaryFileName = null;
  17124. this.preliminarySourcemapFileName = null;
  17125. this.renderedChunkInfo = null;
  17126. this.renderedDependencies = null;
  17127. this.renderedModules = Object.create(null);
  17128. this.sortedExportNames = null;
  17129. this.strictFacade = false;
  17130. /** Modules with 'allow-extension' that should have preserved exports within the chunk */
  17131. this.allowExtensionModules = new Set();
  17132. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  17133. const chunkModules = new Set(orderedModules);
  17134. for (const module of orderedModules) {
  17135. chunkByModule.set(module, this);
  17136. if (module.namespace.included && !outputOptions.preserveModules) {
  17137. includedNamespaces.add(module);
  17138. }
  17139. if (this.isEmpty && module.isIncluded()) {
  17140. this.isEmpty = false;
  17141. }
  17142. if (module.info.isEntry || outputOptions.preserveModules) {
  17143. this.entryModules.push(module);
  17144. }
  17145. for (const importer of module.includedDynamicImporters) {
  17146. if (!chunkModules.has(importer)) {
  17147. this.dynamicEntryModules.push(module);
  17148. // Modules with synthetic exports need an artificial namespace for dynamic imports
  17149. if (module.info.syntheticNamedExports) {
  17150. includedNamespaces.add(module);
  17151. this.exports.add(module.namespace);
  17152. }
  17153. }
  17154. }
  17155. if (module.implicitlyLoadedAfter.size > 0) {
  17156. this.implicitEntryModules.push(module);
  17157. }
  17158. }
  17159. this.suggestedVariableName = makeLegal(this.generateVariableName());
  17160. }
  17161. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  17162. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  17163. chunk.assignFacadeName(facadeName, facadedModule);
  17164. if (!facadeChunkByModule.has(facadedModule)) {
  17165. facadeChunkByModule.set(facadedModule, chunk);
  17166. }
  17167. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  17168. chunk.dependencies.add(dependency instanceof Module
  17169. ? chunkByModule.get(dependency)
  17170. : externalChunkByModule.get(dependency));
  17171. }
  17172. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  17173. facadedModule.info.moduleSideEffects &&
  17174. facadedModule.hasEffects()) {
  17175. chunk.dependencies.add(chunkByModule.get(facadedModule));
  17176. }
  17177. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  17178. chunk.facadeModule = facadedModule;
  17179. chunk.strictFacade = true;
  17180. return chunk;
  17181. }
  17182. canModuleBeFacade(module, exposedVariables) {
  17183. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  17184. // All exports of this chunk need to be exposed by the candidate module
  17185. for (const exposedVariable of this.exports) {
  17186. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  17187. return false;
  17188. }
  17189. }
  17190. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  17191. for (const exposedVariable of exposedVariables) {
  17192. if (!(exposedVariable.module === module ||
  17193. moduleExportNamesByVariable.has(exposedVariable) ||
  17194. (exposedVariable instanceof SyntheticNamedExportVariable &&
  17195. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  17196. return false;
  17197. }
  17198. }
  17199. return true;
  17200. }
  17201. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  17202. const renderedChunkInfo = this.getRenderedChunkInfo();
  17203. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  17204. const preliminaryFileName = renderedChunkInfo.fileName;
  17205. const fileName = (this.fileName = finalize(preliminaryFileName));
  17206. return {
  17207. ...renderedChunkInfo,
  17208. code,
  17209. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  17210. fileName,
  17211. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  17212. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  17213. finalize(fileName),
  17214. bindings
  17215. ])),
  17216. imports: renderedChunkInfo.imports.map(finalize),
  17217. map,
  17218. preliminaryFileName,
  17219. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  17220. sourcemapFileName
  17221. };
  17222. }
  17223. generateExports() {
  17224. this.sortedExportNames = null;
  17225. const remainingExports = new Set(this.exports);
  17226. if (this.facadeModule !== null &&
  17227. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  17228. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  17229. for (const [variable, exportNames] of exportNamesByVariable) {
  17230. this.exportNamesByVariable.set(variable, [...exportNames]);
  17231. for (const exportName of exportNames) {
  17232. this.exportsByName.set(exportName, variable);
  17233. }
  17234. remainingExports.delete(variable);
  17235. }
  17236. }
  17237. for (const module of this.allowExtensionModules) {
  17238. const exportNamesByVariable = module.getExportNamesByVariable();
  17239. for (const [variable, exportNames] of exportNamesByVariable) {
  17240. this.exportNamesByVariable.set(variable, [...exportNames]);
  17241. for (const exportName of exportNames) {
  17242. this.exportsByName.set(exportName, variable);
  17243. }
  17244. remainingExports.delete(variable);
  17245. }
  17246. }
  17247. if (this.outputOptions.minifyInternalExports) {
  17248. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  17249. }
  17250. else {
  17251. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  17252. }
  17253. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  17254. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  17255. }
  17256. generateFacades() {
  17257. const facades = [];
  17258. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  17259. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  17260. for (const module of entryModules) {
  17261. if (module.preserveSignature === 'allow-extension') {
  17262. const canPreserveExports = this.canPreserveModuleExports(module);
  17263. if (canPreserveExports &&
  17264. !module.chunkFileNames.size &&
  17265. module.chunkNames.every(({ isUserDefined }) => !isUserDefined)) {
  17266. this.allowExtensionModules.add(module);
  17267. if (!this.facadeModule) {
  17268. this.facadeModule = module;
  17269. this.strictFacade = false;
  17270. this.assignFacadeName({}, module, this.outputOptions.preserveModules);
  17271. }
  17272. this.facadeChunkByModule.set(module, this);
  17273. continue;
  17274. }
  17275. }
  17276. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  17277. // mapping must run after Set 'name' dedupe
  17278. name => ({
  17279. name
  17280. }));
  17281. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  17282. requiredFacades.push({});
  17283. }
  17284. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  17285. if (requiredFacades.length === 0) {
  17286. requiredFacades.push({});
  17287. }
  17288. if (!this.facadeModule) {
  17289. const needsStrictFacade = !this.outputOptions.preserveModules &&
  17290. (module.preserveSignature === 'strict' ||
  17291. (module.preserveSignature === 'exports-only' &&
  17292. module.getExportNamesByVariable().size > 0));
  17293. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  17294. this.facadeModule = module;
  17295. this.facadeChunkByModule.set(module, this);
  17296. if (module.preserveSignature) {
  17297. this.strictFacade = needsStrictFacade;
  17298. }
  17299. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  17300. }
  17301. }
  17302. for (const facadeName of requiredFacades) {
  17303. 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));
  17304. }
  17305. }
  17306. for (const module of this.dynamicEntryModules) {
  17307. if (module.info.syntheticNamedExports)
  17308. continue;
  17309. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  17310. this.facadeModule = module;
  17311. this.facadeChunkByModule.set(module, this);
  17312. this.strictFacade = true;
  17313. this.dynamicName = getChunkNameFromModule(module);
  17314. }
  17315. else if (this.facadeModule === module &&
  17316. !this.strictFacade &&
  17317. this.canModuleBeFacade(module, exposedVariables)) {
  17318. this.strictFacade = true;
  17319. }
  17320. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  17321. this.includedNamespaces.add(module);
  17322. this.exports.add(module.namespace);
  17323. }
  17324. }
  17325. if (!this.outputOptions.preserveModules) {
  17326. this.addNecessaryImportsForFacades();
  17327. }
  17328. return facades;
  17329. }
  17330. canPreserveModuleExports(module) {
  17331. const exportNamesByVariable = module.getExportNamesByVariable();
  17332. // Check for conflicts - an export name is a conflict if it points to a different module or definition
  17333. for (const [variable, exportNames] of exportNamesByVariable) {
  17334. for (const exportName of exportNames) {
  17335. const existingVariable = this.exportsByName.get(exportName);
  17336. // It's ok if the same export name in two modules references the exact same variable
  17337. if (existingVariable && existingVariable !== variable) {
  17338. return false;
  17339. }
  17340. }
  17341. }
  17342. // No actual conflicts found, add export names for future conflict checks
  17343. for (const [variable, exportNames] of exportNamesByVariable) {
  17344. for (const exportName of exportNames) {
  17345. this.exportsByName.set(exportName, variable);
  17346. }
  17347. }
  17348. return true;
  17349. }
  17350. getChunkName() {
  17351. return (this.name ??= this.outputOptions.sanitizeFileName(this.getFallbackChunkName()));
  17352. }
  17353. getExportNames() {
  17354. return (this.sortedExportNames ??= [...this.exportsByName.keys()].sort());
  17355. }
  17356. getFileName() {
  17357. return this.fileName || this.getPreliminaryFileName().fileName;
  17358. }
  17359. getImportPath(importer) {
  17360. return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  17361. }
  17362. getPreliminaryFileName() {
  17363. if (this.preliminaryFileName) {
  17364. return this.preliminaryFileName;
  17365. }
  17366. let fileName;
  17367. let hashPlaceholder = null;
  17368. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  17369. if (file) {
  17370. fileName = basename(file);
  17371. }
  17372. else if (this.fileName === null) {
  17373. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  17374. ? [entryFileNames, 'output.entryFileNames']
  17375. : [chunkFileNames, 'output.chunkFileNames'];
  17376. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  17377. format: () => format,
  17378. hash: size => hashPlaceholder ||
  17379. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  17380. name: () => this.getChunkName()
  17381. });
  17382. if (!hashPlaceholder) {
  17383. fileName = makeUnique(fileName, this.bundle);
  17384. }
  17385. }
  17386. else {
  17387. fileName = this.fileName;
  17388. }
  17389. if (!hashPlaceholder) {
  17390. this.bundle[fileName] = FILE_PLACEHOLDER;
  17391. }
  17392. // Caching is essential to not conflict with the file name reservation above
  17393. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  17394. }
  17395. getPreliminarySourcemapFileName() {
  17396. if (this.preliminarySourcemapFileName) {
  17397. return this.preliminarySourcemapFileName;
  17398. }
  17399. let sourcemapFileName = null;
  17400. let hashPlaceholder = null;
  17401. const { sourcemapFileNames, format } = this.outputOptions;
  17402. if (sourcemapFileNames) {
  17403. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  17404. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  17405. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  17406. format: () => format,
  17407. hash: size => hashPlaceholder ||
  17408. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  17409. name: () => this.getChunkName()
  17410. });
  17411. if (!hashPlaceholder) {
  17412. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  17413. }
  17414. }
  17415. else {
  17416. return null;
  17417. }
  17418. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  17419. }
  17420. getRenderedChunkInfo() {
  17421. if (this.renderedChunkInfo) {
  17422. return this.renderedChunkInfo;
  17423. }
  17424. return (this.renderedChunkInfo = {
  17425. ...this.getPreRenderedChunkInfo(),
  17426. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  17427. fileName: this.getFileName(),
  17428. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  17429. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  17430. imports: Array.from(this.dependencies, resolveFileName),
  17431. modules: this.renderedModules,
  17432. referencedFiles: this.getReferencedFiles()
  17433. });
  17434. }
  17435. getVariableExportName(variable) {
  17436. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  17437. return '*';
  17438. }
  17439. return this.exportNamesByVariable.get(variable)[0];
  17440. }
  17441. link() {
  17442. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  17443. for (const module of this.orderedModules) {
  17444. this.addImplicitlyLoadedBeforeFromModule(module);
  17445. this.setUpChunkImportsAndExportsForModule(module);
  17446. }
  17447. }
  17448. inlineTransitiveImports() {
  17449. const { facadeModule, dependencies, outputOptions } = this;
  17450. const { hoistTransitiveImports, preserveModules } = outputOptions;
  17451. // for static and dynamic entry points, add transitive dependencies to this
  17452. // chunk's dependencies to avoid loading latency
  17453. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  17454. for (const dep of dependencies) {
  17455. if (dep instanceof Chunk)
  17456. this.inlineChunkDependencies(dep);
  17457. }
  17458. }
  17459. }
  17460. async render() {
  17461. const { exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  17462. const { format, preserveModules } = outputOptions;
  17463. const preliminaryFileName = this.getPreliminaryFileName();
  17464. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  17465. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  17466. const renderedDependencies = [...this.getRenderedDependencies().values()];
  17467. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  17468. let hasExports = renderedExports.length > 0;
  17469. let hasDefaultExport = false;
  17470. for (const renderedDependency of renderedDependencies) {
  17471. const { reexports } = renderedDependency;
  17472. if (reexports?.length) {
  17473. hasExports = true;
  17474. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  17475. hasDefaultExport = true;
  17476. }
  17477. if (format === 'es') {
  17478. renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  17479. }
  17480. }
  17481. }
  17482. if (!hasDefaultExport) {
  17483. for (const { exported } of renderedExports) {
  17484. if (exported === 'default') {
  17485. hasDefaultExport = true;
  17486. break;
  17487. }
  17488. }
  17489. }
  17490. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  17491. finalisers[format](renderedSource, {
  17492. accessedGlobals,
  17493. dependencies: renderedDependencies,
  17494. exports: renderedExports,
  17495. hasDefaultExport,
  17496. hasExports,
  17497. id: preliminaryFileName.fileName,
  17498. indent,
  17499. intro,
  17500. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  17501. isModuleFacade: facadeModule !== null,
  17502. log: onLog,
  17503. namedExportsMode: exportMode !== 'default',
  17504. outro,
  17505. snippets,
  17506. usesTopLevelAwait
  17507. }, outputOptions);
  17508. if (banner)
  17509. magicString.prepend(banner);
  17510. if (format === 'es' || format === 'cjs') {
  17511. const shebang = facadeModule !== null && facadeModule.info.isEntry && facadeModule.shebang;
  17512. if (shebang) {
  17513. magicString.prepend(`#!${shebang}\n`);
  17514. }
  17515. }
  17516. if (footer)
  17517. magicString.append(footer);
  17518. return {
  17519. chunk: this,
  17520. magicString,
  17521. preliminaryFileName,
  17522. preliminarySourcemapFileName,
  17523. usedModules
  17524. };
  17525. }
  17526. addImplicitlyLoadedBeforeFromModule(baseModule) {
  17527. const { chunkByModule, implicitlyLoadedBefore } = this;
  17528. for (const module of baseModule.implicitlyLoadedBefore) {
  17529. const chunk = chunkByModule.get(module);
  17530. if (chunk && chunk !== this) {
  17531. implicitlyLoadedBefore.add(chunk);
  17532. }
  17533. }
  17534. }
  17535. addNecessaryImportsForFacades() {
  17536. for (const [module, variables] of this.includedReexportsByModule) {
  17537. if (this.includedNamespaces.has(module)) {
  17538. for (const variable of variables) {
  17539. this.imports.add(variable);
  17540. }
  17541. }
  17542. }
  17543. }
  17544. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  17545. if (fileName) {
  17546. this.fileName = fileName;
  17547. }
  17548. else {
  17549. this.name = this.outputOptions.sanitizeFileName(name ||
  17550. (preservePath
  17551. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  17552. : getChunkNameFromModule(facadedModule)));
  17553. }
  17554. }
  17555. checkCircularDependencyImport(variable, importingModule) {
  17556. const variableModule = variable.module;
  17557. if (variableModule instanceof Module) {
  17558. const exportChunk = this.chunkByModule.get(variableModule);
  17559. let alternativeReexportModule;
  17560. do {
  17561. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  17562. if (alternativeReexportModule) {
  17563. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  17564. if (exportingChunk !== exportChunk) {
  17565. this.inputOptions.onLog(LOGLEVEL_WARN, logCyclicCrossChunkReexport(
  17566. // Namespaces do not have an export name
  17567. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  17568. }
  17569. importingModule = alternativeReexportModule;
  17570. }
  17571. } while (alternativeReexportModule);
  17572. }
  17573. }
  17574. ensureReexportsAreAvailableForModule(module) {
  17575. const includedReexports = [];
  17576. const map = module.getExportNamesByVariable();
  17577. for (const exportedVariable of map.keys()) {
  17578. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  17579. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  17580. this.checkCircularDependencyImport(importedVariable, module);
  17581. // When preserving modules, we do not create namespace objects but directly
  17582. // use the actual namespaces, which would be broken by this logic.
  17583. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  17584. const exportingModule = importedVariable.module;
  17585. if (exportingModule instanceof Module) {
  17586. const chunk = this.chunkByModule.get(exportingModule);
  17587. if (chunk && chunk !== this) {
  17588. chunk.exports.add(importedVariable);
  17589. includedReexports.push(importedVariable);
  17590. if (isSynthetic) {
  17591. this.imports.add(importedVariable);
  17592. }
  17593. }
  17594. }
  17595. }
  17596. }
  17597. if (includedReexports.length > 0) {
  17598. this.includedReexportsByModule.set(module, includedReexports);
  17599. }
  17600. }
  17601. generateVariableName() {
  17602. if (this.manualChunkAlias) {
  17603. return this.manualChunkAlias;
  17604. }
  17605. const moduleForNaming = this.entryModules[0] ||
  17606. this.implicitEntryModules[0] ||
  17607. this.dynamicEntryModules[0] ||
  17608. this.orderedModules[this.orderedModules.length - 1];
  17609. if (moduleForNaming) {
  17610. return getChunkNameFromModule(moduleForNaming);
  17611. }
  17612. return 'chunk';
  17613. }
  17614. getChunkExportDeclarations(format) {
  17615. const exports = [];
  17616. for (const exportName of this.getExportNames()) {
  17617. if (exportName[0] === '*')
  17618. continue;
  17619. const variable = this.exportsByName.get(exportName);
  17620. if (!(variable instanceof SyntheticNamedExportVariable)) {
  17621. const module = variable.module;
  17622. if (module) {
  17623. const chunk = this.chunkByModule.get(module);
  17624. if (chunk !== this) {
  17625. if (!chunk || format !== 'es') {
  17626. continue;
  17627. }
  17628. const chunkDep = this.renderedDependencies.get(chunk);
  17629. if (!chunkDep) {
  17630. continue;
  17631. }
  17632. const { imports, reexports } = chunkDep;
  17633. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  17634. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  17635. if (!isImported) {
  17636. continue;
  17637. }
  17638. }
  17639. }
  17640. }
  17641. let expression = null;
  17642. let hoisted = false;
  17643. let local = variable.getName(this.snippets.getPropertyAccess);
  17644. if (variable instanceof LocalVariable) {
  17645. for (const declaration of variable.declarations) {
  17646. if (declaration.parent instanceof FunctionDeclaration ||
  17647. (declaration instanceof ExportDefaultDeclaration &&
  17648. declaration.declaration instanceof FunctionDeclaration)) {
  17649. hoisted = true;
  17650. break;
  17651. }
  17652. }
  17653. }
  17654. else if (variable instanceof SyntheticNamedExportVariable) {
  17655. expression = local;
  17656. if (format === 'es') {
  17657. local = variable.renderName;
  17658. }
  17659. }
  17660. exports.push({
  17661. exported: exportName,
  17662. expression,
  17663. hoisted,
  17664. local
  17665. });
  17666. }
  17667. return exports;
  17668. }
  17669. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  17670. const dependencies = new Set();
  17671. const deconflictedDefault = new Set();
  17672. const deconflictedNamespace = new Set();
  17673. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  17674. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  17675. const module = variable.module;
  17676. if (module instanceof ExternalModule) {
  17677. const chunk = this.externalChunkByModule.get(module);
  17678. dependencies.add(chunk);
  17679. if (addNonNamespacesAndInteropHelpers) {
  17680. if (variable.name === 'default') {
  17681. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  17682. deconflictedDefault.add(chunk);
  17683. }
  17684. }
  17685. else if (variable.isNamespace &&
  17686. namespaceInteropHelpersByInteropType[interop(module.id)] &&
  17687. (this.imports.has(variable) ||
  17688. !this.exportNamesByVariable.get(variable)?.every(name => name.startsWith('*')))) {
  17689. // We only need to deconflict it if the namespace is actually
  17690. // created as a variable, i.e. because it is used internally or
  17691. // because it is reexported as an object
  17692. deconflictedNamespace.add(chunk);
  17693. }
  17694. }
  17695. }
  17696. else {
  17697. const chunk = this.chunkByModule.get(module);
  17698. if (chunk !== this) {
  17699. dependencies.add(chunk);
  17700. if (addNonNamespacesAndInteropHelpers &&
  17701. chunk.exportMode === 'default' &&
  17702. variable.isNamespace) {
  17703. deconflictedNamespace.add(chunk);
  17704. }
  17705. }
  17706. }
  17707. }
  17708. }
  17709. if (addDependenciesWithoutBindings) {
  17710. for (const dependency of this.dependencies) {
  17711. dependencies.add(dependency);
  17712. }
  17713. }
  17714. return { deconflictedDefault, deconflictedNamespace, dependencies };
  17715. }
  17716. getDynamicDependencies() {
  17717. return this.getIncludedDynamicImports()
  17718. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  17719. resolvedDynamicImport.chunk ||
  17720. resolvedDynamicImport.externalChunk ||
  17721. resolvedDynamicImport.resolution)
  17722. .filter((resolution) => resolution !== this &&
  17723. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  17724. }
  17725. getDynamicImportStringAndAttributes(resolution, fileName, node) {
  17726. if (resolution instanceof ExternalModule) {
  17727. const chunk = this.externalChunkByModule.get(resolution);
  17728. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAttributes(this.snippets)];
  17729. }
  17730. let attributes = null;
  17731. if (['es', 'cjs'].includes(this.outputOptions.format) &&
  17732. this.outputOptions.externalImportAttributes) {
  17733. const attributesFromImportAttributes = getAttributesFromImportExpression(node);
  17734. attributes =
  17735. attributesFromImportAttributes === EMPTY_OBJECT
  17736. ? true
  17737. : formatAttributes(attributesFromImportAttributes, this.snippets);
  17738. }
  17739. return [resolution || '', attributes];
  17740. }
  17741. getFallbackChunkName() {
  17742. if (this.manualChunkAlias) {
  17743. return this.manualChunkAlias;
  17744. }
  17745. if (this.dynamicName) {
  17746. return this.dynamicName;
  17747. }
  17748. if (this.fileName) {
  17749. return getAliasName(this.fileName);
  17750. }
  17751. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  17752. }
  17753. getImportSpecifiers() {
  17754. const { interop } = this.outputOptions;
  17755. const importsByDependency = new Map();
  17756. for (const variable of this.imports) {
  17757. const module = variable.module;
  17758. let dependency;
  17759. let imported;
  17760. if (module instanceof ExternalModule) {
  17761. dependency = this.externalChunkByModule.get(module);
  17762. imported = variable.name;
  17763. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  17764. return error(logUnexpectedNamedImport(module.id, imported, false));
  17765. }
  17766. }
  17767. else {
  17768. dependency = this.chunkByModule.get(module);
  17769. imported = dependency.getVariableExportName(variable);
  17770. }
  17771. getOrCreate(importsByDependency, dependency, getNewArray).push({
  17772. imported,
  17773. local: variable.getName(this.snippets.getPropertyAccess)
  17774. });
  17775. }
  17776. return importsByDependency;
  17777. }
  17778. getIncludedDynamicImports() {
  17779. if (this.includedDynamicImports) {
  17780. return this.includedDynamicImports;
  17781. }
  17782. const includedDynamicImports = [];
  17783. for (const module of this.orderedModules) {
  17784. for (const { node, resolution } of module.dynamicImports) {
  17785. if (!node.included) {
  17786. continue;
  17787. }
  17788. includedDynamicImports.push(resolution instanceof Module
  17789. ? {
  17790. chunk: this.chunkByModule.get(resolution),
  17791. externalChunk: null,
  17792. facadeChunk: this.facadeChunkByModule.get(resolution),
  17793. node,
  17794. resolution
  17795. }
  17796. : resolution instanceof ExternalModule
  17797. ? {
  17798. chunk: null,
  17799. externalChunk: this.externalChunkByModule.get(resolution),
  17800. facadeChunk: null,
  17801. node,
  17802. resolution
  17803. }
  17804. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  17805. }
  17806. }
  17807. return (this.includedDynamicImports = includedDynamicImports);
  17808. }
  17809. getPreRenderedChunkInfo() {
  17810. if (this.preRenderedChunkInfo) {
  17811. return this.preRenderedChunkInfo;
  17812. }
  17813. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  17814. return (this.preRenderedChunkInfo = {
  17815. exports: this.getExportNames(),
  17816. facadeModuleId: facadeModule && facadeModule.id,
  17817. isDynamicEntry: dynamicEntryModules.length > 0,
  17818. isEntry: !!facadeModule?.info.isEntry,
  17819. isImplicitEntry: implicitEntryModules.length > 0,
  17820. moduleIds: orderedModules.map(({ id }) => id),
  17821. name: this.getChunkName(),
  17822. type: 'chunk'
  17823. });
  17824. }
  17825. getPreserveModulesChunkNameFromModule(module) {
  17826. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  17827. if (predefinedChunkName)
  17828. return predefinedChunkName;
  17829. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  17830. const sanitizedId = sanitizeFileName(normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  17831. const extensionName = extname(sanitizedId);
  17832. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  17833. ? sanitizedId.slice(0, -extensionName.length)
  17834. : sanitizedId;
  17835. if (isAbsolute$1(idWithoutExtension)) {
  17836. if (preserveModulesRoot && resolve$1(idWithoutExtension).startsWith(preserveModulesRoot)) {
  17837. return idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '');
  17838. }
  17839. else {
  17840. // handle edge case in Windows
  17841. if (this.inputBase === '/' && !idWithoutExtension.startsWith('/')) {
  17842. return relative$1(this.inputBase, idWithoutExtension.replace(/^[a-zA-Z]:[/\\]/, '/'));
  17843. }
  17844. return relative$1(this.inputBase, idWithoutExtension);
  17845. }
  17846. }
  17847. else {
  17848. return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + basename(idWithoutExtension));
  17849. }
  17850. }
  17851. getReexportSpecifiers() {
  17852. const { externalLiveBindings, interop } = this.outputOptions;
  17853. const reexportSpecifiers = new Map();
  17854. for (let exportName of this.getExportNames()) {
  17855. let dependency;
  17856. let imported;
  17857. let needsLiveBinding = false;
  17858. if (exportName[0] === '*') {
  17859. const id = exportName.slice(1);
  17860. if (interop(id) === 'defaultOnly') {
  17861. this.inputOptions.onLog(LOGLEVEL_WARN, logUnexpectedNamespaceReexport(id));
  17862. }
  17863. needsLiveBinding = externalLiveBindings;
  17864. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  17865. imported = exportName = '*';
  17866. }
  17867. else {
  17868. const variable = this.exportsByName.get(exportName);
  17869. if (variable instanceof SyntheticNamedExportVariable)
  17870. continue;
  17871. const module = variable.module;
  17872. if (module instanceof Module) {
  17873. dependency = this.chunkByModule.get(module);
  17874. if (dependency === this)
  17875. continue;
  17876. imported = dependency.getVariableExportName(variable);
  17877. needsLiveBinding = variable.isReassigned;
  17878. }
  17879. else {
  17880. dependency = this.externalChunkByModule.get(module);
  17881. imported = variable.name;
  17882. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  17883. return error(logUnexpectedNamedImport(module.id, imported, true));
  17884. }
  17885. needsLiveBinding =
  17886. externalLiveBindings &&
  17887. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  17888. }
  17889. }
  17890. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  17891. imported,
  17892. needsLiveBinding,
  17893. reexported: exportName
  17894. });
  17895. }
  17896. return reexportSpecifiers;
  17897. }
  17898. getReferencedFiles() {
  17899. const referencedFiles = new Set();
  17900. for (const module of this.orderedModules) {
  17901. for (const meta of module.importMetas) {
  17902. const fileName = meta.getReferencedFileName(this.pluginDriver);
  17903. if (fileName) {
  17904. referencedFiles.add(fileName);
  17905. }
  17906. }
  17907. }
  17908. return [...referencedFiles];
  17909. }
  17910. getRenderedDependencies() {
  17911. if (this.renderedDependencies) {
  17912. return this.renderedDependencies;
  17913. }
  17914. const importSpecifiers = this.getImportSpecifiers();
  17915. const reexportSpecifiers = this.getReexportSpecifiers();
  17916. const renderedDependencies = new Map();
  17917. const fileName = this.getFileName();
  17918. for (const dependency of this.dependencies) {
  17919. const imports = importSpecifiers.get(dependency) || null;
  17920. const reexports = reexportSpecifiers.get(dependency) || null;
  17921. const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
  17922. const importPath = dependency.getImportPath(fileName);
  17923. renderedDependencies.set(dependency, {
  17924. attributes: dependency instanceof ExternalChunk
  17925. ? dependency.getImportAttributes(this.snippets)
  17926. : null,
  17927. defaultVariableName: dependency.defaultVariableName,
  17928. globalName: dependency instanceof ExternalChunk &&
  17929. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  17930. getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  17931. importPath,
  17932. imports,
  17933. isChunk: dependency instanceof Chunk,
  17934. name: dependency.variableName,
  17935. namedExportsMode,
  17936. namespaceVariableName: dependency.namespaceVariableName,
  17937. reexports
  17938. });
  17939. }
  17940. return (this.renderedDependencies = renderedDependencies);
  17941. }
  17942. inlineChunkDependencies(chunk) {
  17943. for (const dep of chunk.dependencies) {
  17944. if (this.dependencies.has(dep))
  17945. continue;
  17946. this.dependencies.add(dep);
  17947. if (dep instanceof Chunk) {
  17948. this.inlineChunkDependencies(dep);
  17949. }
  17950. }
  17951. }
  17952. // This method changes properties on the AST before rendering and must not be async
  17953. renderModules(fileName) {
  17954. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  17955. const { compact, format, freeze, generatedCode: { symbols }, importAttributesKey } = outputOptions;
  17956. const { _, cnst, n } = snippets;
  17957. this.setDynamicImportResolutions(fileName);
  17958. this.setImportMetaResolutions(fileName);
  17959. this.setIdentifierRenderResolutions();
  17960. const magicString = new Bundle$1({ separator: `${n}${n}` });
  17961. const indent = getIndentString(orderedModules, outputOptions);
  17962. const usedModules = [];
  17963. let hoistedSource = '';
  17964. const accessedGlobals = new Set();
  17965. const renderedModuleSources = new Map();
  17966. const renderOptions = {
  17967. accessedDocumentCurrentScript: false,
  17968. exportNamesByVariable,
  17969. format,
  17970. freeze,
  17971. importAttributesKey,
  17972. indent,
  17973. pluginDriver,
  17974. snippets,
  17975. symbols,
  17976. useOriginalName: null
  17977. };
  17978. let usesTopLevelAwait = false;
  17979. for (const module of orderedModules) {
  17980. let renderedLength = 0;
  17981. let source;
  17982. if (module.isIncluded() || includedNamespaces.has(module)) {
  17983. const rendered = module.render(renderOptions);
  17984. if (!renderOptions.accessedDocumentCurrentScript &&
  17985. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  17986. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  17987. }
  17988. renderOptions.accessedDocumentCurrentScript = false;
  17989. ({ source } = rendered);
  17990. usesTopLevelAwait ||= rendered.usesTopLevelAwait;
  17991. renderedLength = source.length();
  17992. if (renderedLength) {
  17993. if (compact && source.lastLine().includes('//'))
  17994. source.append('\n');
  17995. renderedModuleSources.set(module, source);
  17996. magicString.addSource(source);
  17997. usedModules.push(module);
  17998. }
  17999. const namespace = module.namespace;
  18000. if (includedNamespaces.has(module)) {
  18001. const rendered = namespace.renderBlock(renderOptions);
  18002. if (namespace.renderFirst())
  18003. hoistedSource += n + rendered;
  18004. else
  18005. magicString.addSource(new MagicString(rendered));
  18006. }
  18007. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  18008. if (accessedGlobalVariables) {
  18009. for (const name of accessedGlobalVariables) {
  18010. accessedGlobals.add(name);
  18011. }
  18012. }
  18013. }
  18014. const { renderedExports, removedExports } = module.getRenderedExports();
  18015. renderedModules[module.id] = {
  18016. get code() {
  18017. return source?.toString() ?? null;
  18018. },
  18019. originalLength: module.originalCode.length,
  18020. removedExports,
  18021. renderedExports,
  18022. renderedLength
  18023. };
  18024. }
  18025. if (hoistedSource)
  18026. magicString.prepend(hoistedSource + n + n);
  18027. if (this.needsExportsShim) {
  18028. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  18029. }
  18030. const renderedSource = compact ? magicString : magicString.trim();
  18031. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  18032. onLog(LOGLEVEL_WARN, logEmptyChunk(this.getChunkName()));
  18033. }
  18034. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  18035. }
  18036. setDynamicImportResolutions(fileName) {
  18037. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  18038. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  18039. if (resolvedDynamicImport.chunk) {
  18040. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  18041. if (chunk === this) {
  18042. node.setInternalResolution(resolution.namespace);
  18043. }
  18044. else {
  18045. 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);
  18046. }
  18047. }
  18048. else {
  18049. const { node, resolution } = resolvedDynamicImport;
  18050. const [resolutionString, attributes] = this.getDynamicImportStringAndAttributes(resolution, fileName, node);
  18051. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, attributes, this, null);
  18052. }
  18053. }
  18054. }
  18055. setIdentifierRenderResolutions() {
  18056. const { format, generatedCode: { symbols }, interop, preserveModules, externalLiveBindings } = this.outputOptions;
  18057. const syntheticExports = new Set();
  18058. for (const exportName of this.getExportNames()) {
  18059. const exportVariable = this.exportsByName.get(exportName);
  18060. if (format !== 'es' &&
  18061. format !== 'system' &&
  18062. exportVariable.isReassigned &&
  18063. !exportVariable.isId) {
  18064. exportVariable.setRenderNames('exports', exportName);
  18065. }
  18066. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  18067. syntheticExports.add(exportVariable);
  18068. }
  18069. else {
  18070. exportVariable.setRenderNames(null, null);
  18071. }
  18072. }
  18073. for (const module of this.orderedModules) {
  18074. if (module.needsExportShim) {
  18075. this.needsExportsShim = true;
  18076. break;
  18077. }
  18078. }
  18079. const usedNames = new Set(['Object', 'Promise']);
  18080. if (this.needsExportsShim) {
  18081. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  18082. }
  18083. if (symbols) {
  18084. usedNames.add('Symbol');
  18085. }
  18086. switch (format) {
  18087. case 'system': {
  18088. usedNames.add('module').add('exports');
  18089. break;
  18090. }
  18091. case 'es': {
  18092. break;
  18093. }
  18094. case 'cjs': {
  18095. usedNames.add('module').add('require').add('__filename').add('__dirname');
  18096. }
  18097. // fallthrough
  18098. default: {
  18099. usedNames.add('exports');
  18100. for (const helper of HELPER_NAMES) {
  18101. usedNames.add(helper);
  18102. }
  18103. }
  18104. }
  18105. 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);
  18106. }
  18107. setImportMetaResolutions(fileName) {
  18108. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  18109. for (const module of orderedModules) {
  18110. for (const importMeta of module.importMetas) {
  18111. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  18112. }
  18113. if (includedNamespaces.has(module)) {
  18114. module.namespace.prepare(accessedGlobalsByScope);
  18115. }
  18116. }
  18117. }
  18118. setUpChunkImportsAndExportsForModule(module) {
  18119. const moduleImports = new Set(module.includedImports);
  18120. // when we are not preserving modules, we need to make all namespace variables available for
  18121. // rendering the namespace object
  18122. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  18123. const memberVariables = module.namespace.getMemberVariables();
  18124. for (const variable of Object.values(memberVariables)) {
  18125. if (variable.included) {
  18126. moduleImports.add(variable);
  18127. }
  18128. }
  18129. }
  18130. for (let variable of moduleImports) {
  18131. if (variable instanceof ExportDefaultVariable) {
  18132. variable = variable.getOriginalVariable();
  18133. }
  18134. if (variable instanceof SyntheticNamedExportVariable) {
  18135. variable = variable.getBaseVariable();
  18136. }
  18137. const chunk = this.chunkByModule.get(variable.module);
  18138. if (chunk !== this) {
  18139. this.imports.add(variable);
  18140. if (variable.module instanceof Module) {
  18141. this.checkCircularDependencyImport(variable, module);
  18142. // When preserving modules, we do not create namespace objects but directly
  18143. // use the actual namespaces, which would be broken by this logic.
  18144. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  18145. chunk.exports.add(variable);
  18146. }
  18147. }
  18148. }
  18149. }
  18150. if (this.includedNamespaces.has(module) ||
  18151. (module.info.isEntry && module.preserveSignature !== false) ||
  18152. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  18153. this.ensureReexportsAreAvailableForModule(module);
  18154. }
  18155. for (const { node, resolution } of module.dynamicImports) {
  18156. if (node.included &&
  18157. resolution instanceof Module &&
  18158. this.chunkByModule.get(resolution) === this &&
  18159. !this.includedNamespaces.has(resolution)) {
  18160. this.includedNamespaces.add(resolution);
  18161. this.ensureReexportsAreAvailableForModule(resolution);
  18162. }
  18163. }
  18164. }
  18165. }
  18166. function getChunkNameFromModule(module) {
  18167. return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id);
  18168. }
  18169. function getPredefinedChunkNameFromModule(module) {
  18170. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  18171. }
  18172. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  18173. const importedBindingsPerDependency = {};
  18174. for (const [dependency, declaration] of renderedDependencies) {
  18175. const specifiers = new Set();
  18176. if (declaration.imports) {
  18177. for (const { imported } of declaration.imports) {
  18178. specifiers.add(imported);
  18179. }
  18180. }
  18181. if (declaration.reexports) {
  18182. for (const { imported } of declaration.reexports) {
  18183. specifiers.add(imported);
  18184. }
  18185. }
  18186. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  18187. }
  18188. return importedBindingsPerDependency;
  18189. }
  18190. const QUERY_HASH_REGEX = /[#?]/;
  18191. const resolveFileName = (dependency) => dependency.getFileName();
  18192. /**
  18193. * Concatenate a number of iterables to a new iterable without fully evaluating
  18194. * their iterators. Useful when e.g. working with large sets or lists and when
  18195. * there is a chance that the iterators will not be fully exhausted.
  18196. */
  18197. function* concatLazy(iterables) {
  18198. for (const iterable of iterables) {
  18199. yield* iterable;
  18200. }
  18201. }
  18202. /**
  18203. * At its core, the algorithm first starts from each static or dynamic entry
  18204. * point and then assigns that entry point to all modules than can be reached
  18205. * via static imports. We call this the *dependent entry points* of that
  18206. * module.
  18207. *
  18208. * Then we group all modules with the same dependent entry points into chunks
  18209. * as those modules will always be loaded together.
  18210. *
  18211. * One non-trivial optimization we can apply is that dynamic entries are
  18212. * different from static entries in so far as when a dynamic import occurs,
  18213. * some modules are already in memory. If some of these modules are also
  18214. * dependencies of the dynamic entry, then it does not make sense to create a
  18215. * separate chunk for them. Instead, the dynamic import target can load them
  18216. * from the importing chunk.
  18217. *
  18218. * With regard to chunking, if B is implicitly loaded after A, then this can be
  18219. * handled the same way as if there was a dynamic import A => B.
  18220. *
  18221. * Example:
  18222. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  18223. * Then the initial algorithm would assign A into the A chunk, C into the C
  18224. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  18225. * points A and C.
  18226. * However we know that C can only be loaded from A, so A and its dependency B
  18227. * must already be in memory when C is loaded. So it is enough to create only
  18228. * two chunks A containing [AB] and C containing [C].
  18229. *
  18230. * So we do not assign the dynamic entry C as dependent entry point to modules
  18231. * that are already loaded.
  18232. *
  18233. * In a more complex example, let us assume that we have entry points X and Y.
  18234. * Further, let us assume
  18235. * X -> A, X -> B, X -> C,
  18236. * Y -> A, Y -> B,
  18237. * A => D,
  18238. * D -> B, D -> C
  18239. * So without dynamic import optimization, the dependent entry points are
  18240. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, so we would for now create six
  18241. * chunks.
  18242. *
  18243. * Now D is loaded only after A is loaded. But A is loaded if either X is
  18244. * loaded or Y is loaded. So the modules that are already in memory when D is
  18245. * loaded are the intersection of all modules that X depends on with all
  18246. * modules that Y depends on, which in this case are the modules A and B.
  18247. * We could also say they are all modules that have both X and Y as dependent
  18248. * entry points.
  18249. *
  18250. * So we can remove D as dependent entry point from A and B, which means they
  18251. * both now have only XY as dependent entry points and can be merged into the
  18252. * same chunk.
  18253. *
  18254. * Now let us extend this to the most general case where we have several
  18255. * dynamic importers for one dynamic entry point.
  18256. *
  18257. * In the most general form, it works like this:
  18258. * For each dynamic entry point, we have a number of dynamic importers, which
  18259. * are the modules importing it. Using the previous ideas, we can determine
  18260. * the modules already in memory for each dynamic importer by looking for all
  18261. * modules that have all the dependent entry points of the dynamic importer as
  18262. * dependent entry points.
  18263. * So the modules that are guaranteed to be in memory when the dynamic entry
  18264. * point is loaded are the intersection of the modules already in memory for
  18265. * each dynamic importer.
  18266. *
  18267. * Assuming that A => D and B => D and A has dependent entry points XY and B
  18268. * has dependent entry points YZ, then the modules guaranteed to be in memory
  18269. * are all modules that have at least XYZ as dependent entry points.
  18270. * We call XYZ the *dynamically dependent entry points* of D.
  18271. *
  18272. * Now there is one last case to consider: If one of the dynamically dependent
  18273. * entries is itself a dynamic entry, then any module is in memory that either
  18274. * is a dependency of that dynamic entry or again has the dynamic dependent
  18275. * entries of that dynamic entry as dependent entry points.
  18276. *
  18277. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  18278. * complexity with regard to dynamic entries that blew up for very large
  18279. * projects.
  18280. *
  18281. * If we have an efficient way to do Set operations, an alternative approach
  18282. * would be to instead collect already loaded modules per dynamic entry. And as
  18283. * all chunks from the initial grouping would behave the same, we can instead
  18284. * collect already loaded chunks for a performance improvement.
  18285. *
  18286. * To do that efficiently, need
  18287. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  18288. * imports that can be triggered by a dynamic entry
  18289. * - a Map of static dependencies per entry
  18290. * - a Map of already loaded chunks per entry that we initially populate with
  18291. * empty Sets for static entries and Sets containing all entries for dynamic
  18292. * entries
  18293. *
  18294. * For efficient operations, we assign each entry a numerical index and
  18295. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  18296. * bit index. Then the last two maps can be represented as arrays of BigInt
  18297. * values.
  18298. *
  18299. * Then we iterate through each dynamic entry. We set the already loaded modules
  18300. * to the intersection of the previously already loaded modules with the union
  18301. * of the already loaded modules of that chunk with its static dependencies.
  18302. *
  18303. * If the already loaded modules changed, then we use the Map of dynamic imports
  18304. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  18305. * them back into the iteration. As an additional optimization, we note for
  18306. * each dynamic entry which dynamic dependent entries have changed and only
  18307. * intersect those entries again on subsequent interations.
  18308. *
  18309. * Then we remove the dynamic entries from the list of dependent entries for
  18310. * those chunks that are already loaded for that dynamic entry and create
  18311. * another round of chunks.
  18312. */
  18313. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log) {
  18314. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  18315. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry } = analyzeModuleGraph(entries);
  18316. // Each chunk is identified by its position in this array
  18317. const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  18318. const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(allEntries, chunkAtoms);
  18319. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  18320. // If we no longer want this, we should make a copy here.
  18321. const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  18322. const awaitedAlreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, allEntries);
  18323. // This mutates the dependentEntries in chunkAtoms
  18324. removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry);
  18325. const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
  18326. chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
  18327. alias: null,
  18328. modules
  18329. })));
  18330. return chunkDefinitions;
  18331. }
  18332. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  18333. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  18334. const manualChunkModulesByAlias = Object.create(null);
  18335. for (const [entry, alias] of manualChunkAliasByEntry) {
  18336. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] ||= []), modulesInManualChunks);
  18337. }
  18338. const manualChunks = Object.entries(manualChunkModulesByAlias);
  18339. const chunkDefinitions = new Array(manualChunks.length);
  18340. let index = 0;
  18341. for (const [alias, modules] of manualChunks) {
  18342. chunkDefinitions[index++] = { alias, modules };
  18343. }
  18344. return { chunkDefinitions, modulesInManualChunks };
  18345. }
  18346. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  18347. const modulesToHandle = new Set([entry]);
  18348. for (const module of modulesToHandle) {
  18349. modulesInManualChunks.add(module);
  18350. manualChunkModules.push(module);
  18351. for (const dependency of module.dependencies) {
  18352. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  18353. modulesToHandle.add(dependency);
  18354. }
  18355. }
  18356. }
  18357. }
  18358. function analyzeModuleGraph(entries) {
  18359. const dynamicEntryModules = new Set();
  18360. const awaitedDynamicEntryModules = new Set();
  18361. const dependentEntriesByModule = new Map();
  18362. const allEntriesSet = new Set(entries);
  18363. const dynamicImportModulesByEntry = new Array(allEntriesSet.size);
  18364. const awaitedDynamicImportModulesByEntry = new Array(allEntriesSet.size);
  18365. let entryIndex = 0;
  18366. for (const currentEntry of allEntriesSet) {
  18367. const dynamicImportsForCurrentEntry = new Set();
  18368. const awaitedDynamicImportsForCurrentEntry = new Set();
  18369. dynamicImportModulesByEntry[entryIndex] = dynamicImportsForCurrentEntry;
  18370. awaitedDynamicImportModulesByEntry[entryIndex] = awaitedDynamicImportsForCurrentEntry;
  18371. const staticDependencies = new Set([currentEntry]);
  18372. for (const module of staticDependencies) {
  18373. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  18374. for (const dependency of module.getDependenciesToBeIncluded()) {
  18375. if (!(dependency instanceof ExternalModule)) {
  18376. staticDependencies.add(dependency);
  18377. }
  18378. }
  18379. for (const { resolution } of module.dynamicImports) {
  18380. if (resolution instanceof Module &&
  18381. resolution.includedDynamicImporters.length > 0 &&
  18382. !allEntriesSet.has(resolution)) {
  18383. dynamicEntryModules.add(resolution);
  18384. allEntriesSet.add(resolution);
  18385. dynamicImportsForCurrentEntry.add(resolution);
  18386. for (const includedDirectTopLevelAwaitingDynamicImporter of resolution.includedDirectTopLevelAwaitingDynamicImporters) {
  18387. if (staticDependencies.has(includedDirectTopLevelAwaitingDynamicImporter)) {
  18388. awaitedDynamicEntryModules.add(resolution);
  18389. awaitedDynamicImportsForCurrentEntry.add(resolution);
  18390. break;
  18391. }
  18392. }
  18393. }
  18394. }
  18395. for (const dependency of module.implicitlyLoadedBefore) {
  18396. if (!allEntriesSet.has(dependency)) {
  18397. dynamicEntryModules.add(dependency);
  18398. allEntriesSet.add(dependency);
  18399. }
  18400. }
  18401. }
  18402. entryIndex++;
  18403. }
  18404. const allEntries = [...allEntriesSet];
  18405. const { awaitedDynamicEntries, awaitedDynamicImportsByEntry, dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry);
  18406. return {
  18407. allEntries,
  18408. awaitedDynamicImportsByEntry,
  18409. dependentEntriesByModule,
  18410. dynamicallyDependentEntriesByAwaitedDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, awaitedDynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedDirectTopLevelAwaitingDynamicImporters),
  18411. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedDynamicImporters),
  18412. dynamicImportsByEntry
  18413. };
  18414. }
  18415. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry) {
  18416. const entryIndexByModule = new Map();
  18417. const dynamicEntries = new Set();
  18418. const awaitedDynamicEntries = new Set();
  18419. for (const [entryIndex, entry] of allEntries.entries()) {
  18420. entryIndexByModule.set(entry, entryIndex);
  18421. if (dynamicEntryModules.has(entry)) {
  18422. dynamicEntries.add(entryIndex);
  18423. }
  18424. if (awaitedDynamicEntryModules.has(entry)) {
  18425. awaitedDynamicEntries.add(entryIndex);
  18426. }
  18427. }
  18428. const dynamicImportsByEntry = getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule);
  18429. const awaitedDynamicImportsByEntry = getDynamicImportsByEntry(awaitedDynamicImportModulesByEntry, entryIndexByModule);
  18430. return {
  18431. awaitedDynamicEntries,
  18432. awaitedDynamicImportsByEntry,
  18433. dynamicEntries,
  18434. dynamicImportsByEntry
  18435. };
  18436. }
  18437. function getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule) {
  18438. const dynamicImportsByEntry = new Array(dynamicImportModulesByEntry.length);
  18439. let index = 0;
  18440. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  18441. const dynamicImports = new Set();
  18442. for (const dynamicEntry of dynamicImportModules) {
  18443. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  18444. }
  18445. dynamicImportsByEntry[index++] = dynamicImports;
  18446. }
  18447. return dynamicImportsByEntry;
  18448. }
  18449. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, getDynamicImporters) {
  18450. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  18451. for (const dynamicEntryIndex of dynamicEntries) {
  18452. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  18453. const dynamicEntry = allEntries[dynamicEntryIndex];
  18454. for (const importer of concatLazy([
  18455. getDynamicImporters(dynamicEntry),
  18456. dynamicEntry.implicitlyLoadedAfter
  18457. ])) {
  18458. for (const entry of dependentEntriesByModule.get(importer)) {
  18459. dynamicallyDependentEntries.add(entry);
  18460. }
  18461. }
  18462. }
  18463. return dynamicallyDependentEntriesByDynamicEntry;
  18464. }
  18465. function getChunksWithSameDependentEntries(modulesWithDependentEntries) {
  18466. const chunkModules = Object.create(null);
  18467. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  18468. let chunkSignature = 0n;
  18469. for (const entryIndex of dependentEntries) {
  18470. chunkSignature |= 1n << BigInt(entryIndex);
  18471. }
  18472. (chunkModules[String(chunkSignature)] ||= {
  18473. dependentEntries: new Set(dependentEntries),
  18474. modules: []
  18475. }).modules.push(...modules);
  18476. }
  18477. return Object.values(chunkModules);
  18478. }
  18479. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  18480. for (const [module, dependentEntries] of dependentEntriesByModule) {
  18481. if (!modulesInManualChunks.has(module)) {
  18482. yield { dependentEntries, modules: [module] };
  18483. }
  18484. }
  18485. }
  18486. function getStaticDependencyAtomsByEntry(allEntries, chunkAtoms) {
  18487. // The indices correspond to the indices in allEntries. The atoms correspond
  18488. // to bits in the bigint values where chunk 0 is the lowest bit.
  18489. const staticDependencyAtomsByEntry = allEntries.map(() => 0n);
  18490. // This toggles the bits for each atom that is a dependency of an entry
  18491. let atomMask = 1n;
  18492. for (const { dependentEntries } of chunkAtoms) {
  18493. for (const entryIndex of dependentEntries) {
  18494. staticDependencyAtomsByEntry[entryIndex] |= atomMask;
  18495. }
  18496. atomMask <<= 1n;
  18497. }
  18498. return staticDependencyAtomsByEntry;
  18499. }
  18500. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  18501. function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  18502. // Dynamic entries have all atoms as already loaded initially because we then
  18503. // intersect with the static dependency atoms of all dynamic importers.
  18504. // Static entries cannot have already loaded atoms.
  18505. const alreadyLoadedAtomsByEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  18506. for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByDynamicEntry) {
  18507. // We delete here so that they can be added again if necessary to be handled
  18508. // again by the loop
  18509. dynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  18510. const knownLoadedAtoms = alreadyLoadedAtomsByEntry[dynamicEntryIndex];
  18511. let updatedLoadedAtoms = knownLoadedAtoms;
  18512. for (const entryIndex of dynamicallyDependentEntries) {
  18513. updatedLoadedAtoms &=
  18514. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  18515. }
  18516. // If the knownLoadedAtoms changed, all dependent dynamic entries need to be
  18517. // updated again
  18518. if (updatedLoadedAtoms !== knownLoadedAtoms) {
  18519. alreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
  18520. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  18521. // If this adds an entry that was deleted before, it will be handled
  18522. // again. This is the reason why we delete every entry from this map
  18523. // that we processed.
  18524. getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  18525. }
  18526. }
  18527. }
  18528. return alreadyLoadedAtomsByEntry;
  18529. }
  18530. /**
  18531. * This removes all unnecessary dynamic entries from the dependentEntries in its
  18532. * first argument if a chunk is already loaded without that entry.
  18533. */
  18534. function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry) {
  18535. // Remove entries from dependent entries if a chunk is already loaded without
  18536. // that entry. Do not remove already loaded atoms where all dynamic imports
  18537. // are awaited to avoid cycles in the output.
  18538. let chunkMask = 1n;
  18539. for (const { dependentEntries } of chunkAtoms) {
  18540. for (const entryIndex of dependentEntries) {
  18541. if ((alreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === chunkMask &&
  18542. (awaitedAlreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === 0n) {
  18543. dependentEntries.delete(entryIndex);
  18544. }
  18545. }
  18546. chunkMask <<= 1n;
  18547. }
  18548. }
  18549. function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
  18550. const chunksBySignature = Object.create(null);
  18551. const chunkByModule = new Map();
  18552. const sizeByAtom = new Array(chunkAtoms.length);
  18553. let sideEffectAtoms = 0n;
  18554. let atomMask = 1n;
  18555. let index = 0;
  18556. for (const { dependentEntries, modules } of chunkAtoms) {
  18557. let chunkSignature = 0n;
  18558. let correlatedAtoms = -1n;
  18559. for (const entryIndex of dependentEntries) {
  18560. chunkSignature |= 1n << BigInt(entryIndex);
  18561. // Correlated atoms are the atoms that are guaranteed to be loaded as
  18562. // well when a given atom is loaded. It is the intersection of the already
  18563. // loaded modules of each chunk merged with its static dependencies.
  18564. correlatedAtoms &=
  18565. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  18566. }
  18567. const chunk = (chunksBySignature[String(chunkSignature)] ||= {
  18568. containedAtoms: 0n,
  18569. correlatedAtoms,
  18570. dependencies: new Set(),
  18571. dependentChunks: new Set(),
  18572. dependentEntries: new Set(dependentEntries),
  18573. modules: [],
  18574. pure: true,
  18575. size: 0
  18576. });
  18577. let atomSize = 0;
  18578. let pure = true;
  18579. for (const module of modules) {
  18580. chunkByModule.set(module, chunk);
  18581. // Unfortunately, we cannot take tree-shaking into account here because
  18582. // rendering did not happen yet, but we can detect empty modules
  18583. if (module.isIncluded()) {
  18584. pure &&= !module.hasEffects();
  18585. // we use a trivial size for the default minChunkSize to improve
  18586. // performance
  18587. atomSize += minChunkSize > 1 ? module.estimateSize() : 1;
  18588. }
  18589. }
  18590. if (!pure) {
  18591. sideEffectAtoms |= atomMask;
  18592. }
  18593. sizeByAtom[index++] = atomSize;
  18594. chunk.containedAtoms |= atomMask;
  18595. chunk.modules.push(...modules);
  18596. chunk.pure &&= pure;
  18597. chunk.size += atomSize;
  18598. atomMask <<= 1n;
  18599. }
  18600. const chunks = Object.values(chunksBySignature);
  18601. sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
  18602. return { chunks, sideEffectAtoms, sizeByAtom };
  18603. }
  18604. function addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, nextAvailableAtomMask) {
  18605. const signatureByExternalModule = new Map();
  18606. let externalSideEffectAtoms = 0n;
  18607. for (const chunk of chunks) {
  18608. const { dependencies, modules } = chunk;
  18609. for (const module of modules) {
  18610. for (const dependency of module.getDependenciesToBeIncluded()) {
  18611. if (dependency instanceof ExternalModule) {
  18612. if (dependency.info.moduleSideEffects) {
  18613. const signature = getOrCreate(signatureByExternalModule, dependency, () => {
  18614. const signature = nextAvailableAtomMask;
  18615. nextAvailableAtomMask <<= 1n;
  18616. externalSideEffectAtoms |= signature;
  18617. return signature;
  18618. });
  18619. chunk.containedAtoms |= signature;
  18620. chunk.correlatedAtoms |= signature;
  18621. }
  18622. }
  18623. else {
  18624. const dependencyChunk = chunkByModule.get(dependency);
  18625. if (dependencyChunk && dependencyChunk !== chunk) {
  18626. dependencies.add(dependencyChunk);
  18627. dependencyChunk.dependentChunks.add(chunk);
  18628. }
  18629. }
  18630. }
  18631. }
  18632. }
  18633. return externalSideEffectAtoms;
  18634. }
  18635. /**
  18636. * This function tries to get rid of small chunks by merging them with other
  18637. * chunks.
  18638. *
  18639. * We can only merge chunks safely if after the merge, loading any entry point
  18640. * in any allowed order will not trigger side effects that should not have been
  18641. * triggered. While side effects are usually things like global function calls,
  18642. * global variable mutations or potentially thrown errors, details do not
  18643. * matter here, and we just discern chunks without side effects (pure chunks)
  18644. * from other chunks.
  18645. *
  18646. * As a first step, we assign each pre-generated chunk with side effects a
  18647. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  18648. *
  18649. * Now to determine the side effects of loading a chunk, one also has to take
  18650. * the side effects of its dependencies into account. So if A depends on B
  18651. * (A -> B) and both have side effects, loading A triggers effects AB.
  18652. *
  18653. * Now from the previous step we know that each chunk is uniquely determine by
  18654. * the entry points that depend on it and cause it to load, which we will call
  18655. * its dependent entry points.
  18656. *
  18657. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  18658. * Starting from that idea, we can determine a set of chunks—and thus a set
  18659. * of side effects—that must have been triggered if a certain chunk has been
  18660. * loaded. Basically, it is the intersection of all chunks loaded by the
  18661. * dependent entry points of a given chunk. We call the corresponding side
  18662. * effects the correlated side effects of that chunk.
  18663. *
  18664. * Example:
  18665. * X -> ABC, Y -> ADE, A-> F, B -> D
  18666. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  18667. * The intersection is ADF. So we know that when A is loaded, D and F must also
  18668. * be in memory even though neither D nor A is a dependency of the other.
  18669. * If all have side effects, we call ADF the correlated side effects of A. The
  18670. * correlated side effects need to remain constant when merging chunks.
  18671. *
  18672. * In contrast, we have the dependency side effects of A, which represents
  18673. * the side effects we trigger if we directly load A. In this example, the
  18674. * dependency side effects are AF.
  18675. * For entry chunks, dependency and correlated side effects are the same.
  18676. *
  18677. * With these concepts, merging chunks is allowed if the correlated side
  18678. * effects of each entry do not change. Thus, we are allowed to merge two
  18679. * chunks if
  18680. *
  18681. * a) the dependency side effects of each chunk are a subset of the correlated
  18682. * side effects of the other chunk, so no additional side effects are
  18683. * triggered for any entry, or
  18684. * b) The dependent entry points of chunk A are a subset of the dependent entry
  18685. * points of chunk B while the dependency side effects of A are a subset of
  18686. * the correlated side effects of B. Because in that scenario, whenever A is
  18687. * loaded, B is loaded as well. But there are cases when B is loaded where A
  18688. * is not loaded. So if we merge the chunks, all dependency side effects of
  18689. * A will be added to the correlated side effects of B, and as the latter is
  18690. * not allowed to change, the former need to be a subset of the latter.
  18691. *
  18692. * Another consideration when merging small chunks into other chunks is to
  18693. * avoid
  18694. * that too much additional code is loaded. This is achieved when the dependent
  18695. * entries of the small chunk are a subset of the dependent entries of the
  18696. * other
  18697. * chunk. Because then when the small chunk is loaded, the other chunk was
  18698. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  18699. * additional size of the small chunk is loaded unnecessarily.
  18700. *
  18701. * So the algorithm performs merges in two passes:
  18702. *
  18703. * 1. First we try to merge small chunks A only into other chunks B if the
  18704. * dependent entries of A are a subset of the dependent entries of B and the
  18705. * dependency side effects of A are a subset of the correlated side effects
  18706. * of B.
  18707. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  18708. * following the rule (a), starting with the smallest chunks to look for
  18709. * possible merge targets.
  18710. */
  18711. function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log) {
  18712. timeStart('optimize chunks', 3);
  18713. const chunkPartition = getPartitionedChunks(chunks, minChunkSize);
  18714. if (!chunkPartition) {
  18715. timeEnd('optimize chunks', 3);
  18716. return chunks; // the actual modules
  18717. }
  18718. if (minChunkSize > 1) {
  18719. log('info', logOptimizeChunkStatus(chunks.length, chunkPartition.small.size, 'Initially'));
  18720. }
  18721. mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
  18722. if (minChunkSize > 1) {
  18723. log('info', logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  18724. }
  18725. timeEnd('optimize chunks', 3);
  18726. return [...chunkPartition.small, ...chunkPartition.big];
  18727. }
  18728. function getPartitionedChunks(chunks, minChunkSize) {
  18729. const smallChunks = [];
  18730. const bigChunks = [];
  18731. for (const chunk of chunks) {
  18732. (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
  18733. }
  18734. if (smallChunks.length === 0) {
  18735. return null;
  18736. }
  18737. smallChunks.sort(compareChunkSize);
  18738. bigChunks.sort(compareChunkSize);
  18739. return {
  18740. big: new Set(bigChunks),
  18741. small: new Set(smallChunks)
  18742. };
  18743. }
  18744. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  18745. return sizeA - sizeB;
  18746. }
  18747. function mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom) {
  18748. const { small } = chunkPartition;
  18749. for (const mergedChunk of small) {
  18750. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, sideEffectAtoms, sizeByAtom,
  18751. // In the default case, we do not accept size increases
  18752. minChunkSize <= 1 ? 1 : Infinity);
  18753. if (bestTargetChunk) {
  18754. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  18755. small.delete(mergedChunk);
  18756. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  18757. bestTargetChunk.modules.push(...modules);
  18758. bestTargetChunk.size += size;
  18759. bestTargetChunk.pure &&= pure;
  18760. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  18761. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  18762. bestTargetChunk.containedAtoms |= containedAtoms;
  18763. for (const entry of mergedChunk.dependentEntries) {
  18764. dependentEntries.add(entry);
  18765. }
  18766. for (const dependency of mergedChunk.dependencies) {
  18767. dependencies.add(dependency);
  18768. dependency.dependentChunks.delete(mergedChunk);
  18769. dependency.dependentChunks.add(bestTargetChunk);
  18770. }
  18771. for (const dependentChunk of mergedChunk.dependentChunks) {
  18772. dependentChunks.add(dependentChunk);
  18773. dependentChunk.dependencies.delete(mergedChunk);
  18774. dependentChunk.dependencies.add(bestTargetChunk);
  18775. }
  18776. dependencies.delete(bestTargetChunk);
  18777. dependentChunks.delete(bestTargetChunk);
  18778. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  18779. }
  18780. }
  18781. }
  18782. function findBestMergeTarget(mergedChunk, { big, small }, sideEffectAtoms, sizeByAtom, smallestAdditionalSize) {
  18783. let bestTargetChunk = null;
  18784. // In the default case, we do not accept size increases
  18785. for (const targetChunk of concatLazy([small, big])) {
  18786. if (mergedChunk === targetChunk)
  18787. continue;
  18788. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  18789. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  18790. bestTargetChunk = targetChunk;
  18791. if (additionalSizeAfterMerge === 0)
  18792. break;
  18793. smallestAdditionalSize = additionalSizeAfterMerge;
  18794. }
  18795. }
  18796. return bestTargetChunk;
  18797. }
  18798. /**
  18799. * Determine the additional unused code size that would be added by merging the
  18800. * two chunks. This is not an exact measurement but rather an upper bound. If
  18801. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  18802. * is returned.
  18803. * Merging will not produce cycles if none of the direct non-merged
  18804. * dependencies of a chunk have the other chunk as a transitive dependency.
  18805. */
  18806. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  18807. // The maximum additional unused code size allowed to be added by the merge,
  18808. // taking dependencies into account, needs to be below this number
  18809. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  18810. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  18811. return firstSize < currentAdditionalSize
  18812. ? firstSize +
  18813. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  18814. : Infinity;
  18815. }
  18816. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  18817. const { correlatedAtoms } = dependencyChunk;
  18818. let dependencyAtoms = dependentChunk.containedAtoms;
  18819. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  18820. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  18821. return Infinity;
  18822. }
  18823. const chunksToCheck = new Set(dependentChunk.dependencies);
  18824. for (const { dependencies, containedAtoms } of chunksToCheck) {
  18825. dependencyAtoms |= containedAtoms;
  18826. const containedSideEffects = containedAtoms & sideEffectAtoms;
  18827. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  18828. return Infinity;
  18829. }
  18830. for (const dependency of dependencies) {
  18831. if (dependency === dependencyChunk) {
  18832. return Infinity;
  18833. }
  18834. chunksToCheck.add(dependency);
  18835. }
  18836. }
  18837. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  18838. }
  18839. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  18840. let size = 0;
  18841. let atomIndex = 0;
  18842. let atomSignature = 1n;
  18843. const { length } = sizeByAtom;
  18844. for (; atomIndex < length; atomIndex++) {
  18845. if ((atoms & atomSignature) === atomSignature) {
  18846. size += sizeByAtom[atomIndex];
  18847. }
  18848. atomSignature <<= 1n;
  18849. if (size >= currentAdditionalSize) {
  18850. return Infinity;
  18851. }
  18852. }
  18853. return size;
  18854. }
  18855. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  18856. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  18857. }
  18858. // ported from https://github.com/substack/node-commondir
  18859. function commondir(files) {
  18860. if (files.length === 0)
  18861. return '/';
  18862. if (files.length === 1)
  18863. return dirname(files[0]);
  18864. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  18865. const pathSegments = file.split(/\/+|\\+/);
  18866. let index;
  18867. for (index = 0; commonSegments[index] === pathSegments[index] &&
  18868. index < Math.min(commonSegments.length, pathSegments.length); index++)
  18869. ;
  18870. return commonSegments.slice(0, index);
  18871. }, files[0].split(/\/+|\\+/));
  18872. // Windows correctly handles paths with forward-slashes
  18873. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  18874. }
  18875. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  18876. function sortByExecutionOrder(units) {
  18877. units.sort(compareExecIndex);
  18878. }
  18879. // This process is currently faulty in so far as it only takes the first entry
  18880. // module into account and assumes that dynamic imports are imported in a
  18881. // certain order.
  18882. // A better algorithm would follow every possible execution path and mark which
  18883. // modules are executed before or after which other modules. THen the chunking
  18884. // would need to take care that in each chunk, all modules are always executed
  18885. // in the same sequence.
  18886. function analyseModuleExecution(entryModules) {
  18887. let nextExecIndex = 0;
  18888. const cyclePaths = [];
  18889. const analysedModules = new Set();
  18890. const dynamicImports = new Set();
  18891. const parents = new Map();
  18892. const orderedModules = [];
  18893. const handleSyncLoadedModule = (module, parent) => {
  18894. if (parents.has(module)) {
  18895. if (!analysedModules.has(module)) {
  18896. cyclePaths.push(getCyclePath(module, parent, parents));
  18897. }
  18898. return;
  18899. }
  18900. parents.set(module, parent);
  18901. analyseModule(module);
  18902. };
  18903. const analyseModule = (module) => {
  18904. if (module instanceof Module) {
  18905. for (const dependency of module.dependencies) {
  18906. handleSyncLoadedModule(dependency, module);
  18907. }
  18908. for (const dependency of module.implicitlyLoadedBefore) {
  18909. dynamicImports.add(dependency);
  18910. }
  18911. for (const { resolution, node } of module.dynamicImports) {
  18912. if (resolution instanceof Module) {
  18913. if (node.withinTopLevelAwait) {
  18914. handleSyncLoadedModule(resolution, module);
  18915. }
  18916. else {
  18917. dynamicImports.add(resolution);
  18918. }
  18919. }
  18920. }
  18921. orderedModules.push(module);
  18922. }
  18923. module.execIndex = nextExecIndex++;
  18924. analysedModules.add(module);
  18925. };
  18926. for (const currentEntry of entryModules) {
  18927. if (!parents.has(currentEntry)) {
  18928. parents.set(currentEntry, null);
  18929. analyseModule(currentEntry);
  18930. }
  18931. }
  18932. for (const currentEntry of dynamicImports) {
  18933. if (!parents.has(currentEntry)) {
  18934. parents.set(currentEntry, null);
  18935. analyseModule(currentEntry);
  18936. }
  18937. }
  18938. return { cyclePaths, orderedModules };
  18939. }
  18940. function getCyclePath(module, parent, parents) {
  18941. const cycleSymbol = Symbol(module.id);
  18942. const path = [module.id];
  18943. let nextModule = parent;
  18944. module.cycles.add(cycleSymbol);
  18945. while (nextModule !== module) {
  18946. nextModule.cycles.add(cycleSymbol);
  18947. path.push(nextModule.id);
  18948. nextModule = parents.get(nextModule);
  18949. }
  18950. path.push(path[0]);
  18951. path.reverse();
  18952. return path;
  18953. }
  18954. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  18955. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  18956. const cnst = constBindings ? 'const' : 'var';
  18957. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  18958. const getFunctionIntro = arrowFunctions
  18959. ? (parameters, { isAsync, name }) => {
  18960. const singleParameter = parameters.length === 1;
  18961. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  18962. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  18963. }
  18964. : getNonArrowFunctionIntro;
  18965. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  18966. `${getFunctionIntro(parameters, {
  18967. isAsync: false,
  18968. name
  18969. })}${arrowFunctions
  18970. ? lineBreakIndent
  18971. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  18972. : ''
  18973. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  18974. arrowFunctions
  18975. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  18976. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  18977. ];
  18978. const isValidPropertyName = reservedNamesAsProps
  18979. ? (name) => VALID_IDENTIFIER_REGEXP.test(name)
  18980. : (name) => !RESERVED_NAMES.has(name) && VALID_IDENTIFIER_REGEXP.test(name);
  18981. return {
  18982. _,
  18983. cnst,
  18984. getDirectReturnFunction,
  18985. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  18986. const [left, right] = getDirectReturnFunction(parameters, {
  18987. functionReturn: true,
  18988. lineBreakIndent: null,
  18989. name: null
  18990. });
  18991. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  18992. },
  18993. getFunctionIntro,
  18994. getNonArrowFunctionIntro,
  18995. getObject(fields, { lineBreakIndent }) {
  18996. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  18997. return `{${fields
  18998. .map(([key, value]) => {
  18999. if (key === null)
  19000. return `${prefix}${value}`;
  19001. const keyInObject = stringifyObjectKeyIfNeeded(key);
  19002. return key === value && objectShorthand && key === keyInObject
  19003. ? prefix + key
  19004. : `${prefix}${keyInObject}:${_}${value}`;
  19005. })
  19006. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  19007. },
  19008. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  19009. n,
  19010. s
  19011. };
  19012. }
  19013. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  19014. class Source {
  19015. constructor(filename, content) {
  19016. this.isOriginal = true;
  19017. this.filename = filename;
  19018. this.content = content;
  19019. }
  19020. traceSegment(line, column, name) {
  19021. return { column, line, name, source: this };
  19022. }
  19023. }
  19024. class Link {
  19025. constructor(map, sources) {
  19026. this.sources = sources;
  19027. this.names = map.names;
  19028. this.mappings = map.mappings;
  19029. }
  19030. traceMappings() {
  19031. const sources = [];
  19032. const sourceIndexMap = new Map();
  19033. const sourcesContent = [];
  19034. const names = [];
  19035. const nameIndexMap = new Map();
  19036. const mappings = [];
  19037. for (const line of this.mappings) {
  19038. const tracedLine = [];
  19039. for (const segment of line) {
  19040. if (segment.length === 1)
  19041. continue;
  19042. const source = this.sources[segment[1]];
  19043. if (!source)
  19044. continue;
  19045. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  19046. if (traced) {
  19047. const { column, line, name, source: { content, filename } } = traced;
  19048. let sourceIndex = sourceIndexMap.get(filename);
  19049. if (sourceIndex === undefined) {
  19050. sourceIndex = sources.length;
  19051. sources.push(filename);
  19052. sourceIndexMap.set(filename, sourceIndex);
  19053. sourcesContent[sourceIndex] = content;
  19054. }
  19055. else if (sourcesContent[sourceIndex] == null) {
  19056. sourcesContent[sourceIndex] = content;
  19057. }
  19058. else if (content != null && sourcesContent[sourceIndex] !== content) {
  19059. return error(logConflictingSourcemapSources(filename));
  19060. }
  19061. const tracedSegment = [segment[0], sourceIndex, line, column];
  19062. if (name) {
  19063. let nameIndex = nameIndexMap.get(name);
  19064. if (nameIndex === undefined) {
  19065. nameIndex = names.length;
  19066. names.push(name);
  19067. nameIndexMap.set(name, nameIndex);
  19068. }
  19069. tracedSegment[4] = nameIndex;
  19070. }
  19071. tracedLine.push(tracedSegment);
  19072. }
  19073. }
  19074. mappings.push(tracedLine);
  19075. }
  19076. return { mappings, names, sources, sourcesContent };
  19077. }
  19078. traceSegment(line, column, name) {
  19079. const segments = this.mappings[line];
  19080. if (!segments)
  19081. return null;
  19082. // binary search through segments for the given column
  19083. let searchStart = 0;
  19084. let searchEnd = segments.length - 1;
  19085. while (searchStart <= searchEnd) {
  19086. const m = (searchStart + searchEnd) >> 1;
  19087. const segment = segments[m];
  19088. // If a sourcemap does not have sufficient resolution to contain a
  19089. // necessary mapping, e.g. because it only contains line information, we
  19090. // use the best approximation we could find
  19091. if (segment[0] === column || searchStart === searchEnd) {
  19092. if (segment.length == 1)
  19093. return null;
  19094. const source = this.sources[segment[1]];
  19095. if (!source)
  19096. return null;
  19097. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  19098. }
  19099. if (segment[0] > column) {
  19100. searchEnd = m - 1;
  19101. }
  19102. else {
  19103. searchStart = m + 1;
  19104. }
  19105. }
  19106. return null;
  19107. }
  19108. }
  19109. function getLinkMap(log) {
  19110. return function linkMap(source, map) {
  19111. if (!map.missing) {
  19112. return new Link(map, [source]);
  19113. }
  19114. log(LOGLEVEL_WARN, logSourcemapBroken(map.plugin));
  19115. return new Link({
  19116. mappings: [],
  19117. names: []
  19118. }, [source]);
  19119. };
  19120. }
  19121. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  19122. let source;
  19123. if (originalSourcemap) {
  19124. const sources = originalSourcemap.sources;
  19125. const sourcesContent = originalSourcemap.sourcesContent || [];
  19126. const directory = dirname(id) || '.';
  19127. const sourceRoot = originalSourcemap.sourceRoot || '.';
  19128. const baseSources = sources.map((source, index) => new Source(resolve$1(directory, sourceRoot, source), sourcesContent[index]));
  19129. source = new Link(originalSourcemap, baseSources);
  19130. }
  19131. else {
  19132. source = new Source(id, originalCode);
  19133. }
  19134. return sourcemapChain.reduce(linkMap, source);
  19135. }
  19136. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  19137. const linkMap = getLinkMap(log);
  19138. const moduleSources = modules
  19139. .filter(module => !module.excludeFromSourcemap)
  19140. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  19141. const link = new Link(map, moduleSources);
  19142. const source = bundleSourcemapChain.reduce(linkMap, link);
  19143. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  19144. if (file) {
  19145. const directory = dirname(file);
  19146. sources = sources.map((source) => relative(directory, source));
  19147. file = basename(file);
  19148. }
  19149. sourcesContent = (excludeContent ? null : sourcesContent);
  19150. for (const module of modules) {
  19151. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  19152. }
  19153. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  19154. }
  19155. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  19156. if (sourcemapChain.length === 0) {
  19157. return originalSourcemap;
  19158. }
  19159. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  19160. const map = source.traceMappings();
  19161. return decodedSourcemap({ version: 3, ...map });
  19162. }
  19163. let textEncoder;
  19164. const getHash64 = input => xxhashBase64Url(ensureBuffer(input));
  19165. const getHash36 = input => xxhashBase36(ensureBuffer(input));
  19166. const getHash16 = input => xxhashBase16(ensureBuffer(input));
  19167. const hasherByType = {
  19168. base36: getHash36,
  19169. base64: getHash64,
  19170. hex: getHash16
  19171. };
  19172. function ensureBuffer(input) {
  19173. if (typeof input === 'string') {
  19174. if (typeof Buffer === 'undefined') {
  19175. textEncoder ??= new TextEncoder();
  19176. return textEncoder.encode(input);
  19177. }
  19178. return Buffer.from(input);
  19179. }
  19180. return input;
  19181. }
  19182. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  19183. // this for an actual sourceMappingURL
  19184. let SOURCEMAPPING_URL = 'sourceMa';
  19185. SOURCEMAPPING_URL += 'ppingURL';
  19186. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  19187. timeStart('render chunks', 2);
  19188. reserveEntryChunksInBundle(chunks);
  19189. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  19190. timeEnd('render chunks', 2);
  19191. timeStart('transform chunks', 2);
  19192. const getHash = hasherByType[outputOptions.hashCharacters];
  19193. const chunkGraph = getChunkGraph(chunks);
  19194. const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
  19195. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
  19196. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  19197. timeEnd('transform chunks', 2);
  19198. }
  19199. function reserveEntryChunksInBundle(chunks) {
  19200. for (const chunk of chunks) {
  19201. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  19202. // reserves name in bundle as side effect if it does not contain a hash
  19203. chunk.getPreliminaryFileName();
  19204. }
  19205. }
  19206. }
  19207. function getChunkGraph(chunks) {
  19208. return Object.fromEntries(chunks.map(chunk => {
  19209. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  19210. return [renderedChunkInfo.fileName, renderedChunkInfo];
  19211. }));
  19212. }
  19213. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  19214. let map = null;
  19215. const sourcemapChain = [];
  19216. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  19217. if (result == null)
  19218. return code;
  19219. if (typeof result === 'string')
  19220. result = {
  19221. code: result,
  19222. map: undefined
  19223. };
  19224. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  19225. if (result.map !== null) {
  19226. const map = decodedSourcemap(result.map);
  19227. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  19228. }
  19229. return result.code;
  19230. });
  19231. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  19232. if (!compact && code[code.length - 1] !== '\n')
  19233. code += '\n';
  19234. if (sourcemap) {
  19235. timeStart('sourcemaps', 3);
  19236. let resultingFile;
  19237. if (file)
  19238. resultingFile = resolve$1(sourcemapFile || file);
  19239. else if (dir)
  19240. resultingFile = resolve$1(dir, fileName);
  19241. else
  19242. resultingFile = resolve$1(fileName);
  19243. const decodedMap = magicString.generateDecodedMap({});
  19244. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  19245. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  19246. let sourcePath = map.sources[sourcesIndex];
  19247. const sourcemapPath = `${resultingFile}.map`;
  19248. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  19249. if (typeof ignoreList !== 'boolean') {
  19250. error(logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  19251. }
  19252. if (ignoreList) {
  19253. if (map.x_google_ignoreList === undefined) {
  19254. map.x_google_ignoreList = [];
  19255. }
  19256. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  19257. map.x_google_ignoreList.push(sourcesIndex);
  19258. }
  19259. }
  19260. if (sourcemapPathTransform) {
  19261. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  19262. if (typeof sourcePath !== 'string') {
  19263. error(logFailedValidation(`sourcemapPathTransform function must return a string.`));
  19264. }
  19265. }
  19266. map.sources[sourcesIndex] = normalize(sourcePath);
  19267. }
  19268. timeEnd('sourcemaps', 3);
  19269. }
  19270. return {
  19271. code,
  19272. map
  19273. };
  19274. }
  19275. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
  19276. const nonHashedChunksWithPlaceholders = [];
  19277. const renderedChunksByPlaceholder = new Map();
  19278. const hashDependenciesByPlaceholder = new Map();
  19279. const initialHashesByPlaceholder = new Map();
  19280. const placeholders = new Set();
  19281. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  19282. if (hashPlaceholder)
  19283. placeholders.add(hashPlaceholder);
  19284. }
  19285. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  19286. const transformedChunk = {
  19287. chunk,
  19288. fileName,
  19289. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  19290. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  19291. };
  19292. const { code, map } = transformedChunk;
  19293. if (hashPlaceholder) {
  19294. // To create a reproducible content-only hash, all placeholders are
  19295. // replaced with the same value before hashing
  19296. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  19297. let contentToHash = transformedCode;
  19298. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  19299. if (pluginHash) {
  19300. augmentation += pluginHash;
  19301. }
  19302. return augmentation;
  19303. });
  19304. if (hashAugmentation) {
  19305. contentToHash += hashAugmentation;
  19306. }
  19307. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  19308. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  19309. containedPlaceholders,
  19310. contentHash: getHash(contentToHash)
  19311. });
  19312. }
  19313. else {
  19314. nonHashedChunksWithPlaceholders.push(transformedChunk);
  19315. }
  19316. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  19317. if (map && sourcemapHashPlaceholder) {
  19318. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  19319. }
  19320. }));
  19321. return {
  19322. hashDependenciesByPlaceholder,
  19323. initialHashesByPlaceholder,
  19324. nonHashedChunksWithPlaceholders,
  19325. placeholders,
  19326. renderedChunksByPlaceholder
  19327. };
  19328. }
  19329. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
  19330. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  19331. for (const placeholder of placeholders) {
  19332. const { fileName } = renderedChunksByPlaceholder.get(placeholder);
  19333. let contentToHash = '';
  19334. const hashDependencyPlaceholders = new Set([placeholder]);
  19335. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  19336. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  19337. contentToHash += contentHash;
  19338. for (const containedPlaceholder of containedPlaceholders) {
  19339. // When looping over a map, setting an entry only causes a new iteration if the key is new
  19340. hashDependencyPlaceholders.add(containedPlaceholder);
  19341. }
  19342. }
  19343. let finalFileName;
  19344. let finalHash;
  19345. do {
  19346. // In case of a hash collision, create a hash of the hash
  19347. if (finalHash) {
  19348. contentToHash = finalHash;
  19349. }
  19350. finalHash = getHash(contentToHash).slice(0, placeholder.length);
  19351. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  19352. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  19353. bundle[finalFileName] = FILE_PLACEHOLDER;
  19354. hashesByPlaceholder.set(placeholder, finalHash);
  19355. }
  19356. return hashesByPlaceholder;
  19357. }
  19358. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  19359. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  19360. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  19361. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  19362. let finalSourcemapFileName = null;
  19363. if (map) {
  19364. if (options.sourcemapDebugIds) {
  19365. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  19366. }
  19367. finalSourcemapFileName = sourcemapFileName
  19368. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  19369. : `${finalFileName}.map`;
  19370. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  19371. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  19372. }
  19373. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  19374. }
  19375. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  19376. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  19377. let finalSourcemapFileName = null;
  19378. if (map) {
  19379. if (options.sourcemapDebugIds) {
  19380. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  19381. }
  19382. finalSourcemapFileName = sourcemapFileName
  19383. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  19384. : `${fileName}.map`;
  19385. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  19386. }
  19387. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  19388. }
  19389. }
  19390. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  19391. let url;
  19392. if (sourcemap === 'inline') {
  19393. url = map.toUrl();
  19394. }
  19395. else {
  19396. const sourcemapFileName = basename(fileName);
  19397. url = sourcemapBaseUrl
  19398. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  19399. : sourcemapFileName;
  19400. pluginDriver.emitFile({
  19401. fileName,
  19402. originalFileName: null,
  19403. source: map.toString(),
  19404. type: 'asset'
  19405. });
  19406. }
  19407. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  19408. }
  19409. function calculateDebugIdAndGetComment(code, map) {
  19410. const hash = hasherByType.hex(code);
  19411. const debugId = [
  19412. hash.slice(0, 8),
  19413. hash.slice(8, 12),
  19414. '4' + hash.slice(12, 15),
  19415. ((parseInt(hash.slice(15, 16), 16) & 3) | 8).toString(16) + hash.slice(17, 20),
  19416. hash.slice(20, 32)
  19417. ].join('-');
  19418. map.debugId = debugId;
  19419. return '//# debugId=' + debugId + '\n';
  19420. }
  19421. class Bundle {
  19422. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  19423. this.outputOptions = outputOptions;
  19424. this.unsetOptions = unsetOptions;
  19425. this.inputOptions = inputOptions;
  19426. this.pluginDriver = pluginDriver;
  19427. this.graph = graph;
  19428. this.facadeChunkByModule = new Map();
  19429. this.includedNamespaces = new Set();
  19430. }
  19431. async generate(isWrite) {
  19432. timeStart('GENERATE', 1);
  19433. const outputBundleBase = Object.create(null);
  19434. const outputBundle = getOutputBundle(outputBundleBase);
  19435. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  19436. try {
  19437. timeStart('initialize render', 2);
  19438. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  19439. timeEnd('initialize render', 2);
  19440. timeStart('generate chunks', 2);
  19441. const getHashPlaceholder = getHashPlaceholderGenerator();
  19442. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  19443. if (chunks.length > 1) {
  19444. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  19445. }
  19446. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  19447. for (const chunk of chunks) {
  19448. chunk.generateExports();
  19449. chunk.inlineTransitiveImports();
  19450. }
  19451. timeEnd('generate chunks', 2);
  19452. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  19453. }
  19454. catch (error_) {
  19455. await this.pluginDriver.hookParallel('renderError', [error_]);
  19456. throw error_;
  19457. }
  19458. removeUnreferencedAssets(outputBundle);
  19459. timeStart('generate bundle', 2);
  19460. await this.pluginDriver.hookSeq('generateBundle', [
  19461. this.outputOptions,
  19462. outputBundle,
  19463. isWrite
  19464. ]);
  19465. this.finaliseAssets(outputBundle);
  19466. timeEnd('generate bundle', 2);
  19467. timeEnd('GENERATE', 1);
  19468. return outputBundleBase;
  19469. }
  19470. async addManualChunks(manualChunks) {
  19471. const manualChunkAliasByEntry = new Map();
  19472. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  19473. alias,
  19474. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  19475. })));
  19476. for (const { alias, entries } of chunkEntries) {
  19477. for (const entry of entries) {
  19478. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  19479. }
  19480. }
  19481. return manualChunkAliasByEntry;
  19482. }
  19483. assignManualChunks(getManualChunk) {
  19484. const manualChunkAliasesWithEntry = [];
  19485. const manualChunksApi = {
  19486. getModuleIds: () => this.graph.modulesById.keys(),
  19487. getModuleInfo: this.graph.getModuleInfo
  19488. };
  19489. for (const module of this.graph.modulesById.values()) {
  19490. if (module instanceof Module) {
  19491. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  19492. if (typeof manualChunkAlias === 'string') {
  19493. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  19494. }
  19495. }
  19496. }
  19497. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  19498. const manualChunkAliasByEntry = new Map();
  19499. for (const [alias, module] of manualChunkAliasesWithEntry) {
  19500. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  19501. }
  19502. return manualChunkAliasByEntry;
  19503. }
  19504. finaliseAssets(bundle) {
  19505. if (this.outputOptions.validate) {
  19506. for (const file of Object.values(bundle)) {
  19507. if ('code' in file) {
  19508. try {
  19509. parseAst(file.code, { jsx: this.inputOptions.jsx !== false });
  19510. }
  19511. catch (error_) {
  19512. this.inputOptions.onLog(LOGLEVEL_WARN, logChunkInvalid(file, error_));
  19513. }
  19514. }
  19515. }
  19516. }
  19517. this.pluginDriver.finaliseAssets();
  19518. }
  19519. async generateChunks(bundle, getHashPlaceholder) {
  19520. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  19521. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  19522. ? await this.addManualChunks(manualChunks)
  19523. : this.assignManualChunks(manualChunks);
  19524. const snippets = getGenerateCodeSnippets(this.outputOptions);
  19525. const includedModules = getIncludedModules(this.graph.modulesById);
  19526. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  19527. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  19528. const executableModule = inlineDynamicImports
  19529. ? [{ alias: null, modules: includedModules }]
  19530. : preserveModules
  19531. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  19532. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog);
  19533. const chunks = new Array(executableModule.length);
  19534. const chunkByModule = new Map();
  19535. let index = 0;
  19536. for (const { alias, modules } of executableModule) {
  19537. sortByExecutionOrder(modules);
  19538. 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);
  19539. chunks[index++] = chunk;
  19540. }
  19541. for (const chunk of chunks) {
  19542. chunk.link();
  19543. }
  19544. const facades = [];
  19545. for (const chunk of chunks) {
  19546. facades.push(...chunk.generateFacades());
  19547. }
  19548. return [...chunks, ...facades];
  19549. }
  19550. }
  19551. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  19552. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  19553. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  19554. if (typeof outputOptions.file === 'string')
  19555. 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'));
  19556. if (outputOptions.sourcemapFile)
  19557. return error(logInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  19558. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  19559. 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'));
  19560. }
  19561. function getIncludedModules(modulesById) {
  19562. const includedModules = [];
  19563. for (const module of modulesById.values()) {
  19564. if (module instanceof Module &&
  19565. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  19566. includedModules.push(module);
  19567. }
  19568. }
  19569. return includedModules;
  19570. }
  19571. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  19572. const absoluteEntryModulePaths = [];
  19573. for (const module of includedModules) {
  19574. if ((module.info.isEntry || preserveModules) && isAbsolute$1(module.id)) {
  19575. absoluteEntryModulePaths.push(module.id);
  19576. }
  19577. }
  19578. return absoluteEntryModulePaths;
  19579. }
  19580. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  19581. const externalChunkByModule = new Map();
  19582. for (const module of modulesById.values()) {
  19583. if (module instanceof ExternalModule) {
  19584. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  19585. }
  19586. }
  19587. return externalChunkByModule;
  19588. }
  19589. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  19590. const existingAlias = manualChunkAliasByEntry.get(module);
  19591. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  19592. return error(logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  19593. }
  19594. manualChunkAliasByEntry.set(module, alias);
  19595. }
  19596. function flru (max) {
  19597. var num, curr, prev;
  19598. var limit = max;
  19599. function keep(key, value) {
  19600. if (++num > limit) {
  19601. prev = curr;
  19602. reset(1);
  19603. ++num;
  19604. }
  19605. curr[key] = value;
  19606. }
  19607. function reset(isPartial) {
  19608. num = 0;
  19609. curr = Object.create(null);
  19610. isPartial || (prev=Object.create(null));
  19611. }
  19612. reset();
  19613. return {
  19614. clear: reset,
  19615. has: function (key) {
  19616. return curr[key] !== void 0 || prev[key] !== void 0;
  19617. },
  19618. get: function (key) {
  19619. var val = curr[key];
  19620. if (val !== void 0) return val;
  19621. if ((val=prev[key]) !== void 0) {
  19622. keep(key, val);
  19623. return val;
  19624. }
  19625. },
  19626. set: function (key, value) {
  19627. if (curr[key] !== void 0) {
  19628. curr[key] = value;
  19629. } else {
  19630. keep(key, value);
  19631. }
  19632. }
  19633. };
  19634. }
  19635. class GlobalScope extends Scope {
  19636. constructor() {
  19637. super();
  19638. this.parent = null;
  19639. this.variables.set('undefined', new UndefinedVariable());
  19640. }
  19641. findVariable(name) {
  19642. let variable = this.variables.get(name);
  19643. if (!variable) {
  19644. variable = new GlobalVariable(name);
  19645. this.variables.set(name, variable);
  19646. }
  19647. return variable;
  19648. }
  19649. }
  19650. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  19651. let skipped = null;
  19652. let replaceContext = null;
  19653. if (skip) {
  19654. skipped = new Set();
  19655. for (const skippedCall of skip) {
  19656. if (source === skippedCall.source && importer === skippedCall.importer) {
  19657. skipped.add(skippedCall.plugin);
  19658. }
  19659. }
  19660. replaceContext = (pluginContext, plugin) => ({
  19661. ...pluginContext,
  19662. resolve: (source, importer, { attributes, custom, isEntry, skipSelf } = BLANK) => {
  19663. skipSelf ??= true;
  19664. return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  19665. }
  19666. });
  19667. }
  19668. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, isEntry }], replaceContext, skipped);
  19669. }
  19670. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  19671. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes);
  19672. if (pluginResult != null) {
  19673. const [resolveIdResult, plugin] = pluginResult;
  19674. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  19675. return {
  19676. ...resolveIdResult,
  19677. resolvedBy: plugin.name
  19678. };
  19679. }
  19680. if (typeof resolveIdResult === 'string') {
  19681. return {
  19682. id: resolveIdResult,
  19683. resolvedBy: plugin.name
  19684. };
  19685. }
  19686. return resolveIdResult;
  19687. }
  19688. // external modules (non-entry modules that start with neither '.' or '/')
  19689. // are skipped at this stage.
  19690. if (importer !== undefined && !isAbsolute$1(source) && source[0] !== '.')
  19691. return null;
  19692. // `resolve` processes paths from right to left, prepending them until an
  19693. // absolute path is created. Absolute importees therefore shortcircuit the
  19694. // resolve call and require no special handing on our part.
  19695. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  19696. return addJsExtensionIfNecessary(importer ? resolve$1(dirname(importer), source) : resolve$1(source), preserveSymlinks);
  19697. }
  19698. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  19699. return ((await findFile(file, preserveSymlinks)) ??
  19700. (await findFile(file + '.mjs', preserveSymlinks)) ??
  19701. (await findFile(file + '.js', preserveSymlinks)));
  19702. }
  19703. async function findFile(file, preserveSymlinks) {
  19704. try {
  19705. const stats = await lstat(file);
  19706. if (!preserveSymlinks && stats.isSymbolicLink())
  19707. return await findFile(await realpath(file), preserveSymlinks);
  19708. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  19709. // check case
  19710. const name = basename(file);
  19711. const files = await readdir(dirname(file));
  19712. if (files.includes(name))
  19713. return file;
  19714. }
  19715. }
  19716. catch {
  19717. // suppress
  19718. }
  19719. }
  19720. function stripBom(content) {
  19721. if (content.charCodeAt(0) === 0xfe_ff) {
  19722. return stripBom(content.slice(1));
  19723. }
  19724. return content;
  19725. }
  19726. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  19727. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  19728. function createPluginCache(cache) {
  19729. return {
  19730. delete(id) {
  19731. return delete cache[id];
  19732. },
  19733. get(id) {
  19734. const item = cache[id];
  19735. if (!item)
  19736. return;
  19737. item[0] = 0;
  19738. return item[1];
  19739. },
  19740. has(id) {
  19741. const item = cache[id];
  19742. if (!item)
  19743. return false;
  19744. item[0] = 0;
  19745. return true;
  19746. },
  19747. set(id, value) {
  19748. cache[id] = [0, value];
  19749. }
  19750. };
  19751. }
  19752. function getTrackedPluginCache(pluginCache, onUse) {
  19753. return {
  19754. delete(id) {
  19755. onUse();
  19756. return pluginCache.delete(id);
  19757. },
  19758. get(id) {
  19759. onUse();
  19760. return pluginCache.get(id);
  19761. },
  19762. has(id) {
  19763. onUse();
  19764. return pluginCache.has(id);
  19765. },
  19766. set(id, value) {
  19767. onUse();
  19768. return pluginCache.set(id, value);
  19769. }
  19770. };
  19771. }
  19772. const NO_CACHE = {
  19773. delete() {
  19774. return false;
  19775. },
  19776. get() {
  19777. return undefined;
  19778. },
  19779. has() {
  19780. return false;
  19781. },
  19782. set() { }
  19783. };
  19784. function uncacheablePluginError(pluginName) {
  19785. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  19786. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  19787. return error(logAnonymousPluginCache());
  19788. }
  19789. return error(logDuplicatePluginName(pluginName));
  19790. }
  19791. function getCacheForUncacheablePlugin(pluginName) {
  19792. return {
  19793. delete() {
  19794. return uncacheablePluginError(pluginName);
  19795. },
  19796. get() {
  19797. return uncacheablePluginError(pluginName);
  19798. },
  19799. has() {
  19800. return uncacheablePluginError(pluginName);
  19801. },
  19802. set() {
  19803. return uncacheablePluginError(pluginName);
  19804. }
  19805. };
  19806. }
  19807. async function asyncFlatten(array) {
  19808. do {
  19809. array = (await Promise.all(array)).flat(Infinity);
  19810. } while (array.some((v) => v?.then));
  19811. return array;
  19812. }
  19813. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  19814. const { onwarn, onLog } = config;
  19815. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  19816. if (onLog) {
  19817. const minimalPriority = logLevelPriority[logLevel];
  19818. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  19819. if (level === LOGLEVEL_ERROR) {
  19820. return error(normalizeLog(handledLog));
  19821. }
  19822. if (logLevelPriority[level] >= minimalPriority) {
  19823. defaultOnLog(level, normalizeLog(handledLog));
  19824. }
  19825. });
  19826. }
  19827. return defaultOnLog;
  19828. };
  19829. const getDefaultOnLog = (printLog, onwarn) => onwarn
  19830. ? (level, log) => {
  19831. if (level === LOGLEVEL_WARN) {
  19832. onwarn(addLogToString(log), warning => printLog(LOGLEVEL_WARN, normalizeLog(warning)));
  19833. }
  19834. else {
  19835. printLog(level, log);
  19836. }
  19837. }
  19838. : printLog;
  19839. const addLogToString = (log) => {
  19840. Object.defineProperty(log, 'toString', {
  19841. value: () => log.message,
  19842. writable: true
  19843. });
  19844. return log;
  19845. };
  19846. const normalizeLog = (log) => typeof log === 'string'
  19847. ? { message: log }
  19848. : typeof log === 'function'
  19849. ? normalizeLog(log())
  19850. : log;
  19851. const defaultPrintLog = (level, { message }) => {
  19852. switch (level) {
  19853. case LOGLEVEL_WARN: {
  19854. return console.warn(message);
  19855. }
  19856. case LOGLEVEL_DEBUG: {
  19857. return console.debug(message);
  19858. }
  19859. default: {
  19860. return console.info(message);
  19861. }
  19862. }
  19863. };
  19864. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  19865. const validOptionSet = new Set(validOptions);
  19866. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  19867. if (unknownOptions.length > 0) {
  19868. log(LOGLEVEL_WARN, logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  19869. }
  19870. }
  19871. const treeshakePresets = {
  19872. recommended: {
  19873. annotations: true,
  19874. correctVarValueBeforeDeclaration: false,
  19875. manualPureFunctions: EMPTY_ARRAY,
  19876. moduleSideEffects: () => true,
  19877. propertyReadSideEffects: true,
  19878. tryCatchDeoptimization: true,
  19879. unknownGlobalSideEffects: false
  19880. },
  19881. safest: {
  19882. annotations: true,
  19883. correctVarValueBeforeDeclaration: true,
  19884. manualPureFunctions: EMPTY_ARRAY,
  19885. moduleSideEffects: () => true,
  19886. propertyReadSideEffects: true,
  19887. tryCatchDeoptimization: true,
  19888. unknownGlobalSideEffects: true
  19889. },
  19890. smallest: {
  19891. annotations: true,
  19892. correctVarValueBeforeDeclaration: false,
  19893. manualPureFunctions: EMPTY_ARRAY,
  19894. moduleSideEffects: () => false,
  19895. propertyReadSideEffects: false,
  19896. tryCatchDeoptimization: false,
  19897. unknownGlobalSideEffects: false
  19898. }
  19899. };
  19900. const jsxPresets = {
  19901. preserve: {
  19902. factory: null,
  19903. fragment: null,
  19904. importSource: null,
  19905. mode: 'preserve'
  19906. },
  19907. 'preserve-react': {
  19908. factory: 'React.createElement',
  19909. fragment: 'React.Fragment',
  19910. importSource: 'react',
  19911. mode: 'preserve'
  19912. },
  19913. react: {
  19914. factory: 'React.createElement',
  19915. fragment: 'React.Fragment',
  19916. importSource: 'react',
  19917. mode: 'classic'
  19918. },
  19919. 'react-jsx': {
  19920. factory: 'React.createElement',
  19921. importSource: 'react',
  19922. jsxImportSource: 'react/jsx-runtime',
  19923. mode: 'automatic'
  19924. }
  19925. };
  19926. const generatedCodePresets = {
  19927. es2015: {
  19928. arrowFunctions: true,
  19929. constBindings: true,
  19930. objectShorthand: true,
  19931. reservedNamesAsProps: true,
  19932. symbols: true
  19933. },
  19934. es5: {
  19935. arrowFunctions: false,
  19936. constBindings: false,
  19937. objectShorthand: false,
  19938. reservedNamesAsProps: true,
  19939. symbols: false
  19940. }
  19941. };
  19942. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  19943. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  19944. if (typeof value === 'string') {
  19945. const preset = presets[value];
  19946. if (preset) {
  19947. return preset;
  19948. }
  19949. error(logInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  19950. }
  19951. return objectifyOption(value);
  19952. };
  19953. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  19954. const presetName = value?.preset;
  19955. if (presetName) {
  19956. const preset = presets[presetName];
  19957. if (preset) {
  19958. return { ...preset, ...value };
  19959. }
  19960. else {
  19961. error(logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  19962. }
  19963. }
  19964. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  19965. };
  19966. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  19967. async function transform(source, module, pluginDriver, log) {
  19968. const id = module.id;
  19969. const sourcemapChain = [];
  19970. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  19971. const originalCode = source.code;
  19972. let ast = source.ast;
  19973. const transformDependencies = [];
  19974. const emittedFiles = [];
  19975. let customTransformCache = false;
  19976. const useCustomTransformCache = () => (customTransformCache = true);
  19977. let pluginName = '';
  19978. let currentSource = source.code;
  19979. function transformReducer(previousCode, result, plugin) {
  19980. let code;
  19981. let map;
  19982. if (typeof result === 'string') {
  19983. code = result;
  19984. }
  19985. else if (result && typeof result === 'object') {
  19986. module.updateOptions(result);
  19987. if (result.code == null) {
  19988. if (result.map || result.ast) {
  19989. log(LOGLEVEL_WARN, logNoTransformMapOrAstWithoutCode(plugin.name));
  19990. }
  19991. return previousCode;
  19992. }
  19993. ({ code, map, ast } = result);
  19994. }
  19995. else {
  19996. return previousCode;
  19997. }
  19998. // strict null check allows 'null' maps to not be pushed to the chain,
  19999. // while 'undefined' gets the missing map warning
  20000. if (map !== null) {
  20001. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  20002. missing: true,
  20003. plugin: plugin.name
  20004. });
  20005. }
  20006. currentSource = code;
  20007. return code;
  20008. }
  20009. const getLogHandler = (handler) => (log, pos) => {
  20010. log = normalizeLog(log);
  20011. if (pos)
  20012. augmentCodeLocation(log, pos, currentSource, id);
  20013. log.id = id;
  20014. log.hook = 'transform';
  20015. handler(log);
  20016. };
  20017. let code;
  20018. try {
  20019. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  20020. pluginName = plugin.name;
  20021. return {
  20022. ...pluginContext,
  20023. addWatchFile(id) {
  20024. transformDependencies.push(id);
  20025. pluginContext.addWatchFile(id);
  20026. },
  20027. cache: customTransformCache
  20028. ? pluginContext.cache
  20029. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  20030. debug: getLogHandler(pluginContext.debug),
  20031. emitFile(emittedFile) {
  20032. emittedFiles.push(emittedFile);
  20033. return pluginDriver.emitFile(emittedFile);
  20034. },
  20035. error(error_, pos) {
  20036. if (typeof error_ === 'string')
  20037. error_ = { message: error_ };
  20038. if (pos)
  20039. augmentCodeLocation(error_, pos, currentSource, id);
  20040. error_.id = id;
  20041. error_.hook = 'transform';
  20042. return pluginContext.error(error_);
  20043. },
  20044. getCombinedSourcemap() {
  20045. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  20046. if (!combinedMap) {
  20047. const magicString = new MagicString(originalCode);
  20048. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  20049. }
  20050. if (originalSourcemap !== combinedMap) {
  20051. originalSourcemap = combinedMap;
  20052. sourcemapChain.length = 0;
  20053. }
  20054. return new SourceMap({
  20055. ...combinedMap,
  20056. file: null,
  20057. sourcesContent: combinedMap.sourcesContent
  20058. });
  20059. },
  20060. info: getLogHandler(pluginContext.info),
  20061. setAssetSource() {
  20062. return this.error(logInvalidSetAssetSourceCall());
  20063. },
  20064. warn: getLogHandler(pluginContext.warn)
  20065. };
  20066. });
  20067. }
  20068. catch (error_) {
  20069. return error(logPluginError(error_, pluginName, { hook: 'transform', id }));
  20070. }
  20071. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  20072. emittedFiles.length > 0)
  20073. module.transformFiles = emittedFiles;
  20074. return {
  20075. ast,
  20076. code,
  20077. customTransformCache,
  20078. originalCode,
  20079. originalSourcemap,
  20080. sourcemapChain,
  20081. transformDependencies
  20082. };
  20083. }
  20084. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  20085. class ModuleLoader {
  20086. constructor(graph, modulesById, options, pluginDriver) {
  20087. this.graph = graph;
  20088. this.modulesById = modulesById;
  20089. this.options = options;
  20090. this.pluginDriver = pluginDriver;
  20091. this.implicitEntryModules = new Set();
  20092. this.indexedEntryModules = [];
  20093. this.latestLoadModulesPromise = Promise.resolve();
  20094. this.moduleLoadPromises = new Map();
  20095. this.modulesWithLoadedDependencies = new Set();
  20096. this.nextChunkNamePriority = 0;
  20097. this.nextEntryModuleIndex = 0;
  20098. this.resolveId = async (source, importer, customOptions, isEntry, attributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  20099. ? false
  20100. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes), importer, source), attributes);
  20101. this.hasModuleSideEffects = options.treeshake
  20102. ? options.treeshake.moduleSideEffects
  20103. : () => true;
  20104. }
  20105. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  20106. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  20107. await this.awaitLoadModulesPromise();
  20108. return result;
  20109. }
  20110. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  20111. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  20112. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  20113. const firstChunkNamePriority = this.nextChunkNamePriority;
  20114. this.nextChunkNamePriority += unresolvedEntryModules.length;
  20115. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  20116. for (const [index, entryModule] of entryModules.entries()) {
  20117. entryModule.isUserDefinedEntryPoint =
  20118. entryModule.isUserDefinedEntryPoint || isUserDefined;
  20119. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  20120. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  20121. if (existingIndexedModule) {
  20122. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  20123. }
  20124. else {
  20125. this.indexedEntryModules.push({
  20126. index: firstEntryModuleIndex + index,
  20127. module: entryModule
  20128. });
  20129. }
  20130. }
  20131. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  20132. return entryModules;
  20133. }));
  20134. await this.awaitLoadModulesPromise();
  20135. return {
  20136. entryModules: this.indexedEntryModules.map(({ module }) => module),
  20137. implicitEntryModules: [...this.implicitEntryModules],
  20138. newEntryModules
  20139. };
  20140. }
  20141. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  20142. const unresolvedModule = {
  20143. fileName: fileName || null,
  20144. id,
  20145. importer,
  20146. name: name || null
  20147. };
  20148. const module = implicitlyLoadedAfterOneOf
  20149. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  20150. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  20151. if (preserveSignature != null) {
  20152. module.preserveSignature = preserveSignature;
  20153. }
  20154. return module;
  20155. }
  20156. async preloadModule(resolvedId) {
  20157. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  20158. return module.info;
  20159. }
  20160. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  20161. const chunkNamePriority = this.nextChunkNamePriority++;
  20162. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  20163. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  20164. if (!entryModule.info.isEntry) {
  20165. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  20166. // We need to check again if this is still an entry module as these
  20167. // changes need to be performed atomically to avoid race conditions
  20168. // if the same module is re-emitted as an entry module.
  20169. // The inverse changes happen in "handleExistingModule"
  20170. if (!entryModule.info.isEntry) {
  20171. this.implicitEntryModules.add(entryModule);
  20172. for (const module of implicitlyLoadedAfterModules) {
  20173. entryModule.implicitlyLoadedAfter.add(module);
  20174. }
  20175. for (const dependant of entryModule.implicitlyLoadedAfter) {
  20176. dependant.implicitlyLoadedBefore.add(entryModule);
  20177. }
  20178. }
  20179. }
  20180. return entryModule;
  20181. }));
  20182. }
  20183. async addModuleSource(id, importer, module) {
  20184. let source;
  20185. try {
  20186. source = await this.graph.fileOperationQueue.run(async () => {
  20187. const content = await this.pluginDriver.hookFirst('load', [id]);
  20188. if (content !== null)
  20189. return content;
  20190. this.graph.watchFiles[id] = true;
  20191. return await readFile(id, 'utf8');
  20192. });
  20193. }
  20194. catch (error_) {
  20195. let message = `Could not load ${id}`;
  20196. if (importer)
  20197. message += ` (imported by ${relativeId(importer)})`;
  20198. message += `: ${error_.message}`;
  20199. error_.message = message;
  20200. throw error_;
  20201. }
  20202. const sourceDescription = typeof source === 'string'
  20203. ? { code: source }
  20204. : source != null && typeof source === 'object' && typeof source.code === 'string'
  20205. ? source
  20206. : error(logBadLoader(id));
  20207. sourceDescription.code = stripBom(sourceDescription.code);
  20208. const cachedModule = this.graph.cachedModules.get(id);
  20209. if (cachedModule &&
  20210. !cachedModule.customTransformCache &&
  20211. cachedModule.originalCode === sourceDescription.code &&
  20212. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  20213. {
  20214. ast: cachedModule.ast,
  20215. code: cachedModule.code,
  20216. id: cachedModule.id,
  20217. meta: cachedModule.meta,
  20218. moduleSideEffects: cachedModule.moduleSideEffects,
  20219. resolvedSources: cachedModule.resolvedIds,
  20220. syntheticNamedExports: cachedModule.syntheticNamedExports
  20221. }
  20222. ]))) {
  20223. if (cachedModule.transformFiles) {
  20224. for (const emittedFile of cachedModule.transformFiles)
  20225. this.pluginDriver.emitFile(emittedFile);
  20226. }
  20227. await module.setSource(cachedModule);
  20228. }
  20229. else {
  20230. module.updateOptions(sourceDescription);
  20231. await module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  20232. }
  20233. }
  20234. async awaitLoadModulesPromise() {
  20235. let startingPromise;
  20236. do {
  20237. startingPromise = this.latestLoadModulesPromise;
  20238. await startingPromise;
  20239. } while (startingPromise !== this.latestLoadModulesPromise);
  20240. }
  20241. extendLoadModulesPromise(loadNewModulesPromise) {
  20242. this.latestLoadModulesPromise = Promise.all([
  20243. loadNewModulesPromise,
  20244. this.latestLoadModulesPromise
  20245. ]);
  20246. this.latestLoadModulesPromise.catch(() => {
  20247. /* Avoid unhandled Promise rejections */
  20248. });
  20249. return loadNewModulesPromise;
  20250. }
  20251. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  20252. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  20253. if (resolvedId === null)
  20254. return null;
  20255. if (typeof resolvedId === 'string') {
  20256. dynamicImport.resolution = resolvedId;
  20257. return null;
  20258. }
  20259. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  20260. })));
  20261. for (const dependency of dependencies) {
  20262. if (dependency) {
  20263. module.dynamicDependencies.add(dependency);
  20264. dependency.dynamicImporters.push(module.id);
  20265. }
  20266. }
  20267. }
  20268. // If this is a preload, then this method always waits for the dependencies of
  20269. // the module to be resolved.
  20270. // Otherwise, if the module does not exist, it waits for the module and all
  20271. // its dependencies to be loaded.
  20272. // Otherwise, it returns immediately.
  20273. async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  20274. const existingModule = this.modulesById.get(id);
  20275. if (existingModule instanceof Module) {
  20276. if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
  20277. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
  20278. }
  20279. await this.handleExistingModule(existingModule, isEntry, isPreload);
  20280. return existingModule;
  20281. }
  20282. if (existingModule instanceof ExternalModule) {
  20283. return error(logExternalModulesCannotBeTransformedToModules(existingModule.id));
  20284. }
  20285. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
  20286. this.modulesById.set(id, module);
  20287. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  20288. this.getResolveStaticDependencyPromises(module),
  20289. this.getResolveDynamicImportPromises(module),
  20290. loadAndResolveDependenciesPromise
  20291. ]);
  20292. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  20293. loadAndResolveDependenciesPromise.catch(() => {
  20294. /* avoid unhandled promise rejections */
  20295. });
  20296. this.moduleLoadPromises.set(module, loadPromise);
  20297. const resolveDependencyPromises = await loadPromise;
  20298. if (!isPreload) {
  20299. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  20300. }
  20301. else if (isPreload === RESOLVE_DEPENDENCIES) {
  20302. await loadAndResolveDependenciesPromise;
  20303. }
  20304. return module;
  20305. }
  20306. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  20307. if (this.modulesWithLoadedDependencies.has(module)) {
  20308. return;
  20309. }
  20310. this.modulesWithLoadedDependencies.add(module);
  20311. await Promise.all([
  20312. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  20313. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  20314. ]);
  20315. module.linkImports();
  20316. // To handle errors when resolving dependencies or in moduleParsed
  20317. await loadAndResolveDependenciesPromise;
  20318. }
  20319. fetchResolvedDependency(source, importer, resolvedId) {
  20320. if (resolvedId.external) {
  20321. const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
  20322. let externalModule = this.modulesById.get(id);
  20323. if (!externalModule) {
  20324. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute$1(id), attributes);
  20325. this.modulesById.set(id, externalModule);
  20326. }
  20327. else if (!(externalModule instanceof ExternalModule)) {
  20328. return error(logInternalIdCannotBeExternal(source, importer));
  20329. }
  20330. else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
  20331. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
  20332. }
  20333. return Promise.resolve(externalModule);
  20334. }
  20335. return this.fetchModule(resolvedId, importer, false, false);
  20336. }
  20337. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  20338. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  20339. module.dependencies.add(dependency);
  20340. dependency.importers.push(module.id);
  20341. }
  20342. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  20343. for (const dependency of module.dependencies) {
  20344. if (dependency instanceof Module) {
  20345. dependency.importedFromNotTreeshaken = true;
  20346. }
  20347. }
  20348. }
  20349. }
  20350. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  20351. const { makeAbsoluteExternalsRelative } = this.options;
  20352. if (resolveIdResult) {
  20353. if (typeof resolveIdResult === 'object') {
  20354. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  20355. return {
  20356. ...resolveIdResult,
  20357. external: external &&
  20358. (external === 'relative' ||
  20359. !isAbsolute$1(resolveIdResult.id) ||
  20360. (external === true &&
  20361. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  20362. 'absolute')
  20363. };
  20364. }
  20365. const external = this.options.external(resolveIdResult, importer, true);
  20366. return {
  20367. external: external &&
  20368. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  20369. 'absolute'),
  20370. id: external && makeAbsoluteExternalsRelative
  20371. ? normalizeRelativeExternalId(resolveIdResult, importer)
  20372. : resolveIdResult
  20373. };
  20374. }
  20375. const id = makeAbsoluteExternalsRelative
  20376. ? normalizeRelativeExternalId(source, importer)
  20377. : source;
  20378. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  20379. return null;
  20380. }
  20381. return {
  20382. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  20383. id
  20384. };
  20385. }
  20386. getResolveDynamicImportPromises(module) {
  20387. return module.dynamicImports.map(async (dynamicImport) => {
  20388. const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
  20389. if (resolvedId && typeof resolvedId === 'object') {
  20390. dynamicImport.id = resolvedId.id;
  20391. }
  20392. return [dynamicImport, resolvedId];
  20393. });
  20394. }
  20395. getResolveStaticDependencyPromises(module) {
  20396. return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
  20397. source,
  20398. (module.resolvedIds[source] =
  20399. module.resolvedIds[source] ||
  20400. this.handleInvalidResolvedId(await this.resolveId(source, module.id, EMPTY_OBJECT, false, attributes), source, module.id, attributes))
  20401. ]);
  20402. }
  20403. getResolvedIdWithDefaults(resolvedId, attributes) {
  20404. if (!resolvedId) {
  20405. return null;
  20406. }
  20407. const external = resolvedId.external || false;
  20408. return {
  20409. attributes: resolvedId.attributes || attributes,
  20410. external,
  20411. id: resolvedId.id,
  20412. meta: resolvedId.meta || {},
  20413. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  20414. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  20415. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  20416. };
  20417. }
  20418. async handleExistingModule(module, isEntry, isPreload) {
  20419. const loadPromise = this.moduleLoadPromises.get(module);
  20420. if (isPreload) {
  20421. return isPreload === RESOLVE_DEPENDENCIES
  20422. ? waitForDependencyResolution(loadPromise)
  20423. : loadPromise;
  20424. }
  20425. if (isEntry) {
  20426. // This reverts the changes in addEntryWithImplicitDependants and needs to
  20427. // be performed atomically
  20428. module.info.isEntry = true;
  20429. this.implicitEntryModules.delete(module);
  20430. for (const dependant of module.implicitlyLoadedAfter) {
  20431. dependant.implicitlyLoadedBefore.delete(module);
  20432. }
  20433. module.implicitlyLoadedAfter.clear();
  20434. }
  20435. return this.fetchModuleDependencies(module, ...(await loadPromise));
  20436. }
  20437. handleInvalidResolvedId(resolvedId, source, importer, attributes) {
  20438. if (resolvedId === null) {
  20439. if (isRelative(source)) {
  20440. return error(logUnresolvedImport(source, importer));
  20441. }
  20442. this.options.onLog(LOGLEVEL_WARN, logUnresolvedImportTreatedAsExternal(source, importer));
  20443. return {
  20444. attributes,
  20445. external: true,
  20446. id: source,
  20447. meta: {},
  20448. moduleSideEffects: this.hasModuleSideEffects(source, true),
  20449. resolvedBy: 'rollup',
  20450. syntheticNamedExports: false
  20451. };
  20452. }
  20453. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  20454. this.options.onLog(LOGLEVEL_WARN, logExternalSyntheticExports(source, importer));
  20455. }
  20456. return resolvedId;
  20457. }
  20458. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  20459. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT);
  20460. if (resolveIdResult == null) {
  20461. return error(implicitlyLoadedBefore === null
  20462. ? logUnresolvedEntry(unresolvedId)
  20463. : logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  20464. }
  20465. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  20466. if (resolveIdResult === false || isExternalModules) {
  20467. return error(implicitlyLoadedBefore === null
  20468. ? isExternalModules && isLoadForManualChunks
  20469. ? logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  20470. : logEntryCannotBeExternal(unresolvedId)
  20471. : logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  20472. }
  20473. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  20474. ? resolveIdResult
  20475. : { id: resolveIdResult }, EMPTY_OBJECT), undefined, isEntry, false);
  20476. }
  20477. async resolveDynamicImport(module, specifier, importer, attributes) {
  20478. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  20479. specifier,
  20480. importer,
  20481. { attributes }
  20482. ]);
  20483. if (typeof specifier !== 'string') {
  20484. if (typeof resolution === 'string') {
  20485. return resolution;
  20486. }
  20487. if (!resolution) {
  20488. return null;
  20489. }
  20490. return this.getResolvedIdWithDefaults(resolution, attributes);
  20491. }
  20492. if (resolution == null) {
  20493. const existingResolution = module.resolvedIds[specifier];
  20494. if (existingResolution) {
  20495. if (doAttributesDiffer(existingResolution.attributes, attributes)) {
  20496. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
  20497. }
  20498. return existingResolution;
  20499. }
  20500. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false, attributes), specifier, module.id, attributes));
  20501. }
  20502. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
  20503. }
  20504. }
  20505. function normalizeRelativeExternalId(source, importer) {
  20506. return isRelative(source)
  20507. ? importer
  20508. ? resolve$1(importer, '..', source)
  20509. : resolve$1(source)
  20510. : source;
  20511. }
  20512. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  20513. if (fileName !== null) {
  20514. module.chunkFileNames.add(fileName);
  20515. }
  20516. else if (name !== null) {
  20517. // Always keep chunkNames sorted by priority
  20518. let namePosition = 0;
  20519. while (module.chunkNames[namePosition]?.priority < priority)
  20520. namePosition++;
  20521. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  20522. }
  20523. }
  20524. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  20525. return (makeAbsoluteExternalsRelative === true ||
  20526. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  20527. !isAbsolute$1(id));
  20528. }
  20529. async function waitForDependencyResolution(loadPromise) {
  20530. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  20531. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  20532. }
  20533. function generateAssetFileName(name, names, source, originalFileName, originalFileNames, sourceHash, outputOptions, bundle, inputOptions) {
  20534. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  20535. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  20536. ? outputOptions.assetFileNames({
  20537. // Additionally, this should be non-enumerable in the next major
  20538. get name() {
  20539. warnDeprecation('Accessing the "name" property of emitted assets when generating the file name is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
  20540. return name;
  20541. },
  20542. names,
  20543. // Additionally, this should be non-enumerable in the next major
  20544. get originalFileName() {
  20545. warnDeprecation('Accessing the "originalFileName" property of emitted assets when generating the file name is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
  20546. return originalFileName;
  20547. },
  20548. originalFileNames,
  20549. source,
  20550. type: 'asset'
  20551. })
  20552. : outputOptions.assetFileNames, 'output.assetFileNames', {
  20553. ext: () => extname(emittedName).slice(1),
  20554. extname: () => extname(emittedName),
  20555. hash: size => sourceHash.slice(0, Math.min(Math.max(0, size || DEFAULT_HASH_SIZE), MAX_HASH_SIZE)),
  20556. name: () => emittedName.slice(0, Math.max(0, emittedName.length - extname(emittedName).length))
  20557. }), bundle);
  20558. }
  20559. function reserveFileNameInBundle(fileName, { bundle }, log) {
  20560. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  20561. log(LOGLEVEL_WARN, logFileNameConflict(fileName));
  20562. }
  20563. else {
  20564. bundle[fileName] = FILE_PLACEHOLDER;
  20565. }
  20566. }
  20567. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  20568. function hasValidType(emittedFile) {
  20569. return Boolean(emittedFile &&
  20570. emittedFileTypes.has(emittedFile.type));
  20571. }
  20572. function hasValidName(emittedFile) {
  20573. const validatedName = emittedFile.fileName || emittedFile.name;
  20574. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  20575. }
  20576. function getValidSource(source, emittedFile, fileReferenceId) {
  20577. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  20578. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  20579. 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.`));
  20580. }
  20581. return source;
  20582. }
  20583. function getAssetFileName(file, referenceId) {
  20584. if (typeof file.fileName !== 'string') {
  20585. return error(logAssetNotFinalisedForFileName(file.name || referenceId));
  20586. }
  20587. return file.fileName;
  20588. }
  20589. function getChunkFileName(file, facadeChunkByModule) {
  20590. if (file.fileName) {
  20591. return file.fileName;
  20592. }
  20593. if (facadeChunkByModule) {
  20594. return facadeChunkByModule.get(file.module).getFileName();
  20595. }
  20596. return error(logChunkNotGeneratedForFileName(file.fileName || file.name));
  20597. }
  20598. class FileEmitter {
  20599. constructor(graph, options, baseFileEmitter) {
  20600. this.graph = graph;
  20601. this.options = options;
  20602. this.facadeChunkByModule = null;
  20603. this.nextIdBase = 1;
  20604. this.output = null;
  20605. this.outputFileEmitters = [];
  20606. this.emitFile = (emittedFile) => {
  20607. if (!hasValidType(emittedFile)) {
  20608. return error(logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  20609. }
  20610. if (emittedFile.type === 'prebuilt-chunk') {
  20611. return this.emitPrebuiltChunk(emittedFile);
  20612. }
  20613. if (!hasValidName(emittedFile)) {
  20614. 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}".`));
  20615. }
  20616. if (emittedFile.type === 'chunk') {
  20617. return this.emitChunk(emittedFile);
  20618. }
  20619. return this.emitAsset(emittedFile);
  20620. };
  20621. this.finaliseAssets = () => {
  20622. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  20623. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  20624. return error(logNoAssetSourceSet(emittedFile.name || referenceId));
  20625. }
  20626. };
  20627. this.getFileName = (fileReferenceId) => {
  20628. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  20629. if (!emittedFile)
  20630. return error(logFileReferenceIdNotFoundForFilename(fileReferenceId));
  20631. if (emittedFile.type === 'chunk') {
  20632. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  20633. }
  20634. if (emittedFile.type === 'prebuilt-chunk') {
  20635. return emittedFile.fileName;
  20636. }
  20637. return getAssetFileName(emittedFile, fileReferenceId);
  20638. };
  20639. this.setAssetSource = (referenceId, requestedSource) => {
  20640. const consumedFile = this.filesByReferenceId.get(referenceId);
  20641. if (!consumedFile)
  20642. return error(logAssetReferenceIdNotFoundForSetSource(referenceId));
  20643. if (consumedFile.type !== 'asset') {
  20644. return error(logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  20645. }
  20646. if (consumedFile.source !== undefined) {
  20647. return error(logAssetSourceAlreadySet(consumedFile.name || referenceId));
  20648. }
  20649. const source = getValidSource(requestedSource, consumedFile, referenceId);
  20650. if (this.output) {
  20651. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  20652. }
  20653. else {
  20654. consumedFile.source = source;
  20655. for (const emitter of this.outputFileEmitters) {
  20656. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  20657. }
  20658. }
  20659. };
  20660. this.setChunkInformation = (facadeChunkByModule) => {
  20661. this.facadeChunkByModule = facadeChunkByModule;
  20662. };
  20663. this.setOutputBundle = (bundle, outputOptions) => {
  20664. const getHash = hasherByType[outputOptions.hashCharacters];
  20665. const output = (this.output = {
  20666. bundle,
  20667. fileNamesBySourceHash: new Map(),
  20668. getHash,
  20669. outputOptions
  20670. });
  20671. for (const emittedFile of this.filesByReferenceId.values()) {
  20672. if (emittedFile.fileName) {
  20673. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  20674. }
  20675. }
  20676. const consumedAssetsByHash = new Map();
  20677. for (const consumedFile of this.filesByReferenceId.values()) {
  20678. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  20679. if (consumedFile.fileName) {
  20680. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  20681. }
  20682. else {
  20683. const sourceHash = getHash(consumedFile.source);
  20684. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  20685. }
  20686. }
  20687. else if (consumedFile.type === 'prebuilt-chunk') {
  20688. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  20689. }
  20690. }
  20691. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  20692. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  20693. }
  20694. };
  20695. this.filesByReferenceId = baseFileEmitter
  20696. ? new Map(baseFileEmitter.filesByReferenceId)
  20697. : new Map();
  20698. baseFileEmitter?.addOutputFileEmitter(this);
  20699. }
  20700. addOutputFileEmitter(outputFileEmitter) {
  20701. this.outputFileEmitters.push(outputFileEmitter);
  20702. }
  20703. assignReferenceId(file, idBase) {
  20704. let referenceId = idBase;
  20705. do {
  20706. referenceId = getHash64(referenceId).slice(0, 8).replaceAll('-', '$');
  20707. } while (this.filesByReferenceId.has(referenceId) ||
  20708. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  20709. file.referenceId = referenceId;
  20710. this.filesByReferenceId.set(referenceId, file);
  20711. for (const { filesByReferenceId } of this.outputFileEmitters) {
  20712. filesByReferenceId.set(referenceId, file);
  20713. }
  20714. return referenceId;
  20715. }
  20716. createPrebuiltChunk(prebuiltChunk) {
  20717. return {
  20718. code: prebuiltChunk.code,
  20719. dynamicImports: [],
  20720. exports: prebuiltChunk.exports || [],
  20721. facadeModuleId: null,
  20722. fileName: prebuiltChunk.fileName,
  20723. implicitlyLoadedBefore: [],
  20724. importedBindings: {},
  20725. imports: [],
  20726. isDynamicEntry: false,
  20727. isEntry: false,
  20728. isImplicitEntry: false,
  20729. map: prebuiltChunk.map || null,
  20730. moduleIds: [],
  20731. modules: {},
  20732. name: prebuiltChunk.fileName,
  20733. preliminaryFileName: prebuiltChunk.fileName,
  20734. referencedFiles: [],
  20735. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  20736. type: 'chunk'
  20737. };
  20738. }
  20739. emitAsset(emittedAsset) {
  20740. const source = emittedAsset.source === undefined
  20741. ? undefined
  20742. : getValidSource(emittedAsset.source, emittedAsset, null);
  20743. const originalFileName = emittedAsset.originalFileName || null;
  20744. if (typeof originalFileName === 'string') {
  20745. this.graph.watchFiles[originalFileName] = true;
  20746. }
  20747. const consumedAsset = {
  20748. fileName: emittedAsset.fileName,
  20749. name: emittedAsset.name,
  20750. needsCodeReference: !!emittedAsset.needsCodeReference,
  20751. originalFileName,
  20752. referenceId: '',
  20753. source,
  20754. type: 'asset'
  20755. };
  20756. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  20757. if (this.output) {
  20758. this.emitAssetWithReferenceId(consumedAsset, this.output);
  20759. }
  20760. else {
  20761. for (const fileEmitter of this.outputFileEmitters) {
  20762. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  20763. }
  20764. }
  20765. return referenceId;
  20766. }
  20767. emitAssetWithReferenceId(consumedAsset, output) {
  20768. const { fileName, source } = consumedAsset;
  20769. if (fileName) {
  20770. reserveFileNameInBundle(fileName, output, this.options.onLog);
  20771. }
  20772. if (source !== undefined) {
  20773. this.finalizeAdditionalAsset(consumedAsset, source, output);
  20774. }
  20775. }
  20776. emitChunk(emittedChunk) {
  20777. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  20778. return error(logInvalidRollupPhaseForChunkEmission());
  20779. }
  20780. if (typeof emittedChunk.id !== 'string') {
  20781. return error(logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  20782. }
  20783. const consumedChunk = {
  20784. fileName: emittedChunk.fileName,
  20785. module: null,
  20786. name: emittedChunk.name || emittedChunk.id,
  20787. referenceId: '',
  20788. type: 'chunk'
  20789. };
  20790. this.graph.moduleLoader
  20791. .emitChunk(emittedChunk)
  20792. .then(module => (consumedChunk.module = module))
  20793. .catch(() => {
  20794. // Avoid unhandled Promise rejection as the error will be thrown later
  20795. // once module loading has finished
  20796. });
  20797. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  20798. }
  20799. emitPrebuiltChunk(emitPrebuiltChunk) {
  20800. if (typeof emitPrebuiltChunk.code !== 'string') {
  20801. return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  20802. }
  20803. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  20804. isPathFragment(emitPrebuiltChunk.fileName)) {
  20805. return error(logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  20806. }
  20807. const consumedPrebuiltChunk = {
  20808. code: emitPrebuiltChunk.code,
  20809. exports: emitPrebuiltChunk.exports,
  20810. fileName: emitPrebuiltChunk.fileName,
  20811. map: emitPrebuiltChunk.map,
  20812. referenceId: '',
  20813. type: 'prebuilt-chunk'
  20814. };
  20815. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  20816. if (this.output) {
  20817. this.output.bundle[consumedPrebuiltChunk.fileName] =
  20818. this.createPrebuiltChunk(consumedPrebuiltChunk);
  20819. }
  20820. return referenceId;
  20821. }
  20822. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySourceHash, getHash, outputOptions }) {
  20823. let { fileName, name, needsCodeReference, originalFileName, referenceId } = consumedFile;
  20824. // Deduplicate assets if an explicit fileName is not provided
  20825. if (!fileName) {
  20826. const sourceHash = getHash(source);
  20827. fileName = fileNamesBySourceHash.get(sourceHash);
  20828. if (!fileName) {
  20829. fileName = generateAssetFileName(name, name ? [name] : [], source, originalFileName, originalFileName ? [originalFileName] : [], sourceHash, outputOptions, bundle, this.options);
  20830. fileNamesBySourceHash.set(sourceHash, fileName);
  20831. }
  20832. }
  20833. // We must not modify the original assets to avoid interaction between outputs
  20834. const assetWithFileName = { ...consumedFile, fileName, source };
  20835. this.filesByReferenceId.set(referenceId, assetWithFileName);
  20836. const existingAsset = bundle[fileName];
  20837. if (existingAsset?.type === 'asset') {
  20838. existingAsset.needsCodeReference &&= needsCodeReference;
  20839. if (name) {
  20840. existingAsset.names.push(name);
  20841. }
  20842. if (originalFileName) {
  20843. existingAsset.originalFileNames.push(originalFileName);
  20844. }
  20845. }
  20846. else {
  20847. const { options } = this;
  20848. bundle[fileName] = {
  20849. fileName,
  20850. get name() {
  20851. // Additionally, this should be non-enumerable in the next major
  20852. warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
  20853. return name;
  20854. },
  20855. names: name ? [name] : [],
  20856. needsCodeReference,
  20857. get originalFileName() {
  20858. // Additionally, this should be non-enumerable in the next major
  20859. warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
  20860. return originalFileName;
  20861. },
  20862. originalFileNames: originalFileName ? [originalFileName] : [],
  20863. source,
  20864. type: 'asset'
  20865. };
  20866. }
  20867. }
  20868. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySourceHash, outputOptions }) {
  20869. const { names, originalFileNames } = getNamesFromAssets(consumedFiles);
  20870. let fileName = '';
  20871. let usedConsumedFile;
  20872. let needsCodeReference = true;
  20873. for (const consumedFile of consumedFiles) {
  20874. needsCodeReference &&= consumedFile.needsCodeReference;
  20875. const assetFileName = generateAssetFileName(consumedFile.name, names, consumedFile.source, consumedFile.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
  20876. if (!fileName ||
  20877. assetFileName.length < fileName.length ||
  20878. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  20879. fileName = assetFileName;
  20880. usedConsumedFile = consumedFile;
  20881. }
  20882. }
  20883. fileNamesBySourceHash.set(sourceHash, fileName);
  20884. for (const consumedFile of consumedFiles) {
  20885. // We must not modify the original assets to avoid interaction between outputs
  20886. const assetWithFileName = { ...consumedFile, fileName };
  20887. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  20888. }
  20889. const { options } = this;
  20890. bundle[fileName] = {
  20891. fileName,
  20892. get name() {
  20893. // Additionally, this should be non-enumerable in the next major
  20894. warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
  20895. return usedConsumedFile.name;
  20896. },
  20897. names,
  20898. needsCodeReference,
  20899. get originalFileName() {
  20900. // Additionally, this should be non-enumerable in the next major
  20901. warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
  20902. return usedConsumedFile.originalFileName;
  20903. },
  20904. originalFileNames,
  20905. source: usedConsumedFile.source,
  20906. type: 'asset'
  20907. };
  20908. }
  20909. }
  20910. function getNamesFromAssets(consumedFiles) {
  20911. const names = [];
  20912. const originalFileNames = [];
  20913. for (const { name, originalFileName } of consumedFiles) {
  20914. if (typeof name === 'string') {
  20915. names.push(name);
  20916. }
  20917. if (originalFileName) {
  20918. originalFileNames.push(originalFileName);
  20919. }
  20920. }
  20921. originalFileNames.sort();
  20922. // Sort by length first and then alphabetically so that the order is stable
  20923. // and the shortest names come first
  20924. names.sort((a, b) => a.length - b.length || (a > b ? 1 : a === b ? 0 : -1));
  20925. return { names, originalFileNames };
  20926. }
  20927. function getLogHandler(level, code, logger, pluginName, logLevel) {
  20928. if (logLevelPriority[level] < logLevelPriority[logLevel]) {
  20929. return doNothing;
  20930. }
  20931. return (log, pos) => {
  20932. if (pos != null) {
  20933. logger(LOGLEVEL_WARN, logInvalidLogPosition(pluginName));
  20934. }
  20935. log = normalizeLog(log);
  20936. if (log.code && !log.pluginCode) {
  20937. log.pluginCode = log.code;
  20938. }
  20939. log.code = code;
  20940. log.plugin = pluginName;
  20941. logger(level, log);
  20942. };
  20943. }
  20944. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  20945. const { logLevel, onLog } = options;
  20946. let cacheable = true;
  20947. if (typeof plugin.cacheKey !== 'string') {
  20948. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  20949. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  20950. existingPluginNames.has(plugin.name)) {
  20951. cacheable = false;
  20952. }
  20953. else {
  20954. existingPluginNames.add(plugin.name);
  20955. }
  20956. }
  20957. let cacheInstance;
  20958. if (!pluginCache) {
  20959. cacheInstance = NO_CACHE;
  20960. }
  20961. else if (cacheable) {
  20962. const cacheKey = plugin.cacheKey || plugin.name;
  20963. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  20964. }
  20965. else {
  20966. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  20967. }
  20968. return {
  20969. addWatchFile(id) {
  20970. graph.watchFiles[id] = true;
  20971. },
  20972. cache: cacheInstance,
  20973. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  20974. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  20975. error(error_) {
  20976. return error(logPluginError(normalizeLog(error_), plugin.name));
  20977. },
  20978. getFileName: fileEmitter.getFileName,
  20979. getModuleIds: () => graph.modulesById.keys(),
  20980. getModuleInfo: graph.getModuleInfo,
  20981. getWatchFiles: () => Object.keys(graph.watchFiles),
  20982. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  20983. load(resolvedId) {
  20984. return graph.moduleLoader.preloadModule(resolvedId);
  20985. },
  20986. meta: {
  20987. rollupVersion: version,
  20988. watchMode: graph.watchMode
  20989. },
  20990. parse: parseAst,
  20991. resolve(source, importer, { attributes, custom, isEntry, skipSelf } = BLANK) {
  20992. skipSelf ??= true;
  20993. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  20994. },
  20995. setAssetSource: fileEmitter.setAssetSource,
  20996. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  20997. };
  20998. }
  20999. function ensureArray(items) {
  21000. if (Array.isArray(items)) {
  21001. return items.filter(Boolean);
  21002. }
  21003. if (items) {
  21004. return [items];
  21005. }
  21006. return [];
  21007. }
  21008. function getMatcherString(glob, cwd) {
  21009. if (glob.startsWith('**') || isAbsolute$1(glob)) {
  21010. return normalize(glob);
  21011. }
  21012. const resolved = resolve$1(cwd, glob);
  21013. return normalize(resolved);
  21014. }
  21015. function patternToIdFilter(pattern) {
  21016. if (pattern instanceof RegExp) {
  21017. return (id) => {
  21018. const normalizedId = normalize(id);
  21019. const result = pattern.test(normalizedId);
  21020. pattern.lastIndex = 0;
  21021. return result;
  21022. };
  21023. }
  21024. const cwd = process.cwd();
  21025. const glob = getMatcherString(pattern, cwd);
  21026. const matcher = picomatch(glob, { dot: true });
  21027. return (id) => {
  21028. const normalizedId = normalize(id);
  21029. return matcher(normalizedId);
  21030. };
  21031. }
  21032. function patternToCodeFilter(pattern) {
  21033. if (pattern instanceof RegExp) {
  21034. return (code) => {
  21035. const result = pattern.test(code);
  21036. pattern.lastIndex = 0;
  21037. return result;
  21038. };
  21039. }
  21040. return (code) => code.includes(pattern);
  21041. }
  21042. function createFilter(exclude, include) {
  21043. if (!exclude && !include) {
  21044. return;
  21045. }
  21046. return input => {
  21047. if (exclude?.some(filter => filter(input))) {
  21048. return false;
  21049. }
  21050. if (include?.some(filter => filter(input))) {
  21051. return true;
  21052. }
  21053. return !(include && include.length > 0);
  21054. };
  21055. }
  21056. function normalizeFilter(filter) {
  21057. if (typeof filter === 'string' || filter instanceof RegExp) {
  21058. return {
  21059. include: [filter]
  21060. };
  21061. }
  21062. if (Array.isArray(filter)) {
  21063. return {
  21064. include: filter
  21065. };
  21066. }
  21067. return {
  21068. exclude: filter.exclude ? ensureArray(filter.exclude) : undefined,
  21069. include: filter.include ? ensureArray(filter.include) : undefined
  21070. };
  21071. }
  21072. function createIdFilter(filter) {
  21073. if (!filter)
  21074. return;
  21075. const { exclude, include } = normalizeFilter(filter);
  21076. const excludeFilter = exclude?.map(patternToIdFilter);
  21077. const includeFilter = include?.map(patternToIdFilter);
  21078. return createFilter(excludeFilter, includeFilter);
  21079. }
  21080. function createCodeFilter(filter) {
  21081. if (!filter)
  21082. return;
  21083. const { exclude, include } = normalizeFilter(filter);
  21084. const excludeFilter = exclude?.map(patternToCodeFilter);
  21085. const includeFilter = include?.map(patternToCodeFilter);
  21086. return createFilter(excludeFilter, includeFilter);
  21087. }
  21088. function createFilterForId(filter) {
  21089. const filterFunction = createIdFilter(filter);
  21090. return filterFunction ? id => !!filterFunction(id) : undefined;
  21091. }
  21092. function createFilterForTransform(idFilter, codeFilter) {
  21093. if (!idFilter && !codeFilter)
  21094. return;
  21095. const idFilterFunction = createIdFilter(idFilter);
  21096. const codeFilterFunction = createCodeFilter(codeFilter);
  21097. return (id, code) => {
  21098. let fallback = true;
  21099. if (idFilterFunction) {
  21100. fallback &&= idFilterFunction(id);
  21101. }
  21102. if (!fallback) {
  21103. return false;
  21104. }
  21105. if (codeFilterFunction) {
  21106. fallback &&= codeFilterFunction(code);
  21107. }
  21108. return fallback;
  21109. };
  21110. }
  21111. // This will make sure no input hook is omitted
  21112. const inputHookNames = {
  21113. buildEnd: 1,
  21114. buildStart: 1,
  21115. closeBundle: 1,
  21116. closeWatcher: 1,
  21117. load: 1,
  21118. moduleParsed: 1,
  21119. onLog: 1,
  21120. options: 1,
  21121. resolveDynamicImport: 1,
  21122. resolveId: 1,
  21123. shouldTransformCachedModule: 1,
  21124. transform: 1,
  21125. watchChange: 1
  21126. };
  21127. const inputHooks = Object.keys(inputHookNames);
  21128. class PluginDriver {
  21129. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  21130. this.graph = graph;
  21131. this.options = options;
  21132. this.pluginCache = pluginCache;
  21133. this.sortedPlugins = new Map();
  21134. this.unfulfilledActions = new Set();
  21135. this.compiledPluginFilters = {
  21136. idOnlyFilter: new WeakMap(),
  21137. transformFilter: new WeakMap()
  21138. };
  21139. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  21140. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  21141. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  21142. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  21143. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  21144. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  21145. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  21146. const existingPluginNames = new Set();
  21147. this.pluginContexts = new Map(this.plugins.map(plugin => [
  21148. plugin,
  21149. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  21150. ]));
  21151. if (basePluginDriver) {
  21152. for (const plugin of userPlugins) {
  21153. for (const hook of inputHooks) {
  21154. if (hook in plugin) {
  21155. options.onLog(LOGLEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
  21156. }
  21157. }
  21158. }
  21159. }
  21160. }
  21161. createOutputPluginDriver(plugins) {
  21162. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  21163. }
  21164. getUnfulfilledHookActions() {
  21165. return this.unfulfilledActions;
  21166. }
  21167. // chains, first non-null result stops and returns
  21168. hookFirst(hookName, parameters, replaceContext, skipped) {
  21169. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  21170. }
  21171. // chains, first non-null result stops and returns result and last plugin
  21172. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  21173. for (const plugin of this.getSortedPlugins(hookName)) {
  21174. if (skipped?.has(plugin))
  21175. continue;
  21176. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  21177. if (result != null)
  21178. return [result, plugin];
  21179. }
  21180. return null;
  21181. }
  21182. // chains synchronously, first non-null result stops and returns
  21183. hookFirstSync(hookName, parameters, replaceContext) {
  21184. for (const plugin of this.getSortedPlugins(hookName)) {
  21185. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21186. if (result != null)
  21187. return result;
  21188. }
  21189. return null;
  21190. }
  21191. // parallel, ignores returns
  21192. async hookParallel(hookName, parameters, replaceContext) {
  21193. const parallelPromises = [];
  21194. for (const plugin of this.getSortedPlugins(hookName)) {
  21195. if (plugin[hookName].sequential) {
  21196. await Promise.all(parallelPromises);
  21197. parallelPromises.length = 0;
  21198. await this.runHook(hookName, parameters, plugin, replaceContext);
  21199. }
  21200. else {
  21201. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  21202. }
  21203. }
  21204. await Promise.all(parallelPromises);
  21205. }
  21206. // chains, reduces returned value, handling the reduced value as the first hook argument
  21207. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  21208. let promise = Promise.resolve(argument0);
  21209. for (const plugin of this.getSortedPlugins(hookName)) {
  21210. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  21211. }
  21212. return promise;
  21213. }
  21214. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  21215. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  21216. for (const plugin of this.getSortedPlugins(hookName)) {
  21217. const parameters = [argument0, ...rest];
  21218. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21219. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  21220. }
  21221. return argument0;
  21222. }
  21223. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  21224. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  21225. const results = [];
  21226. const parallelResults = [];
  21227. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  21228. if (plugin[hookName].sequential) {
  21229. results.push(...(await Promise.all(parallelResults)));
  21230. parallelResults.length = 0;
  21231. results.push(await this.runHook(hookName, parameters, plugin));
  21232. }
  21233. else {
  21234. parallelResults.push(this.runHook(hookName, parameters, plugin));
  21235. }
  21236. }
  21237. results.push(...(await Promise.all(parallelResults)));
  21238. return results.reduce(reducer, await initialValue);
  21239. }
  21240. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  21241. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  21242. let accumulator = initialValue;
  21243. for (const plugin of this.getSortedPlugins(hookName)) {
  21244. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21245. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  21246. }
  21247. return accumulator;
  21248. }
  21249. // chains, ignores returns
  21250. hookSeq(hookName, parameters, replaceContext) {
  21251. let promise = Promise.resolve();
  21252. for (const plugin of this.getSortedPlugins(hookName)) {
  21253. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  21254. }
  21255. return promise.then(noReturn);
  21256. }
  21257. getSortedPlugins(hookName, validateHandler) {
  21258. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  21259. }
  21260. // Implementation signature
  21261. runHook(hookName, parameters, plugin, replaceContext) {
  21262. // We always filter for plugins that support the hook before running it
  21263. const hook = plugin[hookName];
  21264. const handler = typeof hook === 'object' ? hook.handler : hook;
  21265. if (typeof hook === 'object' && 'filter' in hook && hook.filter) {
  21266. if (hookName === 'transform') {
  21267. const filter = hook.filter;
  21268. const hookParameters = parameters;
  21269. const compiledFilter = getOrCreate(this.compiledPluginFilters.transformFilter, filter, () => createFilterForTransform(filter.id, filter.code));
  21270. if (compiledFilter && !compiledFilter(hookParameters[1], hookParameters[0])) {
  21271. return Promise.resolve();
  21272. }
  21273. }
  21274. else if (hookName === 'resolveId' || hookName === 'load') {
  21275. const filter = hook.filter;
  21276. const hookParameters = parameters;
  21277. const compiledFilter = getOrCreate(this.compiledPluginFilters.idOnlyFilter, filter, () => createFilterForId(filter.id));
  21278. if (compiledFilter && !compiledFilter(hookParameters[0])) {
  21279. return Promise.resolve();
  21280. }
  21281. }
  21282. }
  21283. let context = this.pluginContexts.get(plugin);
  21284. if (replaceContext) {
  21285. context = replaceContext(context, plugin);
  21286. }
  21287. let action = null;
  21288. return Promise.resolve()
  21289. .then(() => {
  21290. if (typeof handler !== 'function') {
  21291. return handler;
  21292. }
  21293. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  21294. const hookResult = handler.apply(context, parameters);
  21295. if (!hookResult?.then) {
  21296. // short circuit for non-thenables and non-Promises
  21297. return hookResult;
  21298. }
  21299. // Track pending hook actions to properly error out when
  21300. // unfulfilled promises cause rollup to abruptly and confusingly
  21301. // exit with a successful 0 return code but without producing any
  21302. // output, errors or warnings.
  21303. action = [plugin.name, hookName, parameters];
  21304. this.unfulfilledActions.add(action);
  21305. // Although it would be more elegant to just return hookResult here
  21306. // and put the .then() handler just above the .catch() handler below,
  21307. // doing so would subtly change the defacto async event dispatch order
  21308. // which at least one test and some plugins in the wild may depend on.
  21309. return Promise.resolve(hookResult).then(result => {
  21310. // action was fulfilled
  21311. this.unfulfilledActions.delete(action);
  21312. return result;
  21313. });
  21314. })
  21315. .catch(error_ => {
  21316. if (action !== null) {
  21317. // action considered to be fulfilled since error being handled
  21318. this.unfulfilledActions.delete(action);
  21319. }
  21320. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  21321. });
  21322. }
  21323. /**
  21324. * Run a sync plugin hook and return the result.
  21325. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  21326. * @param args Arguments passed to the plugin hook.
  21327. * @param plugin The acutal plugin
  21328. * @param replaceContext When passed, the plugin context can be overridden.
  21329. */
  21330. runHookSync(hookName, parameters, plugin, replaceContext) {
  21331. const hook = plugin[hookName];
  21332. const handler = typeof hook === 'object' ? hook.handler : hook;
  21333. let context = this.pluginContexts.get(plugin);
  21334. if (replaceContext) {
  21335. context = replaceContext(context, plugin);
  21336. }
  21337. try {
  21338. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  21339. return handler.apply(context, parameters);
  21340. }
  21341. catch (error_) {
  21342. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  21343. }
  21344. }
  21345. }
  21346. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  21347. const pre = [];
  21348. const normal = [];
  21349. const post = [];
  21350. for (const plugin of plugins) {
  21351. const hook = plugin[hookName];
  21352. if (hook) {
  21353. if (typeof hook === 'object') {
  21354. validateHandler(hook.handler, hookName, plugin);
  21355. if (hook.order === 'pre') {
  21356. pre.push(plugin);
  21357. continue;
  21358. }
  21359. if (hook.order === 'post') {
  21360. post.push(plugin);
  21361. continue;
  21362. }
  21363. }
  21364. else {
  21365. validateHandler(hook, hookName, plugin);
  21366. }
  21367. normal.push(plugin);
  21368. }
  21369. }
  21370. return [...pre, ...normal, ...post];
  21371. }
  21372. function validateFunctionPluginHandler(handler, hookName, plugin) {
  21373. if (typeof handler !== 'function') {
  21374. error(logInvalidFunctionPluginHook(hookName, plugin.name));
  21375. }
  21376. }
  21377. function validateAddonPluginHandler(handler, hookName, plugin) {
  21378. if (typeof handler !== 'string' && typeof handler !== 'function') {
  21379. return error(logInvalidAddonPluginHook(hookName, plugin.name));
  21380. }
  21381. }
  21382. function noReturn() { }
  21383. class Queue {
  21384. constructor(maxParallel) {
  21385. this.maxParallel = maxParallel;
  21386. this.queue = [];
  21387. this.workerCount = 0;
  21388. }
  21389. run(task) {
  21390. return new Promise((resolve, reject) => {
  21391. this.queue.push({ reject, resolve, task });
  21392. this.work();
  21393. });
  21394. }
  21395. async work() {
  21396. if (this.workerCount >= this.maxParallel)
  21397. return;
  21398. this.workerCount++;
  21399. let entry;
  21400. while ((entry = this.queue.shift())) {
  21401. const { reject, resolve, task } = entry;
  21402. try {
  21403. const result = await task();
  21404. resolve(result);
  21405. }
  21406. catch (error) {
  21407. reject(error);
  21408. }
  21409. }
  21410. this.workerCount--;
  21411. }
  21412. }
  21413. function normalizeEntryModules(entryModules) {
  21414. if (Array.isArray(entryModules)) {
  21415. return entryModules.map(id => ({
  21416. fileName: null,
  21417. id,
  21418. implicitlyLoadedAfter: [],
  21419. importer: undefined,
  21420. name: null
  21421. }));
  21422. }
  21423. return Object.entries(entryModules).map(([name, id]) => ({
  21424. fileName: null,
  21425. id,
  21426. implicitlyLoadedAfter: [],
  21427. importer: undefined,
  21428. name
  21429. }));
  21430. }
  21431. class Graph {
  21432. constructor(options, watcher) {
  21433. this.options = options;
  21434. this.astLru = flru(5);
  21435. this.cachedModules = new Map();
  21436. this.deoptimizationTracker = new EntityPathTracker();
  21437. this.entryModules = [];
  21438. this.modulesById = new Map();
  21439. this.needsTreeshakingPass = false;
  21440. this.newlyIncludedVariableInits = new Set();
  21441. this.phase = BuildPhase.LOAD_AND_PARSE;
  21442. this.scope = new GlobalScope();
  21443. this.watchFiles = Object.create(null);
  21444. this.watchMode = false;
  21445. this.externalModules = [];
  21446. this.implicitEntryModules = [];
  21447. this.modules = [];
  21448. this.getModuleInfo = (moduleId) => {
  21449. const foundModule = this.modulesById.get(moduleId);
  21450. if (!foundModule)
  21451. return null;
  21452. return foundModule.info;
  21453. };
  21454. if (options.cache !== false) {
  21455. if (options.cache?.modules) {
  21456. for (const module of options.cache.modules)
  21457. this.cachedModules.set(module.id, module);
  21458. }
  21459. this.pluginCache = options.cache?.plugins || Object.create(null);
  21460. // increment access counter
  21461. for (const name in this.pluginCache) {
  21462. const cache = this.pluginCache[name];
  21463. for (const value of Object.values(cache))
  21464. value[0]++;
  21465. }
  21466. }
  21467. if (watcher) {
  21468. this.watchMode = true;
  21469. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  21470. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  21471. watcher.onCurrentRun('change', handleChange);
  21472. watcher.onCurrentRun('close', handleClose);
  21473. }
  21474. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  21475. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  21476. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  21477. this.pureFunctions = getPureFunctions(options);
  21478. }
  21479. async build() {
  21480. timeStart('generate module graph', 2);
  21481. await this.generateModuleGraph();
  21482. timeEnd('generate module graph', 2);
  21483. timeStart('sort and bind modules', 2);
  21484. this.phase = BuildPhase.ANALYSE;
  21485. this.sortModules();
  21486. timeEnd('sort and bind modules', 2);
  21487. timeStart('mark included statements', 2);
  21488. this.includeStatements();
  21489. timeEnd('mark included statements', 2);
  21490. this.phase = BuildPhase.GENERATE;
  21491. }
  21492. getCache() {
  21493. // handle plugin cache eviction
  21494. for (const name in this.pluginCache) {
  21495. const cache = this.pluginCache[name];
  21496. let allDeleted = true;
  21497. for (const [key, value] of Object.entries(cache)) {
  21498. if (value[0] >= this.options.experimentalCacheExpiry)
  21499. delete cache[key];
  21500. else
  21501. allDeleted = false;
  21502. }
  21503. if (allDeleted)
  21504. delete this.pluginCache[name];
  21505. }
  21506. return {
  21507. modules: this.modules.map(module => module.toJSON()),
  21508. plugins: this.pluginCache
  21509. };
  21510. }
  21511. async generateModuleGraph() {
  21512. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  21513. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  21514. if (this.entryModules.length === 0) {
  21515. throw new Error('You must supply options.input to rollup');
  21516. }
  21517. for (const module of this.modulesById.values()) {
  21518. module.cacheInfoGetters();
  21519. if (module instanceof Module) {
  21520. this.modules.push(module);
  21521. }
  21522. else {
  21523. this.externalModules.push(module);
  21524. }
  21525. }
  21526. }
  21527. includeStatements() {
  21528. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  21529. for (const module of entryModules) {
  21530. markModuleAndImpureDependenciesAsExecuted(module);
  21531. }
  21532. if (this.options.treeshake) {
  21533. let treeshakingPass = 1;
  21534. this.newlyIncludedVariableInits.clear();
  21535. do {
  21536. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  21537. this.needsTreeshakingPass = false;
  21538. for (const module of this.modules) {
  21539. if (module.isExecuted) {
  21540. module.hasTreeShakingPassStarted = true;
  21541. if (module.info.moduleSideEffects === 'no-treeshake') {
  21542. module.includeAllInBundle();
  21543. }
  21544. else {
  21545. module.include();
  21546. }
  21547. for (const entity of this.newlyIncludedVariableInits) {
  21548. this.newlyIncludedVariableInits.delete(entity);
  21549. entity.include(createInclusionContext(), false);
  21550. }
  21551. }
  21552. }
  21553. if (treeshakingPass === 1) {
  21554. // We only include exports after the first pass to avoid issues with
  21555. // the TDZ detection logic
  21556. for (const module of entryModules) {
  21557. if (module.preserveSignature !== false) {
  21558. module.includeAllExports(false);
  21559. this.needsTreeshakingPass = true;
  21560. }
  21561. }
  21562. }
  21563. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  21564. } while (this.needsTreeshakingPass);
  21565. }
  21566. else {
  21567. for (const module of this.modules)
  21568. module.includeAllInBundle();
  21569. }
  21570. for (const externalModule of this.externalModules)
  21571. externalModule.warnUnusedImports();
  21572. for (const module of this.implicitEntryModules) {
  21573. for (const dependant of module.implicitlyLoadedAfter) {
  21574. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  21575. error(logImplicitDependantIsNotIncluded(dependant));
  21576. }
  21577. }
  21578. }
  21579. }
  21580. sortModules() {
  21581. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  21582. for (const cyclePath of cyclePaths) {
  21583. this.options.onLog(LOGLEVEL_WARN, logCircularDependency(cyclePath));
  21584. }
  21585. this.modules = orderedModules;
  21586. for (const module of this.modules) {
  21587. module.bindReferences();
  21588. }
  21589. this.warnForMissingExports();
  21590. }
  21591. warnForMissingExports() {
  21592. for (const module of this.modules) {
  21593. for (const importDescription of module.importDescriptions.values()) {
  21594. if (importDescription.name !== '*' &&
  21595. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  21596. module.log(LOGLEVEL_WARN, logMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  21597. }
  21598. }
  21599. }
  21600. }
  21601. }
  21602. function formatAction([pluginName, hookName, parameters]) {
  21603. const action = `(${pluginName}) ${hookName}`;
  21604. const s = JSON.stringify;
  21605. switch (hookName) {
  21606. case 'resolveId': {
  21607. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  21608. }
  21609. case 'load': {
  21610. return `${action} ${s(parameters[0])}`;
  21611. }
  21612. case 'transform': {
  21613. return `${action} ${s(parameters[1])}`;
  21614. }
  21615. case 'shouldTransformCachedModule': {
  21616. return `${action} ${s(parameters[0].id)}`;
  21617. }
  21618. case 'moduleParsed': {
  21619. return `${action} ${s(parameters[0].id)}`;
  21620. }
  21621. }
  21622. return action;
  21623. }
  21624. let handleBeforeExit = null;
  21625. const rejectByPluginDriver = new Map();
  21626. async function catchUnfinishedHookActions(pluginDriver, callback) {
  21627. const emptyEventLoopPromise = new Promise((_, reject) => {
  21628. rejectByPluginDriver.set(pluginDriver, reject);
  21629. if (!handleBeforeExit) {
  21630. // We only ever create a single event listener to avoid max listener and
  21631. // other issues
  21632. handleBeforeExit = () => {
  21633. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  21634. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  21635. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  21636. [...unfulfilledActions].map(formatAction).join('\n')));
  21637. }
  21638. };
  21639. process$1.once('beforeExit', handleBeforeExit);
  21640. }
  21641. });
  21642. try {
  21643. return await Promise.race([callback(), emptyEventLoopPromise]);
  21644. }
  21645. finally {
  21646. rejectByPluginDriver.delete(pluginDriver);
  21647. if (rejectByPluginDriver.size === 0) {
  21648. process$1.off('beforeExit', handleBeforeExit);
  21649. handleBeforeExit = null;
  21650. }
  21651. }
  21652. }
  21653. async function initWasm() { }
  21654. function getLogger(plugins, onLog, watchMode, logLevel) {
  21655. plugins = getSortedValidatedPlugins('onLog', plugins);
  21656. const minimalPriority = logLevelPriority[logLevel];
  21657. const logger = (level, log, skipped = EMPTY_SET) => {
  21658. augmentLogMessage(log);
  21659. const logPriority = logLevelPriority[level];
  21660. if (logPriority < minimalPriority) {
  21661. return;
  21662. }
  21663. for (const plugin of plugins) {
  21664. if (skipped.has(plugin))
  21665. continue;
  21666. const { onLog: pluginOnLog } = plugin;
  21667. const getLogHandler = (level) => {
  21668. if (logLevelPriority[level] < minimalPriority) {
  21669. return doNothing;
  21670. }
  21671. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  21672. };
  21673. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  21674. if (handler.call({
  21675. debug: getLogHandler(LOGLEVEL_DEBUG),
  21676. error: (log) => error(normalizeLog(log)),
  21677. info: getLogHandler(LOGLEVEL_INFO),
  21678. meta: { rollupVersion: version, watchMode },
  21679. warn: getLogHandler(LOGLEVEL_WARN)
  21680. }, level, log) === false) {
  21681. return;
  21682. }
  21683. }
  21684. onLog(level, log);
  21685. };
  21686. return logger;
  21687. }
  21688. async function normalizeInputOptions(config, watchMode) {
  21689. // These are options that may trigger special warnings or behaviour later
  21690. // if the user did not select an explicit value
  21691. const unsetOptions = new Set();
  21692. const context = config.context ?? 'undefined';
  21693. const plugins = await normalizePluginOption(config.plugins);
  21694. const logLevel = config.logLevel || LOGLEVEL_INFO;
  21695. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  21696. const strictDeprecations = config.strictDeprecations || false;
  21697. const maxParallelFileOps = getMaxParallelFileOps(config);
  21698. const options = {
  21699. cache: getCache(config),
  21700. context,
  21701. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  21702. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  21703. external: getIdMatcher(config.external),
  21704. input: getInput(config),
  21705. jsx: getJsx(config),
  21706. logLevel,
  21707. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  21708. maxParallelFileOps,
  21709. moduleContext: getModuleContext(config, context),
  21710. onLog,
  21711. perf: config.perf || false,
  21712. plugins,
  21713. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  21714. preserveSymlinks: config.preserveSymlinks || false,
  21715. shimMissingExports: config.shimMissingExports || false,
  21716. strictDeprecations,
  21717. treeshake: getTreeshake(config)
  21718. };
  21719. warnUnknownOptions(config, [...Object.keys(options), 'onwarn', 'watch'], 'input options', onLog, /^(output)$/);
  21720. return { options, unsetOptions };
  21721. }
  21722. const getCache = (config) => config.cache === true // `true` is the default
  21723. ? undefined
  21724. : config.cache?.cache || config.cache;
  21725. const getIdMatcher = (option) => {
  21726. if (option === true) {
  21727. return () => true;
  21728. }
  21729. if (typeof option === 'function') {
  21730. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  21731. }
  21732. if (option) {
  21733. const ids = new Set();
  21734. const matchers = [];
  21735. for (const value of ensureArray(option)) {
  21736. if (value instanceof RegExp) {
  21737. matchers.push(value);
  21738. }
  21739. else {
  21740. ids.add(value);
  21741. }
  21742. }
  21743. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  21744. }
  21745. return () => false;
  21746. };
  21747. const getInput = (config) => {
  21748. const configInput = config.input;
  21749. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  21750. };
  21751. const getJsx = (config) => {
  21752. const configJsx = config.jsx;
  21753. if (!configJsx)
  21754. return false;
  21755. const configWithPreset = getOptionWithPreset(configJsx, jsxPresets, 'jsx', URL_JSX, 'false, ');
  21756. const { factory, importSource, mode } = configWithPreset;
  21757. switch (mode) {
  21758. case 'automatic': {
  21759. return {
  21760. factory: factory || 'React.createElement',
  21761. importSource: importSource || 'react',
  21762. jsxImportSource: configWithPreset.jsxImportSource || 'react/jsx-runtime',
  21763. mode: 'automatic'
  21764. };
  21765. }
  21766. case 'preserve': {
  21767. if (importSource && !(factory || configWithPreset.fragment)) {
  21768. error(logInvalidOption('jsx', URL_JSX, 'when preserving JSX and specifying an importSource, you also need to specify a factory or fragment'));
  21769. }
  21770. return {
  21771. factory: factory || null,
  21772. fragment: configWithPreset.fragment || null,
  21773. importSource: importSource || null,
  21774. mode: 'preserve'
  21775. };
  21776. }
  21777. // case 'classic':
  21778. default: {
  21779. if (mode && mode !== 'classic') {
  21780. error(logInvalidOption('jsx.mode', URL_JSX, 'mode must be "automatic", "classic" or "preserve"', mode));
  21781. }
  21782. return {
  21783. factory: factory || 'React.createElement',
  21784. fragment: configWithPreset.fragment || 'React.Fragment',
  21785. importSource: importSource || null,
  21786. mode: 'classic'
  21787. };
  21788. }
  21789. }
  21790. };
  21791. const getMaxParallelFileOps = (config) => {
  21792. const maxParallelFileOps = config.maxParallelFileOps;
  21793. if (typeof maxParallelFileOps === 'number') {
  21794. if (maxParallelFileOps <= 0)
  21795. return Infinity;
  21796. return maxParallelFileOps;
  21797. }
  21798. return 20;
  21799. };
  21800. const getModuleContext = (config, context) => {
  21801. const configModuleContext = config.moduleContext;
  21802. if (typeof configModuleContext === 'function') {
  21803. return id => configModuleContext(id) ?? context;
  21804. }
  21805. if (configModuleContext) {
  21806. const contextByModuleId = Object.create(null);
  21807. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  21808. contextByModuleId[resolve$1(key)] = moduleContext;
  21809. }
  21810. return id => contextByModuleId[id] ?? context;
  21811. }
  21812. return () => context;
  21813. };
  21814. const getTreeshake = (config) => {
  21815. const configTreeshake = config.treeshake;
  21816. if (configTreeshake === false) {
  21817. return false;
  21818. }
  21819. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ');
  21820. return {
  21821. annotations: configWithPreset.annotations !== false,
  21822. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  21823. manualPureFunctions: configWithPreset.manualPureFunctions ?? EMPTY_ARRAY,
  21824. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  21825. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  21826. ? 'always'
  21827. : configWithPreset.propertyReadSideEffects !== false,
  21828. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  21829. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  21830. };
  21831. };
  21832. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  21833. if (typeof moduleSideEffectsOption === 'boolean') {
  21834. return () => moduleSideEffectsOption;
  21835. }
  21836. if (moduleSideEffectsOption === 'no-external') {
  21837. return (_id, external) => !external;
  21838. }
  21839. if (typeof moduleSideEffectsOption === 'function') {
  21840. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  21841. }
  21842. if (Array.isArray(moduleSideEffectsOption)) {
  21843. const ids = new Set(moduleSideEffectsOption);
  21844. return id => ids.has(id);
  21845. }
  21846. if (moduleSideEffectsOption) {
  21847. error(logInvalidOption('treeshake.moduleSideEffects', URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  21848. }
  21849. return () => true;
  21850. };
  21851. // https://datatracker.ietf.org/doc/html/rfc2396
  21852. // eslint-disable-next-line no-control-regex
  21853. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g;
  21854. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  21855. function sanitizeFileName(name) {
  21856. const match = DRIVE_LETTER_REGEX.exec(name);
  21857. const driveLetter = match ? match[0] : '';
  21858. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  21859. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  21860. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  21861. }
  21862. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  21863. // These are options that may trigger special warnings or behaviour later
  21864. // if the user did not select an explicit value
  21865. const unsetOptions = new Set(unsetInputOptions);
  21866. const compact = config.compact || false;
  21867. const format = getFormat(config);
  21868. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  21869. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  21870. const file = getFile(config, preserveModules, inputOptions);
  21871. const generatedCode = getGeneratedCode(config);
  21872. const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
  21873. const outputOptions = {
  21874. amd: getAmd(config),
  21875. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  21876. banner: getAddon(config, 'banner'),
  21877. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  21878. compact,
  21879. dir: getDir(config, file),
  21880. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  21881. entryFileNames: getEntryFileNames(config, unsetOptions),
  21882. esModule: config.esModule ?? 'if-default-prop',
  21883. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  21884. exports: getExports(config, unsetOptions),
  21885. extend: config.extend || false,
  21886. externalImportAssertions: externalImportAttributes,
  21887. externalImportAttributes,
  21888. externalLiveBindings: config.externalLiveBindings ?? true,
  21889. file,
  21890. footer: getAddon(config, 'footer'),
  21891. format,
  21892. freeze: config.freeze ?? true,
  21893. generatedCode,
  21894. globals: config.globals || {},
  21895. hashCharacters: config.hashCharacters ?? 'base64',
  21896. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  21897. importAttributesKey: config.importAttributesKey ?? 'assert',
  21898. indent: getIndent(config, compact),
  21899. inlineDynamicImports,
  21900. interop: getInterop(config),
  21901. intro: getAddon(config, 'intro'),
  21902. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules),
  21903. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  21904. name: config.name,
  21905. noConflict: config.noConflict || false,
  21906. outro: getAddon(config, 'outro'),
  21907. paths: config.paths || {},
  21908. plugins: await normalizePluginOption(config.plugins),
  21909. preserveModules,
  21910. preserveModulesRoot: getPreserveModulesRoot(config),
  21911. reexportProtoFromExternal: config.reexportProtoFromExternal ?? true,
  21912. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  21913. ? config.sanitizeFileName
  21914. : config.sanitizeFileName === false
  21915. ? id => id
  21916. : sanitizeFileName,
  21917. sourcemap: config.sourcemap || false,
  21918. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  21919. sourcemapDebugIds: config.sourcemapDebugIds || false,
  21920. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  21921. sourcemapFile: config.sourcemapFile,
  21922. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  21923. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  21924. ? config.sourcemapIgnoreList
  21925. : config.sourcemapIgnoreList === false
  21926. ? () => false
  21927. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  21928. sourcemapPathTransform: config.sourcemapPathTransform,
  21929. strict: config.strict ?? true,
  21930. systemNullSetters: config.systemNullSetters ?? true,
  21931. validate: config.validate || false,
  21932. virtualDirname: config.virtualDirname || '_virtual'
  21933. };
  21934. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  21935. return { options: outputOptions, unsetOptions };
  21936. }
  21937. const getFile = (config, preserveModules, inputOptions) => {
  21938. const { file } = config;
  21939. if (typeof file === 'string') {
  21940. if (preserveModules) {
  21941. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  21942. }
  21943. if (!Array.isArray(inputOptions.input))
  21944. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  21945. }
  21946. return file;
  21947. };
  21948. const getFormat = (config) => {
  21949. const configFormat = config.format;
  21950. switch (configFormat) {
  21951. case undefined:
  21952. case 'es':
  21953. case 'esm':
  21954. case 'module': {
  21955. return 'es';
  21956. }
  21957. case 'cjs':
  21958. case 'commonjs': {
  21959. return 'cjs';
  21960. }
  21961. case 'system':
  21962. case 'systemjs': {
  21963. return 'system';
  21964. }
  21965. case 'amd':
  21966. case 'iife':
  21967. case 'umd': {
  21968. return configFormat;
  21969. }
  21970. default: {
  21971. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  21972. }
  21973. }
  21974. };
  21975. const getInlineDynamicImports = (config, inputOptions) => {
  21976. const inlineDynamicImports = config.inlineDynamicImports || false;
  21977. const { input } = inputOptions;
  21978. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  21979. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  21980. }
  21981. return inlineDynamicImports;
  21982. };
  21983. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  21984. const preserveModules = config.preserveModules || false;
  21985. if (preserveModules) {
  21986. if (inlineDynamicImports) {
  21987. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  21988. }
  21989. if (inputOptions.preserveEntrySignatures === false) {
  21990. return error(logInvalidOption('preserveEntrySignatures', URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  21991. }
  21992. }
  21993. return preserveModules;
  21994. };
  21995. const getPreserveModulesRoot = (config) => {
  21996. const { preserveModulesRoot } = config;
  21997. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  21998. return undefined;
  21999. }
  22000. return resolve$1(preserveModulesRoot);
  22001. };
  22002. const getAmd = (config) => {
  22003. const mergedOption = {
  22004. autoId: false,
  22005. basePath: '',
  22006. define: 'define',
  22007. forceJsExtensionForImports: false,
  22008. ...config.amd
  22009. };
  22010. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  22011. return error(logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  22012. }
  22013. if (mergedOption.basePath && !mergedOption.autoId) {
  22014. return error(logInvalidOption('output.amd.basePath', URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  22015. }
  22016. return mergedOption.autoId
  22017. ? {
  22018. autoId: true,
  22019. basePath: mergedOption.basePath,
  22020. define: mergedOption.define,
  22021. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  22022. }
  22023. : {
  22024. autoId: false,
  22025. define: mergedOption.define,
  22026. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  22027. id: mergedOption.id
  22028. };
  22029. };
  22030. const getAddon = (config, name) => {
  22031. const configAddon = config[name];
  22032. if (typeof configAddon === 'function') {
  22033. return configAddon;
  22034. }
  22035. return () => configAddon || '';
  22036. };
  22037. const getDir = (config, file) => {
  22038. const { dir } = config;
  22039. if (typeof dir === 'string' && typeof file === 'string') {
  22040. 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'));
  22041. }
  22042. return dir;
  22043. };
  22044. const getEntryFileNames = (config, unsetOptions) => {
  22045. const configEntryFileNames = config.entryFileNames;
  22046. if (configEntryFileNames == null) {
  22047. unsetOptions.add('entryFileNames');
  22048. }
  22049. return configEntryFileNames ?? '[name].js';
  22050. };
  22051. function getExports(config, unsetOptions) {
  22052. const configExports = config.exports;
  22053. if (configExports == null) {
  22054. unsetOptions.add('exports');
  22055. }
  22056. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  22057. return error(logInvalidExportOptionValue(configExports));
  22058. }
  22059. return configExports || 'auto';
  22060. }
  22061. const getExternalImportAttributes = (config, inputOptions) => {
  22062. if (config.externalImportAssertions != undefined) {
  22063. warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
  22064. }
  22065. return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
  22066. };
  22067. const getGeneratedCode = (config) => {
  22068. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
  22069. return {
  22070. arrowFunctions: configWithPreset.arrowFunctions === true,
  22071. constBindings: configWithPreset.constBindings === true,
  22072. objectShorthand: configWithPreset.objectShorthand === true,
  22073. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  22074. symbols: configWithPreset.symbols === true
  22075. };
  22076. };
  22077. const getIndent = (config, compact) => {
  22078. if (compact) {
  22079. return '';
  22080. }
  22081. const configIndent = config.indent;
  22082. return configIndent === false ? '' : (configIndent ?? true);
  22083. };
  22084. const ALLOWED_INTEROP_TYPES = new Set([
  22085. 'compat',
  22086. 'auto',
  22087. 'esModule',
  22088. 'default',
  22089. 'defaultOnly'
  22090. ]);
  22091. const getInterop = (config) => {
  22092. const configInterop = config.interop;
  22093. if (typeof configInterop === 'function') {
  22094. const interopPerId = Object.create(null);
  22095. let defaultInterop = null;
  22096. return id => id === null
  22097. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22098. : id in interopPerId
  22099. ? interopPerId[id]
  22100. : validateInterop((interopPerId[id] = configInterop(id)));
  22101. }
  22102. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  22103. };
  22104. const validateInterop = (interop) => {
  22105. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22106. return error(logInvalidOption('output.interop', URL_OUTPUT_INTEROP, `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  22107. }
  22108. return interop;
  22109. };
  22110. const getManualChunks = (config, inlineDynamicImports, preserveModules) => {
  22111. const configManualChunks = config.manualChunks;
  22112. if (configManualChunks) {
  22113. if (inlineDynamicImports) {
  22114. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  22115. }
  22116. if (preserveModules) {
  22117. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  22118. }
  22119. }
  22120. return configManualChunks || {};
  22121. };
  22122. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  22123. const getSourcemapFileNames = (config, unsetOptions) => {
  22124. const configSourcemapFileNames = config.sourcemapFileNames;
  22125. if (configSourcemapFileNames == null) {
  22126. unsetOptions.add('sourcemapFileNames');
  22127. }
  22128. return configSourcemapFileNames;
  22129. };
  22130. const getSourcemapBaseUrl = (config) => {
  22131. const { sourcemapBaseUrl } = config;
  22132. if (sourcemapBaseUrl) {
  22133. if (isValidUrl(sourcemapBaseUrl)) {
  22134. return addTrailingSlashIfMissed(sourcemapBaseUrl);
  22135. }
  22136. return error(logInvalidOption('output.sourcemapBaseUrl', URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22137. }
  22138. };
  22139. // @ts-expect-error TS2540: the polyfill of `asyncDispose`.
  22140. Symbol.asyncDispose ??= Symbol('Symbol.asyncDispose');
  22141. function rollup(rawInputOptions) {
  22142. return rollupInternal(rawInputOptions, null);
  22143. }
  22144. async function rollupInternal(rawInputOptions, watcher) {
  22145. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22146. initialiseTimers(inputOptions);
  22147. await initWasm();
  22148. const graph = new Graph(inputOptions, watcher);
  22149. // remove the cache object from the memory after graph creation (cache is not used anymore)
  22150. const useCache = rawInputOptions.cache !== false;
  22151. if (rawInputOptions.cache) {
  22152. inputOptions.cache = undefined;
  22153. rawInputOptions.cache = undefined;
  22154. }
  22155. timeStart('BUILD', 1);
  22156. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22157. try {
  22158. timeStart('initialize', 2);
  22159. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22160. timeEnd('initialize', 2);
  22161. await graph.build();
  22162. }
  22163. catch (error_) {
  22164. const watchFiles = Object.keys(graph.watchFiles);
  22165. if (watchFiles.length > 0) {
  22166. error_.watchFiles = watchFiles;
  22167. }
  22168. try {
  22169. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  22170. }
  22171. catch (buildEndError) {
  22172. // Create a compound error object to include both errors, based on the original error
  22173. const compoundError = getRollupError({
  22174. ...error_,
  22175. 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}`
  22176. });
  22177. await graph.pluginDriver.hookParallel('closeBundle', [compoundError]);
  22178. throw compoundError;
  22179. }
  22180. await graph.pluginDriver.hookParallel('closeBundle', [error_]);
  22181. throw error_;
  22182. }
  22183. try {
  22184. await graph.pluginDriver.hookParallel('buildEnd', []);
  22185. }
  22186. catch (buildEndError) {
  22187. await graph.pluginDriver.hookParallel('closeBundle', [buildEndError]);
  22188. throw buildEndError;
  22189. }
  22190. });
  22191. timeEnd('BUILD', 1);
  22192. const result = {
  22193. cache: useCache ? graph.getCache() : undefined,
  22194. async close() {
  22195. if (result.closed)
  22196. return;
  22197. result.closed = true;
  22198. await graph.pluginDriver.hookParallel('closeBundle', []);
  22199. },
  22200. closed: false,
  22201. async [Symbol.asyncDispose]() {
  22202. await this.close();
  22203. },
  22204. async generate(rawOutputOptions) {
  22205. if (result.closed)
  22206. return error(logAlreadyClosed());
  22207. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22208. },
  22209. get watchFiles() {
  22210. return Object.keys(graph.watchFiles);
  22211. },
  22212. async write(rawOutputOptions) {
  22213. if (result.closed)
  22214. return error(logAlreadyClosed());
  22215. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22216. }
  22217. };
  22218. if (inputOptions.perf)
  22219. result.getTimings = getTimings;
  22220. return result;
  22221. }
  22222. async function getInputOptions(initialInputOptions, watchMode) {
  22223. if (!initialInputOptions) {
  22224. throw new Error('You must supply an options object to rollup');
  22225. }
  22226. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  22227. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  22228. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22229. return { options, unsetOptions };
  22230. }
  22231. async function getProcessedInputOptions(inputOptions, watchMode) {
  22232. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  22233. const logLevel = inputOptions.logLevel || LOGLEVEL_INFO;
  22234. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  22235. for (const plugin of plugins) {
  22236. const { name, options } = plugin;
  22237. const handler = 'handler' in options ? options.handler : options;
  22238. const processedOptions = await handler.call({
  22239. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  22240. error: (error_) => error(logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  22241. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  22242. meta: { rollupVersion: version, watchMode },
  22243. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  22244. }, inputOptions);
  22245. if (processedOptions) {
  22246. inputOptions = processedOptions;
  22247. }
  22248. }
  22249. return inputOptions;
  22250. }
  22251. function normalizePlugins(plugins, anonymousPrefix) {
  22252. for (const [index, plugin] of plugins.entries()) {
  22253. if (!plugin.name) {
  22254. plugin.name = `${anonymousPrefix}${index + 1}`;
  22255. }
  22256. }
  22257. }
  22258. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22259. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22260. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22261. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22262. const generated = await bundle.generate(isWrite);
  22263. if (isWrite) {
  22264. timeStart('WRITE', 1);
  22265. if (!outputOptions.dir && !outputOptions.file) {
  22266. return error(logMissingFileOrDirOption());
  22267. }
  22268. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  22269. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22270. timeEnd('WRITE', 1);
  22271. }
  22272. return createOutput(generated);
  22273. });
  22274. }
  22275. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22276. if (!rawOutputOptions) {
  22277. throw new Error('You must supply an options object');
  22278. }
  22279. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  22280. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22281. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22282. return {
  22283. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  22284. outputPluginDriver
  22285. };
  22286. }
  22287. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22288. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22289. const emitError = () => pluginContext.error(logCannotEmitFromOptionsHook());
  22290. return {
  22291. ...pluginContext,
  22292. emitFile: emitError,
  22293. setAssetSource: emitError
  22294. };
  22295. }), inputOptions, unsetInputOptions);
  22296. }
  22297. function createOutput(outputBundle) {
  22298. return {
  22299. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  22300. };
  22301. }
  22302. var SortingFileType;
  22303. (function (SortingFileType) {
  22304. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22305. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22306. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22307. })(SortingFileType || (SortingFileType = {}));
  22308. function getSortingFileType(file) {
  22309. if (file.type === 'asset') {
  22310. return SortingFileType.ASSET;
  22311. }
  22312. if (file.isEntry) {
  22313. return SortingFileType.ENTRY_CHUNK;
  22314. }
  22315. return SortingFileType.SECONDARY_CHUNK;
  22316. }
  22317. async function writeOutputFile(outputFile, outputOptions) {
  22318. const fileName = resolve$1(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  22319. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22320. await mkdir(dirname(fileName), { recursive: true });
  22321. return writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  22322. }
  22323. /**
  22324. * Auxiliary function for defining rollup configuration
  22325. * Mainly to facilitate IDE code prompts, after all, export default does not
  22326. * prompt, even if you add @type annotations, it is not accurate
  22327. * @param options
  22328. */
  22329. function defineConfig(options) {
  22330. return options;
  22331. }
  22332. var picocolors = {exports: {}};
  22333. var hasRequiredPicocolors;
  22334. function requirePicocolors () {
  22335. if (hasRequiredPicocolors) return picocolors.exports;
  22336. hasRequiredPicocolors = 1;
  22337. let p = process || {}, argv = p.argv || [], env = p.env || {};
  22338. let isColorSupported =
  22339. !(!!env.NO_COLOR || argv.includes("--no-color")) &&
  22340. (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
  22341. let formatter = (open, close, replace = open) =>
  22342. input => {
  22343. let string = "" + input, index = string.indexOf(close, open.length);
  22344. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  22345. };
  22346. let replaceClose = (string, close, replace, index) => {
  22347. let result = "", cursor = 0;
  22348. do {
  22349. result += string.substring(cursor, index) + replace;
  22350. cursor = index + close.length;
  22351. index = string.indexOf(close, cursor);
  22352. } while (~index)
  22353. return result + string.substring(cursor)
  22354. };
  22355. let createColors = (enabled = isColorSupported) => {
  22356. let f = enabled ? formatter : () => String;
  22357. return {
  22358. isColorSupported: enabled,
  22359. reset: f("\x1b[0m", "\x1b[0m"),
  22360. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  22361. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  22362. italic: f("\x1b[3m", "\x1b[23m"),
  22363. underline: f("\x1b[4m", "\x1b[24m"),
  22364. inverse: f("\x1b[7m", "\x1b[27m"),
  22365. hidden: f("\x1b[8m", "\x1b[28m"),
  22366. strikethrough: f("\x1b[9m", "\x1b[29m"),
  22367. black: f("\x1b[30m", "\x1b[39m"),
  22368. red: f("\x1b[31m", "\x1b[39m"),
  22369. green: f("\x1b[32m", "\x1b[39m"),
  22370. yellow: f("\x1b[33m", "\x1b[39m"),
  22371. blue: f("\x1b[34m", "\x1b[39m"),
  22372. magenta: f("\x1b[35m", "\x1b[39m"),
  22373. cyan: f("\x1b[36m", "\x1b[39m"),
  22374. white: f("\x1b[37m", "\x1b[39m"),
  22375. gray: f("\x1b[90m", "\x1b[39m"),
  22376. bgBlack: f("\x1b[40m", "\x1b[49m"),
  22377. bgRed: f("\x1b[41m", "\x1b[49m"),
  22378. bgGreen: f("\x1b[42m", "\x1b[49m"),
  22379. bgYellow: f("\x1b[43m", "\x1b[49m"),
  22380. bgBlue: f("\x1b[44m", "\x1b[49m"),
  22381. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  22382. bgCyan: f("\x1b[46m", "\x1b[49m"),
  22383. bgWhite: f("\x1b[47m", "\x1b[49m"),
  22384. blackBright: f("\x1b[90m", "\x1b[39m"),
  22385. redBright: f("\x1b[91m", "\x1b[39m"),
  22386. greenBright: f("\x1b[92m", "\x1b[39m"),
  22387. yellowBright: f("\x1b[93m", "\x1b[39m"),
  22388. blueBright: f("\x1b[94m", "\x1b[39m"),
  22389. magentaBright: f("\x1b[95m", "\x1b[39m"),
  22390. cyanBright: f("\x1b[96m", "\x1b[39m"),
  22391. whiteBright: f("\x1b[97m", "\x1b[39m"),
  22392. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  22393. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  22394. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  22395. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  22396. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  22397. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  22398. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  22399. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  22400. }
  22401. };
  22402. picocolors.exports = createColors();
  22403. picocolors.exports.createColors = createColors;
  22404. return picocolors.exports;
  22405. }
  22406. var picocolorsExports = /*@__PURE__*/ requirePicocolors();
  22407. const pc = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  22408. // @see https://no-color.org
  22409. // @see https://www.npmjs.com/package/chalk
  22410. const { bold, cyan, dim, red} = pc.createColors(env.FORCE_COLOR !== '0' && !env.NO_COLOR);
  22411. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  22412. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  22413. function handleError(error, recover = false) {
  22414. const name = error.name || error.cause?.name;
  22415. const nameSection = name ? `${name}: ` : '';
  22416. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  22417. const message = `${pluginSection}${nameSection}${error.message}`;
  22418. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  22419. if (error.url) {
  22420. outputLines.push(cyan(error.url));
  22421. }
  22422. if (error.loc) {
  22423. outputLines.push(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  22424. }
  22425. else if (error.id) {
  22426. outputLines.push(relativeId(error.id));
  22427. }
  22428. if (error.frame) {
  22429. outputLines.push(dim(error.frame));
  22430. }
  22431. if (error.stack) {
  22432. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  22433. }
  22434. // ES2022: Error.prototype.cause is optional
  22435. if (error.cause) {
  22436. let cause = error.cause;
  22437. const causeErrorLines = [];
  22438. let indent = '';
  22439. while (cause) {
  22440. indent += ' ';
  22441. const message = cause.stack || cause;
  22442. causeErrorLines.push(...`[cause] ${message}`.split('\n').map(line => indent + line));
  22443. cause = cause.cause;
  22444. }
  22445. outputLines.push(dim(causeErrorLines.join('\n')));
  22446. }
  22447. outputLines.push('', '');
  22448. stderr(outputLines.join('\n'));
  22449. if (!recover)
  22450. process$1.exit(1);
  22451. }
  22452. const commandAliases = {
  22453. c: 'config',
  22454. d: 'dir',
  22455. e: 'external',
  22456. f: 'format',
  22457. g: 'globals',
  22458. h: 'help',
  22459. i: 'input',
  22460. m: 'sourcemap',
  22461. n: 'name',
  22462. o: 'file',
  22463. p: 'plugin',
  22464. v: 'version',
  22465. w: 'watch'
  22466. };
  22467. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  22468. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  22469. const command = getCommandOptions(rawCommandOptions);
  22470. const plugins = await normalizePluginOption(config.plugins);
  22471. const logLevel = config.logLevel || LOGLEVEL_INFO;
  22472. const onLog = getOnLog(config, logLevel, printLog);
  22473. const log = getLogger(plugins, onLog, watchMode, logLevel);
  22474. const inputOptions = mergeInputOptions(config, command, plugins, log, onLog);
  22475. if (command.output) {
  22476. Object.assign(command, command.output);
  22477. }
  22478. const outputOptionsArray = ensureArray(config.output);
  22479. if (outputOptionsArray.length === 0)
  22480. outputOptionsArray.push({});
  22481. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  22482. warnUnknownOptions(command, [
  22483. ...Object.keys(inputOptions),
  22484. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  22485. ...Object.keys(commandAliases),
  22486. 'bundleConfigAsCjs',
  22487. 'config',
  22488. 'configImportAttributesKey',
  22489. 'configPlugin',
  22490. 'environment',
  22491. 'failAfterWarnings',
  22492. 'filterLogs',
  22493. 'forceExit',
  22494. 'plugin',
  22495. 'silent',
  22496. 'stdin',
  22497. 'waitForBundleInput'
  22498. ], 'CLI flags', log, /^_$|output$|config/);
  22499. inputOptions.output = outputOptions;
  22500. return inputOptions;
  22501. }
  22502. function getCommandOptions(rawCommandOptions) {
  22503. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  22504. ? rawCommandOptions.external.split(',')
  22505. : [];
  22506. return {
  22507. ...rawCommandOptions,
  22508. external,
  22509. globals: typeof rawCommandOptions.globals === 'string'
  22510. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  22511. const [id, variableName] = globalDefinition.split(':');
  22512. globals[id] = variableName;
  22513. if (!external.includes(id)) {
  22514. external.push(id);
  22515. }
  22516. return globals;
  22517. }, Object.create(null))
  22518. : undefined
  22519. };
  22520. }
  22521. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  22522. const getOption = (name) => overrides[name] ?? config[name];
  22523. const inputOptions = {
  22524. cache: config.cache,
  22525. context: getOption('context'),
  22526. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  22527. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  22528. external: getExternal(config, overrides),
  22529. input: getOption('input') || [],
  22530. jsx: getObjectOption(config, overrides, 'jsx', objectifyOptionWithPresets(jsxPresets, 'jsx', URL_JSX, 'false, ')),
  22531. logLevel: getOption('logLevel'),
  22532. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  22533. maxParallelFileOps: getOption('maxParallelFileOps'),
  22534. moduleContext: getOption('moduleContext'),
  22535. onLog,
  22536. onwarn: undefined,
  22537. perf: getOption('perf'),
  22538. plugins,
  22539. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  22540. preserveSymlinks: getOption('preserveSymlinks'),
  22541. shimMissingExports: getOption('shimMissingExports'),
  22542. strictDeprecations: getOption('strictDeprecations'),
  22543. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ')),
  22544. watch: getWatch(config, overrides)
  22545. };
  22546. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  22547. return inputOptions;
  22548. }
  22549. const getExternal = (config, overrides) => {
  22550. const configExternal = config.external;
  22551. return typeof configExternal === 'function'
  22552. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  22553. : [...ensureArray(configExternal), ...overrides.external];
  22554. };
  22555. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  22556. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  22557. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  22558. if (commandOption !== undefined) {
  22559. return commandOption && { ...configOption, ...commandOption };
  22560. }
  22561. return configOption;
  22562. };
  22563. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  22564. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  22565. if (!optionValue) {
  22566. return optionValue;
  22567. }
  22568. if (Array.isArray(optionValue)) {
  22569. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  22570. }
  22571. return objectifyValue(optionValue);
  22572. };
  22573. async function mergeOutputOptions(config, overrides, log) {
  22574. const getOption = (name) => overrides[name] ?? config[name];
  22575. const outputOptions = {
  22576. amd: getObjectOption(config, overrides, 'amd'),
  22577. assetFileNames: getOption('assetFileNames'),
  22578. banner: getOption('banner'),
  22579. chunkFileNames: getOption('chunkFileNames'),
  22580. compact: getOption('compact'),
  22581. dir: getOption('dir'),
  22582. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  22583. entryFileNames: getOption('entryFileNames'),
  22584. esModule: getOption('esModule'),
  22585. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  22586. exports: getOption('exports'),
  22587. extend: getOption('extend'),
  22588. externalImportAssertions: getOption('externalImportAssertions'),
  22589. externalImportAttributes: getOption('externalImportAttributes'),
  22590. externalLiveBindings: getOption('externalLiveBindings'),
  22591. file: getOption('file'),
  22592. footer: getOption('footer'),
  22593. format: getOption('format'),
  22594. freeze: getOption('freeze'),
  22595. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '')),
  22596. globals: getOption('globals'),
  22597. hashCharacters: getOption('hashCharacters'),
  22598. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  22599. importAttributesKey: getOption('importAttributesKey'),
  22600. indent: getOption('indent'),
  22601. inlineDynamicImports: getOption('inlineDynamicImports'),
  22602. interop: getOption('interop'),
  22603. intro: getOption('intro'),
  22604. manualChunks: getOption('manualChunks'),
  22605. minifyInternalExports: getOption('minifyInternalExports'),
  22606. name: getOption('name'),
  22607. noConflict: getOption('noConflict'),
  22608. outro: getOption('outro'),
  22609. paths: getOption('paths'),
  22610. plugins: await normalizePluginOption(config.plugins),
  22611. preserveModules: getOption('preserveModules'),
  22612. preserveModulesRoot: getOption('preserveModulesRoot'),
  22613. reexportProtoFromExternal: getOption('reexportProtoFromExternal'),
  22614. sanitizeFileName: getOption('sanitizeFileName'),
  22615. sourcemap: getOption('sourcemap'),
  22616. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  22617. sourcemapDebugIds: getOption('sourcemapDebugIds'),
  22618. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  22619. sourcemapFile: getOption('sourcemapFile'),
  22620. sourcemapFileNames: getOption('sourcemapFileNames'),
  22621. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  22622. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  22623. strict: getOption('strict'),
  22624. systemNullSetters: getOption('systemNullSetters'),
  22625. validate: getOption('validate'),
  22626. virtualDirname: getOption('virtualDirname')
  22627. };
  22628. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  22629. return outputOptions;
  22630. }
  22631. class WatchEmitter {
  22632. constructor() {
  22633. this.currentHandlers = Object.create(null);
  22634. this.persistentHandlers = Object.create(null);
  22635. }
  22636. // Will be overwritten by Rollup
  22637. async close() { }
  22638. emit(event, ...parameters) {
  22639. return Promise.all([...this.getCurrentHandlers(event), ...this.getPersistentHandlers(event)].map(handler => handler(...parameters)));
  22640. }
  22641. off(event, listener) {
  22642. const listeners = this.persistentHandlers[event];
  22643. if (listeners) {
  22644. // A hack stolen from "mitt": ">>> 0" does not change numbers >= 0, but -1
  22645. // (which would remove the last array element if used unchanged) is turned
  22646. // into max_int, which is outside the array and does not change anything.
  22647. listeners.splice(listeners.indexOf(listener) >>> 0, 1);
  22648. }
  22649. return this;
  22650. }
  22651. on(event, listener) {
  22652. this.getPersistentHandlers(event).push(listener);
  22653. return this;
  22654. }
  22655. onCurrentRun(event, listener) {
  22656. this.getCurrentHandlers(event).push(listener);
  22657. return this;
  22658. }
  22659. once(event, listener) {
  22660. const selfRemovingListener = (...parameters) => {
  22661. this.off(event, selfRemovingListener);
  22662. return listener(...parameters);
  22663. };
  22664. this.on(event, selfRemovingListener);
  22665. return this;
  22666. }
  22667. removeAllListeners() {
  22668. this.removeListenersForCurrentRun();
  22669. this.persistentHandlers = Object.create(null);
  22670. return this;
  22671. }
  22672. removeListenersForCurrentRun() {
  22673. this.currentHandlers = Object.create(null);
  22674. return this;
  22675. }
  22676. getCurrentHandlers(event) {
  22677. return this.currentHandlers[event] || (this.currentHandlers[event] = []);
  22678. }
  22679. getPersistentHandlers(event) {
  22680. return this.persistentHandlers[event] || (this.persistentHandlers[event] = []);
  22681. }
  22682. }
  22683. let fsEvents;
  22684. let fsEventsImportError;
  22685. async function loadFsEvents() {
  22686. try {
  22687. ({ default: fsEvents } = await import('fsevents'));
  22688. }
  22689. catch (error) {
  22690. fsEventsImportError = error;
  22691. }
  22692. }
  22693. // A call to this function will be injected into the chokidar code
  22694. function getFsEvents() {
  22695. if (fsEventsImportError)
  22696. throw fsEventsImportError;
  22697. return fsEvents;
  22698. }
  22699. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  22700. __proto__: null,
  22701. getFsEvents,
  22702. loadFsEvents
  22703. }, Symbol.toStringTag, { value: 'Module' });
  22704. function watch(configs) {
  22705. const emitter = new WatchEmitter();
  22706. watchInternal(configs, emitter).catch(error => {
  22707. handleError(error);
  22708. });
  22709. return emitter;
  22710. }
  22711. function withTrailingSlash(path) {
  22712. if (path[path.length - 1] !== '/') {
  22713. return `${path}/`;
  22714. }
  22715. return path;
  22716. }
  22717. function checkWatchConfig(config) {
  22718. for (const item of config) {
  22719. if (item.input && item.output) {
  22720. const input = typeof item.input === 'string' ? ensureArray(item.input) : item.input;
  22721. const output = ensureArray(item.output);
  22722. for (const index in input) {
  22723. const inputPath = input[index];
  22724. const subPath = output.find(o => {
  22725. if (!o.dir || typeof inputPath !== 'string') {
  22726. return false;
  22727. }
  22728. const _outPath = withTrailingSlash(o.dir);
  22729. const _inputPath = withTrailingSlash(inputPath);
  22730. return _inputPath.startsWith(_outPath);
  22731. });
  22732. if (subPath) {
  22733. error(logInvalidOption('watch', URL_WATCH, `the input "${inputPath}" is a subpath of the output "${subPath.dir}"`));
  22734. }
  22735. }
  22736. }
  22737. }
  22738. }
  22739. async function watchInternal(configs, emitter) {
  22740. const optionsList = await Promise.all(ensureArray(configs).map(config => mergeOptions(config, true)));
  22741. const watchOptionsList = optionsList.filter(config => config.watch !== false);
  22742. if (watchOptionsList.length === 0) {
  22743. return error(logInvalidOption('watch', URL_WATCH, 'there must be at least one config where "watch" is not set to "false"'));
  22744. }
  22745. checkWatchConfig(watchOptionsList);
  22746. await loadFsEvents();
  22747. const { Watcher } = await import('./watch.js');
  22748. new Watcher(watchOptionsList, emitter);
  22749. }
  22750. export { createFilter$1 as createFilter, defineConfig, fseventsImporter, getAugmentedNamespace, getDefaultExportFromCjs, rollup, rollupInternal, version, watch };