node-entry.js 785 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025
  1. /*
  2. @license
  3. Rollup.js v4.16.4
  4. Tue, 23 Apr 2024 13:14:37 GMT - commit 1c404fa352b70007066e94ff4c1981f8046f8cef
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import { normalize, getImportPath, EMPTY_ARRAY, LOGLEVEL_WARN, logUnusedExternalImports, ANNOTATION_KEY, INVALID_ANNOTATION_KEY, Program as Program$1, logRedeclarationError, CatchClause as CatchClause$1, logDuplicateArgumentNameError, CallExpression as CallExpression$1, BLANK, logIllegalImportReassignment, logModuleLevelDirective, ReturnStatement as ReturnStatement$1, Property as Property$1, logConstVariableReassignError, ExpressionStatement as ExpressionStatement$1, ArrowFunctionExpression as ArrowFunctionExpression$1, logMissingExport, EMPTY_SET, logCannotCallNamespace, logEval, BlockStatement as BlockStatement$1, getRollupError, logParseError, logModuleParseError, error, LOGLEVEL_INFO, logFirstSideEffect, locate, logInvalidAnnotation, Identifier as Identifier$1, logThisIsUndefined, getReadStringFunction, convertString, convertAnnotations, FIXED_STRINGS, convertNode as convertNode$1, EMPTY_OBJECT, logImportAttributeIsInvalid, logImportOptionsAreInvalid, logSyntheticNamedExportsNeedNamespaceExport, logMissingEntryExport, logInvalidFormatForTopLevelAwait, logDuplicateExportError, logInvalidSourcemapForError, augmentCodeLocation, logInconsistentImportAttributes, logNamespaceConflict, logAmbiguousExternalNamespaces, logShimmedExport, parseAst, logCircularReexport, TemplateLiteral as TemplateLiteral$1, Literal as Literal$1, logMissingNodeBuiltins, logIllegalIdentifierAsName, logMissingNameOptionForIifeExport, logMissingNameOptionForUmdExport, 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, LOGLEVEL_ERROR, logLevelPriority, LOGLEVEL_DEBUG, logUnknownOption, printQuotedStringList, logInvalidSetAssetSourceCall, logPluginError, logNoTransformMapOrAstWithoutCode, relativeId, logBadLoader, logExternalModulesCannotBeTransformedToModules, logInternalIdCannotBeExternal, isRelative, logUnresolvedImport, logUnresolvedImportTreatedAsExternal, logExternalSyntheticExports, logUnresolvedEntry, logUnresolvedImplicitDependant, logExternalModulesCannotBeIncludedInManualChunks, logEntryCannotBeExternal, logImplicitDependantCannotBeExternal, logNoAssetSourceSet, logFileReferenceIdNotFoundForFilename, logAssetReferenceIdNotFoundForSetSource, logAssetSourceAlreadySet, logInvalidRollupPhaseForChunkEmission, logFileNameConflict, logAssetNotFinalisedForFileName, logChunkNotGeneratedForFileName, logInvalidLogPosition, logInputHookInOutputPlugin, logInvalidFunctionPluginHook, logInvalidAddonPluginHook, logImplicitDependantIsNotIncluded, logCircularDependency, augmentLogMessage, URL_TREESHAKE_MODULESIDEEFFECTS, URL_TREESHAKE, URL_OUTPUT_INLINEDYNAMICIMPORTS, URL_PRESERVEENTRYSIGNATURES, URL_OUTPUT_AMD_BASEPATH, logInvalidExportOptionValue, warnDeprecation, URL_OUTPUT_INTEROP, URL_OUTPUT_MANUALCHUNKS, isValidUrl, addTrailingSlashIfMissed, URL_OUTPUT_SOURCEMAPBASEURL, URL_OUTPUT_GENERATEDCODE, 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 require$$0$1, { win32, posix, isAbsolute, resolve } from 'path';
  11. import { parseAsync, xxhashBase64Url, xxhashBase36, xxhashBase16 } from '../../native.js';
  12. import process$1, { env as env$1 } from 'node:process';
  13. import { performance } from 'node:perf_hooks';
  14. import { lstat, realpath, readdir, readFile, mkdir, writeFile } from 'node:fs/promises';
  15. import * as tty from 'tty';
  16. var version = "4.16.4";
  17. const comma = ','.charCodeAt(0);
  18. const semicolon = ';'.charCodeAt(0);
  19. const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  20. const intToChar = new Uint8Array(64); // 64 possible chars.
  21. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  22. for (let i = 0; i < chars$1.length; i++) {
  23. const c = chars$1.charCodeAt(i);
  24. intToChar[i] = c;
  25. charToInt[c] = i;
  26. }
  27. // Provide a fallback for older environments.
  28. const td = typeof TextDecoder !== 'undefined'
  29. ? /* #__PURE__ */ new TextDecoder()
  30. : typeof Buffer !== 'undefined'
  31. ? {
  32. decode(buf) {
  33. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  34. return out.toString();
  35. },
  36. }
  37. : {
  38. decode(buf) {
  39. let out = '';
  40. for (let i = 0; i < buf.length; i++) {
  41. out += String.fromCharCode(buf[i]);
  42. }
  43. return out;
  44. },
  45. };
  46. function decode(mappings) {
  47. const state = new Int32Array(5);
  48. const decoded = [];
  49. let index = 0;
  50. do {
  51. const semi = indexOf(mappings, index);
  52. const line = [];
  53. let sorted = true;
  54. let lastCol = 0;
  55. state[0] = 0;
  56. for (let i = index; i < semi; i++) {
  57. let seg;
  58. i = decodeInteger(mappings, i, state, 0); // genColumn
  59. const col = state[0];
  60. if (col < lastCol)
  61. sorted = false;
  62. lastCol = col;
  63. if (hasMoreVlq(mappings, i, semi)) {
  64. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  65. i = decodeInteger(mappings, i, state, 2); // sourceLine
  66. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  67. if (hasMoreVlq(mappings, i, semi)) {
  68. i = decodeInteger(mappings, i, state, 4); // namesIndex
  69. seg = [col, state[1], state[2], state[3], state[4]];
  70. }
  71. else {
  72. seg = [col, state[1], state[2], state[3]];
  73. }
  74. }
  75. else {
  76. seg = [col];
  77. }
  78. line.push(seg);
  79. }
  80. if (!sorted)
  81. sort(line);
  82. decoded.push(line);
  83. index = semi + 1;
  84. } while (index <= mappings.length);
  85. return decoded;
  86. }
  87. function indexOf(mappings, index) {
  88. const idx = mappings.indexOf(';', index);
  89. return idx === -1 ? mappings.length : idx;
  90. }
  91. function decodeInteger(mappings, pos, state, j) {
  92. let value = 0;
  93. let shift = 0;
  94. let integer = 0;
  95. do {
  96. const c = mappings.charCodeAt(pos++);
  97. integer = charToInt[c];
  98. value |= (integer & 31) << shift;
  99. shift += 5;
  100. } while (integer & 32);
  101. const shouldNegate = value & 1;
  102. value >>>= 1;
  103. if (shouldNegate) {
  104. value = -0x80000000 | -value;
  105. }
  106. state[j] += value;
  107. return pos;
  108. }
  109. function hasMoreVlq(mappings, i, length) {
  110. if (i >= length)
  111. return false;
  112. return mappings.charCodeAt(i) !== comma;
  113. }
  114. function sort(line) {
  115. line.sort(sortComparator);
  116. }
  117. function sortComparator(a, b) {
  118. return a[0] - b[0];
  119. }
  120. function encode(decoded) {
  121. const state = new Int32Array(5);
  122. const bufLength = 1024 * 16;
  123. const subLength = bufLength - 36;
  124. const buf = new Uint8Array(bufLength);
  125. const sub = buf.subarray(0, subLength);
  126. let pos = 0;
  127. let out = '';
  128. for (let i = 0; i < decoded.length; i++) {
  129. const line = decoded[i];
  130. if (i > 0) {
  131. if (pos === bufLength) {
  132. out += td.decode(buf);
  133. pos = 0;
  134. }
  135. buf[pos++] = semicolon;
  136. }
  137. if (line.length === 0)
  138. continue;
  139. state[0] = 0;
  140. for (let j = 0; j < line.length; j++) {
  141. const segment = line[j];
  142. // We can push up to 5 ints, each int can take at most 7 chars, and we
  143. // may push a comma.
  144. if (pos > subLength) {
  145. out += td.decode(sub);
  146. buf.copyWithin(0, subLength, pos);
  147. pos -= subLength;
  148. }
  149. if (j > 0)
  150. buf[pos++] = comma;
  151. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  152. if (segment.length === 1)
  153. continue;
  154. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  155. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  156. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  157. if (segment.length === 4)
  158. continue;
  159. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  160. }
  161. }
  162. return out + td.decode(buf.subarray(0, pos));
  163. }
  164. function encodeInteger(buf, pos, state, segment, j) {
  165. const next = segment[j];
  166. let num = next - state[j];
  167. state[j] = next;
  168. num = num < 0 ? (-num << 1) | 1 : num << 1;
  169. do {
  170. let clamped = num & 0b011111;
  171. num >>>= 5;
  172. if (num > 0)
  173. clamped |= 0b100000;
  174. buf[pos++] = intToChar[clamped];
  175. } while (num > 0);
  176. return pos;
  177. }
  178. class BitSet {
  179. constructor(arg) {
  180. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  181. }
  182. add(n) {
  183. this.bits[n >> 5] |= 1 << (n & 31);
  184. }
  185. has(n) {
  186. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  187. }
  188. }
  189. let Chunk$1 = class Chunk {
  190. constructor(start, end, content) {
  191. this.start = start;
  192. this.end = end;
  193. this.original = content;
  194. this.intro = '';
  195. this.outro = '';
  196. this.content = content;
  197. this.storeName = false;
  198. this.edited = false;
  199. {
  200. this.previous = null;
  201. this.next = null;
  202. }
  203. }
  204. appendLeft(content) {
  205. this.outro += content;
  206. }
  207. appendRight(content) {
  208. this.intro = this.intro + content;
  209. }
  210. clone() {
  211. const chunk = new Chunk(this.start, this.end, this.original);
  212. chunk.intro = this.intro;
  213. chunk.outro = this.outro;
  214. chunk.content = this.content;
  215. chunk.storeName = this.storeName;
  216. chunk.edited = this.edited;
  217. return chunk;
  218. }
  219. contains(index) {
  220. return this.start < index && index < this.end;
  221. }
  222. eachNext(fn) {
  223. let chunk = this;
  224. while (chunk) {
  225. fn(chunk);
  226. chunk = chunk.next;
  227. }
  228. }
  229. eachPrevious(fn) {
  230. let chunk = this;
  231. while (chunk) {
  232. fn(chunk);
  233. chunk = chunk.previous;
  234. }
  235. }
  236. edit(content, storeName, contentOnly) {
  237. this.content = content;
  238. if (!contentOnly) {
  239. this.intro = '';
  240. this.outro = '';
  241. }
  242. this.storeName = storeName;
  243. this.edited = true;
  244. return this;
  245. }
  246. prependLeft(content) {
  247. this.outro = content + this.outro;
  248. }
  249. prependRight(content) {
  250. this.intro = content + this.intro;
  251. }
  252. reset() {
  253. this.intro = '';
  254. this.outro = '';
  255. if (this.edited) {
  256. this.content = this.original;
  257. this.storeName = false;
  258. this.edited = false;
  259. }
  260. }
  261. split(index) {
  262. const sliceIndex = index - this.start;
  263. const originalBefore = this.original.slice(0, sliceIndex);
  264. const originalAfter = this.original.slice(sliceIndex);
  265. this.original = originalBefore;
  266. const newChunk = new Chunk(index, this.end, originalAfter);
  267. newChunk.outro = this.outro;
  268. this.outro = '';
  269. this.end = index;
  270. if (this.edited) {
  271. // after split we should save the edit content record into the correct chunk
  272. // to make sure sourcemap correct
  273. // For example:
  274. // ' test'.trim()
  275. // split -> ' ' + 'test'
  276. // ✔️ edit -> '' + 'test'
  277. // ✖️ edit -> 'test' + ''
  278. // TODO is this block necessary?...
  279. newChunk.edit('', false);
  280. this.content = '';
  281. } else {
  282. this.content = originalBefore;
  283. }
  284. newChunk.next = this.next;
  285. if (newChunk.next) newChunk.next.previous = newChunk;
  286. newChunk.previous = this;
  287. this.next = newChunk;
  288. return newChunk;
  289. }
  290. toString() {
  291. return this.intro + this.content + this.outro;
  292. }
  293. trimEnd(rx) {
  294. this.outro = this.outro.replace(rx, '');
  295. if (this.outro.length) return true;
  296. const trimmed = this.content.replace(rx, '');
  297. if (trimmed.length) {
  298. if (trimmed !== this.content) {
  299. this.split(this.start + trimmed.length).edit('', undefined, true);
  300. if (this.edited) {
  301. // save the change, if it has been edited
  302. this.edit(trimmed, this.storeName, true);
  303. }
  304. }
  305. return true;
  306. } else {
  307. this.edit('', undefined, true);
  308. this.intro = this.intro.replace(rx, '');
  309. if (this.intro.length) return true;
  310. }
  311. }
  312. trimStart(rx) {
  313. this.intro = this.intro.replace(rx, '');
  314. if (this.intro.length) return true;
  315. const trimmed = this.content.replace(rx, '');
  316. if (trimmed.length) {
  317. if (trimmed !== this.content) {
  318. const newChunk = this.split(this.end - trimmed.length);
  319. if (this.edited) {
  320. // save the change, if it has been edited
  321. newChunk.edit(trimmed, this.storeName, true);
  322. }
  323. this.edit('', undefined, true);
  324. }
  325. return true;
  326. } else {
  327. this.edit('', undefined, true);
  328. this.outro = this.outro.replace(rx, '');
  329. if (this.outro.length) return true;
  330. }
  331. }
  332. };
  333. function getBtoa() {
  334. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  335. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  336. } else if (typeof Buffer === 'function') {
  337. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  338. } else {
  339. return () => {
  340. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  341. };
  342. }
  343. }
  344. const btoa = /*#__PURE__*/ getBtoa();
  345. class SourceMap {
  346. constructor(properties) {
  347. this.version = 3;
  348. this.file = properties.file;
  349. this.sources = properties.sources;
  350. this.sourcesContent = properties.sourcesContent;
  351. this.names = properties.names;
  352. this.mappings = encode(properties.mappings);
  353. if (typeof properties.x_google_ignoreList !== 'undefined') {
  354. this.x_google_ignoreList = properties.x_google_ignoreList;
  355. }
  356. }
  357. toString() {
  358. return JSON.stringify(this);
  359. }
  360. toUrl() {
  361. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  362. }
  363. }
  364. function guessIndent(code) {
  365. const lines = code.split('\n');
  366. const tabbed = lines.filter((line) => /^\t+/.test(line));
  367. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  368. if (tabbed.length === 0 && spaced.length === 0) {
  369. return null;
  370. }
  371. // More lines tabbed than spaced? Assume tabs, and
  372. // default to tabs in the case of a tie (or nothing
  373. // to go on)
  374. if (tabbed.length >= spaced.length) {
  375. return '\t';
  376. }
  377. // Otherwise, we need to guess the multiple
  378. const min = spaced.reduce((previous, current) => {
  379. const numSpaces = /^ +/.exec(current)[0].length;
  380. return Math.min(numSpaces, previous);
  381. }, Infinity);
  382. return new Array(min + 1).join(' ');
  383. }
  384. function getRelativePath(from, to) {
  385. const fromParts = from.split(/[/\\]/);
  386. const toParts = to.split(/[/\\]/);
  387. fromParts.pop(); // get dirname
  388. while (fromParts[0] === toParts[0]) {
  389. fromParts.shift();
  390. toParts.shift();
  391. }
  392. if (fromParts.length) {
  393. let i = fromParts.length;
  394. while (i--) fromParts[i] = '..';
  395. }
  396. return fromParts.concat(toParts).join('/');
  397. }
  398. const toString = Object.prototype.toString;
  399. function isObject$1(thing) {
  400. return toString.call(thing) === '[object Object]';
  401. }
  402. function getLocator(source) {
  403. const originalLines = source.split('\n');
  404. const lineOffsets = [];
  405. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  406. lineOffsets.push(pos);
  407. pos += originalLines[i].length + 1;
  408. }
  409. return function locate(index) {
  410. let i = 0;
  411. let j = lineOffsets.length;
  412. while (i < j) {
  413. const m = (i + j) >> 1;
  414. if (index < lineOffsets[m]) {
  415. j = m;
  416. } else {
  417. i = m + 1;
  418. }
  419. }
  420. const line = i - 1;
  421. const column = index - lineOffsets[line];
  422. return { line, column };
  423. };
  424. }
  425. const wordRegex = /\w/;
  426. class Mappings {
  427. constructor(hires) {
  428. this.hires = hires;
  429. this.generatedCodeLine = 0;
  430. this.generatedCodeColumn = 0;
  431. this.raw = [];
  432. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  433. this.pending = null;
  434. }
  435. addEdit(sourceIndex, content, loc, nameIndex) {
  436. if (content.length) {
  437. const contentLengthMinusOne = content.length - 1;
  438. let contentLineEnd = content.indexOf('\n', 0);
  439. let previousContentLineEnd = -1;
  440. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  441. // else code afterwards would fill one line too many
  442. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  443. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  444. if (nameIndex >= 0) {
  445. segment.push(nameIndex);
  446. }
  447. this.rawSegments.push(segment);
  448. this.generatedCodeLine += 1;
  449. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  450. this.generatedCodeColumn = 0;
  451. previousContentLineEnd = contentLineEnd;
  452. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  453. }
  454. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  455. if (nameIndex >= 0) {
  456. segment.push(nameIndex);
  457. }
  458. this.rawSegments.push(segment);
  459. this.advance(content.slice(previousContentLineEnd + 1));
  460. } else if (this.pending) {
  461. this.rawSegments.push(this.pending);
  462. this.advance(content);
  463. }
  464. this.pending = null;
  465. }
  466. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  467. let originalCharIndex = chunk.start;
  468. let first = true;
  469. // when iterating each char, check if it's in a word boundary
  470. let charInHiresBoundary = false;
  471. while (originalCharIndex < chunk.end) {
  472. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  473. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  474. if (this.hires === 'boundary') {
  475. // in hires "boundary", group segments per word boundary than per char
  476. if (wordRegex.test(original[originalCharIndex])) {
  477. // for first char in the boundary found, start the boundary by pushing a segment
  478. if (!charInHiresBoundary) {
  479. this.rawSegments.push(segment);
  480. charInHiresBoundary = true;
  481. }
  482. } else {
  483. // for non-word char, end the boundary by pushing a segment
  484. this.rawSegments.push(segment);
  485. charInHiresBoundary = false;
  486. }
  487. } else {
  488. this.rawSegments.push(segment);
  489. }
  490. }
  491. if (original[originalCharIndex] === '\n') {
  492. loc.line += 1;
  493. loc.column = 0;
  494. this.generatedCodeLine += 1;
  495. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  496. this.generatedCodeColumn = 0;
  497. first = true;
  498. } else {
  499. loc.column += 1;
  500. this.generatedCodeColumn += 1;
  501. first = false;
  502. }
  503. originalCharIndex += 1;
  504. }
  505. this.pending = null;
  506. }
  507. advance(str) {
  508. if (!str) return;
  509. const lines = str.split('\n');
  510. if (lines.length > 1) {
  511. for (let i = 0; i < lines.length - 1; i++) {
  512. this.generatedCodeLine++;
  513. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  514. }
  515. this.generatedCodeColumn = 0;
  516. }
  517. this.generatedCodeColumn += lines[lines.length - 1].length;
  518. }
  519. }
  520. const n = '\n';
  521. const warned = {
  522. insertLeft: false,
  523. insertRight: false,
  524. storeName: false,
  525. };
  526. class MagicString {
  527. constructor(string, options = {}) {
  528. const chunk = new Chunk$1(0, string.length, string);
  529. Object.defineProperties(this, {
  530. original: { writable: true, value: string },
  531. outro: { writable: true, value: '' },
  532. intro: { writable: true, value: '' },
  533. firstChunk: { writable: true, value: chunk },
  534. lastChunk: { writable: true, value: chunk },
  535. lastSearchedChunk: { writable: true, value: chunk },
  536. byStart: { writable: true, value: {} },
  537. byEnd: { writable: true, value: {} },
  538. filename: { writable: true, value: options.filename },
  539. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  540. sourcemapLocations: { writable: true, value: new BitSet() },
  541. storedNames: { writable: true, value: {} },
  542. indentStr: { writable: true, value: undefined },
  543. ignoreList: { writable: true, value: options.ignoreList },
  544. });
  545. this.byStart[0] = chunk;
  546. this.byEnd[string.length] = chunk;
  547. }
  548. addSourcemapLocation(char) {
  549. this.sourcemapLocations.add(char);
  550. }
  551. append(content) {
  552. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  553. this.outro += content;
  554. return this;
  555. }
  556. appendLeft(index, content) {
  557. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  558. this._split(index);
  559. const chunk = this.byEnd[index];
  560. if (chunk) {
  561. chunk.appendLeft(content);
  562. } else {
  563. this.intro += content;
  564. }
  565. return this;
  566. }
  567. appendRight(index, content) {
  568. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  569. this._split(index);
  570. const chunk = this.byStart[index];
  571. if (chunk) {
  572. chunk.appendRight(content);
  573. } else {
  574. this.outro += content;
  575. }
  576. return this;
  577. }
  578. clone() {
  579. const cloned = new MagicString(this.original, { filename: this.filename });
  580. let originalChunk = this.firstChunk;
  581. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  582. while (originalChunk) {
  583. cloned.byStart[clonedChunk.start] = clonedChunk;
  584. cloned.byEnd[clonedChunk.end] = clonedChunk;
  585. const nextOriginalChunk = originalChunk.next;
  586. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  587. if (nextClonedChunk) {
  588. clonedChunk.next = nextClonedChunk;
  589. nextClonedChunk.previous = clonedChunk;
  590. clonedChunk = nextClonedChunk;
  591. }
  592. originalChunk = nextOriginalChunk;
  593. }
  594. cloned.lastChunk = clonedChunk;
  595. if (this.indentExclusionRanges) {
  596. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  597. }
  598. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  599. cloned.intro = this.intro;
  600. cloned.outro = this.outro;
  601. return cloned;
  602. }
  603. generateDecodedMap(options) {
  604. options = options || {};
  605. const sourceIndex = 0;
  606. const names = Object.keys(this.storedNames);
  607. const mappings = new Mappings(options.hires);
  608. const locate = getLocator(this.original);
  609. if (this.intro) {
  610. mappings.advance(this.intro);
  611. }
  612. this.firstChunk.eachNext((chunk) => {
  613. const loc = locate(chunk.start);
  614. if (chunk.intro.length) mappings.advance(chunk.intro);
  615. if (chunk.edited) {
  616. mappings.addEdit(
  617. sourceIndex,
  618. chunk.content,
  619. loc,
  620. chunk.storeName ? names.indexOf(chunk.original) : -1,
  621. );
  622. } else {
  623. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  624. }
  625. if (chunk.outro.length) mappings.advance(chunk.outro);
  626. });
  627. return {
  628. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  629. sources: [
  630. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  631. ],
  632. sourcesContent: options.includeContent ? [this.original] : undefined,
  633. names,
  634. mappings: mappings.raw,
  635. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  636. };
  637. }
  638. generateMap(options) {
  639. return new SourceMap(this.generateDecodedMap(options));
  640. }
  641. _ensureindentStr() {
  642. if (this.indentStr === undefined) {
  643. this.indentStr = guessIndent(this.original);
  644. }
  645. }
  646. _getRawIndentString() {
  647. this._ensureindentStr();
  648. return this.indentStr;
  649. }
  650. getIndentString() {
  651. this._ensureindentStr();
  652. return this.indentStr === null ? '\t' : this.indentStr;
  653. }
  654. indent(indentStr, options) {
  655. const pattern = /^[^\r\n]/gm;
  656. if (isObject$1(indentStr)) {
  657. options = indentStr;
  658. indentStr = undefined;
  659. }
  660. if (indentStr === undefined) {
  661. this._ensureindentStr();
  662. indentStr = this.indentStr || '\t';
  663. }
  664. if (indentStr === '') return this; // noop
  665. options = options || {};
  666. // Process exclusion ranges
  667. const isExcluded = {};
  668. if (options.exclude) {
  669. const exclusions =
  670. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  671. exclusions.forEach((exclusion) => {
  672. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  673. isExcluded[i] = true;
  674. }
  675. });
  676. }
  677. let shouldIndentNextCharacter = options.indentStart !== false;
  678. const replacer = (match) => {
  679. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  680. shouldIndentNextCharacter = true;
  681. return match;
  682. };
  683. this.intro = this.intro.replace(pattern, replacer);
  684. let charIndex = 0;
  685. let chunk = this.firstChunk;
  686. while (chunk) {
  687. const end = chunk.end;
  688. if (chunk.edited) {
  689. if (!isExcluded[charIndex]) {
  690. chunk.content = chunk.content.replace(pattern, replacer);
  691. if (chunk.content.length) {
  692. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  693. }
  694. }
  695. } else {
  696. charIndex = chunk.start;
  697. while (charIndex < end) {
  698. if (!isExcluded[charIndex]) {
  699. const char = this.original[charIndex];
  700. if (char === '\n') {
  701. shouldIndentNextCharacter = true;
  702. } else if (char !== '\r' && shouldIndentNextCharacter) {
  703. shouldIndentNextCharacter = false;
  704. if (charIndex === chunk.start) {
  705. chunk.prependRight(indentStr);
  706. } else {
  707. this._splitChunk(chunk, charIndex);
  708. chunk = chunk.next;
  709. chunk.prependRight(indentStr);
  710. }
  711. }
  712. }
  713. charIndex += 1;
  714. }
  715. }
  716. charIndex = chunk.end;
  717. chunk = chunk.next;
  718. }
  719. this.outro = this.outro.replace(pattern, replacer);
  720. return this;
  721. }
  722. insert() {
  723. throw new Error(
  724. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  725. );
  726. }
  727. insertLeft(index, content) {
  728. if (!warned.insertLeft) {
  729. console.warn(
  730. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  731. ); // eslint-disable-line no-console
  732. warned.insertLeft = true;
  733. }
  734. return this.appendLeft(index, content);
  735. }
  736. insertRight(index, content) {
  737. if (!warned.insertRight) {
  738. console.warn(
  739. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  740. ); // eslint-disable-line no-console
  741. warned.insertRight = true;
  742. }
  743. return this.prependRight(index, content);
  744. }
  745. move(start, end, index) {
  746. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  747. this._split(start);
  748. this._split(end);
  749. this._split(index);
  750. const first = this.byStart[start];
  751. const last = this.byEnd[end];
  752. const oldLeft = first.previous;
  753. const oldRight = last.next;
  754. const newRight = this.byStart[index];
  755. if (!newRight && last === this.lastChunk) return this;
  756. const newLeft = newRight ? newRight.previous : this.lastChunk;
  757. if (oldLeft) oldLeft.next = oldRight;
  758. if (oldRight) oldRight.previous = oldLeft;
  759. if (newLeft) newLeft.next = first;
  760. if (newRight) newRight.previous = last;
  761. if (!first.previous) this.firstChunk = last.next;
  762. if (!last.next) {
  763. this.lastChunk = first.previous;
  764. this.lastChunk.next = null;
  765. }
  766. first.previous = newLeft;
  767. last.next = newRight || null;
  768. if (!newLeft) this.firstChunk = first;
  769. if (!newRight) this.lastChunk = last;
  770. return this;
  771. }
  772. overwrite(start, end, content, options) {
  773. options = options || {};
  774. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  775. }
  776. update(start, end, content, options) {
  777. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  778. while (start < 0) start += this.original.length;
  779. while (end < 0) end += this.original.length;
  780. if (end > this.original.length) throw new Error('end is out of bounds');
  781. if (start === end)
  782. throw new Error(
  783. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  784. );
  785. this._split(start);
  786. this._split(end);
  787. if (options === true) {
  788. if (!warned.storeName) {
  789. console.warn(
  790. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  791. ); // eslint-disable-line no-console
  792. warned.storeName = true;
  793. }
  794. options = { storeName: true };
  795. }
  796. const storeName = options !== undefined ? options.storeName : false;
  797. const overwrite = options !== undefined ? options.overwrite : false;
  798. if (storeName) {
  799. const original = this.original.slice(start, end);
  800. Object.defineProperty(this.storedNames, original, {
  801. writable: true,
  802. value: true,
  803. enumerable: true,
  804. });
  805. }
  806. const first = this.byStart[start];
  807. const last = this.byEnd[end];
  808. if (first) {
  809. let chunk = first;
  810. while (chunk !== last) {
  811. if (chunk.next !== this.byStart[chunk.end]) {
  812. throw new Error('Cannot overwrite across a split point');
  813. }
  814. chunk = chunk.next;
  815. chunk.edit('', false);
  816. }
  817. first.edit(content, storeName, !overwrite);
  818. } else {
  819. // must be inserting at the end
  820. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  821. // TODO last chunk in the array may not be the last chunk, if it's moved...
  822. last.next = newChunk;
  823. newChunk.previous = last;
  824. }
  825. return this;
  826. }
  827. prepend(content) {
  828. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  829. this.intro = content + this.intro;
  830. return this;
  831. }
  832. prependLeft(index, content) {
  833. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  834. this._split(index);
  835. const chunk = this.byEnd[index];
  836. if (chunk) {
  837. chunk.prependLeft(content);
  838. } else {
  839. this.intro = content + this.intro;
  840. }
  841. return this;
  842. }
  843. prependRight(index, content) {
  844. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  845. this._split(index);
  846. const chunk = this.byStart[index];
  847. if (chunk) {
  848. chunk.prependRight(content);
  849. } else {
  850. this.outro = content + this.outro;
  851. }
  852. return this;
  853. }
  854. remove(start, end) {
  855. while (start < 0) start += this.original.length;
  856. while (end < 0) end += this.original.length;
  857. if (start === end) return this;
  858. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  859. if (start > end) throw new Error('end must be greater than start');
  860. this._split(start);
  861. this._split(end);
  862. let chunk = this.byStart[start];
  863. while (chunk) {
  864. chunk.intro = '';
  865. chunk.outro = '';
  866. chunk.edit('');
  867. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  868. }
  869. return this;
  870. }
  871. reset(start, end) {
  872. while (start < 0) start += this.original.length;
  873. while (end < 0) end += this.original.length;
  874. if (start === end) return this;
  875. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  876. if (start > end) throw new Error('end must be greater than start');
  877. this._split(start);
  878. this._split(end);
  879. let chunk = this.byStart[start];
  880. while (chunk) {
  881. chunk.reset();
  882. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  883. }
  884. return this;
  885. }
  886. lastChar() {
  887. if (this.outro.length) return this.outro[this.outro.length - 1];
  888. let chunk = this.lastChunk;
  889. do {
  890. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  891. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  892. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  893. } while ((chunk = chunk.previous));
  894. if (this.intro.length) return this.intro[this.intro.length - 1];
  895. return '';
  896. }
  897. lastLine() {
  898. let lineIndex = this.outro.lastIndexOf(n);
  899. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  900. let lineStr = this.outro;
  901. let chunk = this.lastChunk;
  902. do {
  903. if (chunk.outro.length > 0) {
  904. lineIndex = chunk.outro.lastIndexOf(n);
  905. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  906. lineStr = chunk.outro + lineStr;
  907. }
  908. if (chunk.content.length > 0) {
  909. lineIndex = chunk.content.lastIndexOf(n);
  910. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  911. lineStr = chunk.content + lineStr;
  912. }
  913. if (chunk.intro.length > 0) {
  914. lineIndex = chunk.intro.lastIndexOf(n);
  915. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  916. lineStr = chunk.intro + lineStr;
  917. }
  918. } while ((chunk = chunk.previous));
  919. lineIndex = this.intro.lastIndexOf(n);
  920. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  921. return this.intro + lineStr;
  922. }
  923. slice(start = 0, end = this.original.length) {
  924. while (start < 0) start += this.original.length;
  925. while (end < 0) end += this.original.length;
  926. let result = '';
  927. // find start chunk
  928. let chunk = this.firstChunk;
  929. while (chunk && (chunk.start > start || chunk.end <= start)) {
  930. // found end chunk before start
  931. if (chunk.start < end && chunk.end >= end) {
  932. return result;
  933. }
  934. chunk = chunk.next;
  935. }
  936. if (chunk && chunk.edited && chunk.start !== start)
  937. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  938. const startChunk = chunk;
  939. while (chunk) {
  940. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  941. result += chunk.intro;
  942. }
  943. const containsEnd = chunk.start < end && chunk.end >= end;
  944. if (containsEnd && chunk.edited && chunk.end !== end)
  945. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  946. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  947. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  948. result += chunk.content.slice(sliceStart, sliceEnd);
  949. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  950. result += chunk.outro;
  951. }
  952. if (containsEnd) {
  953. break;
  954. }
  955. chunk = chunk.next;
  956. }
  957. return result;
  958. }
  959. // TODO deprecate this? not really very useful
  960. snip(start, end) {
  961. const clone = this.clone();
  962. clone.remove(0, start);
  963. clone.remove(end, clone.original.length);
  964. return clone;
  965. }
  966. _split(index) {
  967. if (this.byStart[index] || this.byEnd[index]) return;
  968. let chunk = this.lastSearchedChunk;
  969. const searchForward = index > chunk.end;
  970. while (chunk) {
  971. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  972. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  973. }
  974. }
  975. _splitChunk(chunk, index) {
  976. if (chunk.edited && chunk.content.length) {
  977. // zero-length edited chunks are a special case (overlapping replacements)
  978. const loc = getLocator(this.original)(index);
  979. throw new Error(
  980. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  981. );
  982. }
  983. const newChunk = chunk.split(index);
  984. this.byEnd[index] = chunk;
  985. this.byStart[index] = newChunk;
  986. this.byEnd[newChunk.end] = newChunk;
  987. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  988. this.lastSearchedChunk = chunk;
  989. return true;
  990. }
  991. toString() {
  992. let str = this.intro;
  993. let chunk = this.firstChunk;
  994. while (chunk) {
  995. str += chunk.toString();
  996. chunk = chunk.next;
  997. }
  998. return str + this.outro;
  999. }
  1000. isEmpty() {
  1001. let chunk = this.firstChunk;
  1002. do {
  1003. if (
  1004. (chunk.intro.length && chunk.intro.trim()) ||
  1005. (chunk.content.length && chunk.content.trim()) ||
  1006. (chunk.outro.length && chunk.outro.trim())
  1007. )
  1008. return false;
  1009. } while ((chunk = chunk.next));
  1010. return true;
  1011. }
  1012. length() {
  1013. let chunk = this.firstChunk;
  1014. let length = 0;
  1015. do {
  1016. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  1017. } while ((chunk = chunk.next));
  1018. return length;
  1019. }
  1020. trimLines() {
  1021. return this.trim('[\\r\\n]');
  1022. }
  1023. trim(charType) {
  1024. return this.trimStart(charType).trimEnd(charType);
  1025. }
  1026. trimEndAborted(charType) {
  1027. const rx = new RegExp((charType || '\\s') + '+$');
  1028. this.outro = this.outro.replace(rx, '');
  1029. if (this.outro.length) return true;
  1030. let chunk = this.lastChunk;
  1031. do {
  1032. const end = chunk.end;
  1033. const aborted = chunk.trimEnd(rx);
  1034. // if chunk was trimmed, we have a new lastChunk
  1035. if (chunk.end !== end) {
  1036. if (this.lastChunk === chunk) {
  1037. this.lastChunk = chunk.next;
  1038. }
  1039. this.byEnd[chunk.end] = chunk;
  1040. this.byStart[chunk.next.start] = chunk.next;
  1041. this.byEnd[chunk.next.end] = chunk.next;
  1042. }
  1043. if (aborted) return true;
  1044. chunk = chunk.previous;
  1045. } while (chunk);
  1046. return false;
  1047. }
  1048. trimEnd(charType) {
  1049. this.trimEndAborted(charType);
  1050. return this;
  1051. }
  1052. trimStartAborted(charType) {
  1053. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1054. this.intro = this.intro.replace(rx, '');
  1055. if (this.intro.length) return true;
  1056. let chunk = this.firstChunk;
  1057. do {
  1058. const end = chunk.end;
  1059. const aborted = chunk.trimStart(rx);
  1060. if (chunk.end !== end) {
  1061. // special case...
  1062. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  1063. this.byEnd[chunk.end] = chunk;
  1064. this.byStart[chunk.next.start] = chunk.next;
  1065. this.byEnd[chunk.next.end] = chunk.next;
  1066. }
  1067. if (aborted) return true;
  1068. chunk = chunk.next;
  1069. } while (chunk);
  1070. return false;
  1071. }
  1072. trimStart(charType) {
  1073. this.trimStartAborted(charType);
  1074. return this;
  1075. }
  1076. hasChanged() {
  1077. return this.original !== this.toString();
  1078. }
  1079. _replaceRegexp(searchValue, replacement) {
  1080. function getReplacement(match, str) {
  1081. if (typeof replacement === 'string') {
  1082. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  1083. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  1084. if (i === '$') return '$';
  1085. if (i === '&') return match[0];
  1086. const num = +i;
  1087. if (num < match.length) return match[+i];
  1088. return `$${i}`;
  1089. });
  1090. } else {
  1091. return replacement(...match, match.index, str, match.groups);
  1092. }
  1093. }
  1094. function matchAll(re, str) {
  1095. let match;
  1096. const matches = [];
  1097. while ((match = re.exec(str))) {
  1098. matches.push(match);
  1099. }
  1100. return matches;
  1101. }
  1102. if (searchValue.global) {
  1103. const matches = matchAll(searchValue, this.original);
  1104. matches.forEach((match) => {
  1105. if (match.index != null) {
  1106. const replacement = getReplacement(match, this.original);
  1107. if (replacement !== match[0]) {
  1108. this.overwrite(
  1109. match.index,
  1110. match.index + match[0].length,
  1111. replacement
  1112. );
  1113. }
  1114. }
  1115. });
  1116. } else {
  1117. const match = this.original.match(searchValue);
  1118. if (match && match.index != null) {
  1119. const replacement = getReplacement(match, this.original);
  1120. if (replacement !== match[0]) {
  1121. this.overwrite(
  1122. match.index,
  1123. match.index + match[0].length,
  1124. replacement
  1125. );
  1126. }
  1127. }
  1128. }
  1129. return this;
  1130. }
  1131. _replaceString(string, replacement) {
  1132. const { original } = this;
  1133. const index = original.indexOf(string);
  1134. if (index !== -1) {
  1135. this.overwrite(index, index + string.length, replacement);
  1136. }
  1137. return this;
  1138. }
  1139. replace(searchValue, replacement) {
  1140. if (typeof searchValue === 'string') {
  1141. return this._replaceString(searchValue, replacement);
  1142. }
  1143. return this._replaceRegexp(searchValue, replacement);
  1144. }
  1145. _replaceAllString(string, replacement) {
  1146. const { original } = this;
  1147. const stringLength = string.length;
  1148. for (
  1149. let index = original.indexOf(string);
  1150. index !== -1;
  1151. index = original.indexOf(string, index + stringLength)
  1152. ) {
  1153. const previous = original.slice(index, index + stringLength);
  1154. if (previous !== replacement)
  1155. this.overwrite(index, index + stringLength, replacement);
  1156. }
  1157. return this;
  1158. }
  1159. replaceAll(searchValue, replacement) {
  1160. if (typeof searchValue === 'string') {
  1161. return this._replaceAllString(searchValue, replacement);
  1162. }
  1163. if (!searchValue.global) {
  1164. throw new TypeError(
  1165. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  1166. );
  1167. }
  1168. return this._replaceRegexp(searchValue, replacement);
  1169. }
  1170. }
  1171. const hasOwnProp = Object.prototype.hasOwnProperty;
  1172. let Bundle$1 = class Bundle {
  1173. constructor(options = {}) {
  1174. this.intro = options.intro || '';
  1175. this.separator = options.separator !== undefined ? options.separator : '\n';
  1176. this.sources = [];
  1177. this.uniqueSources = [];
  1178. this.uniqueSourceIndexByFilename = {};
  1179. }
  1180. addSource(source) {
  1181. if (source instanceof MagicString) {
  1182. return this.addSource({
  1183. content: source,
  1184. filename: source.filename,
  1185. separator: this.separator,
  1186. });
  1187. }
  1188. if (!isObject$1(source) || !source.content) {
  1189. throw new Error(
  1190. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  1191. );
  1192. }
  1193. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1194. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1195. });
  1196. if (source.separator === undefined) {
  1197. // TODO there's a bunch of this sort of thing, needs cleaning up
  1198. source.separator = this.separator;
  1199. }
  1200. if (source.filename) {
  1201. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1202. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1203. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1204. } else {
  1205. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1206. if (source.content.original !== uniqueSource.content) {
  1207. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1208. }
  1209. }
  1210. }
  1211. this.sources.push(source);
  1212. return this;
  1213. }
  1214. append(str, options) {
  1215. this.addSource({
  1216. content: new MagicString(str),
  1217. separator: (options && options.separator) || '',
  1218. });
  1219. return this;
  1220. }
  1221. clone() {
  1222. const bundle = new Bundle({
  1223. intro: this.intro,
  1224. separator: this.separator,
  1225. });
  1226. this.sources.forEach((source) => {
  1227. bundle.addSource({
  1228. filename: source.filename,
  1229. content: source.content.clone(),
  1230. separator: source.separator,
  1231. });
  1232. });
  1233. return bundle;
  1234. }
  1235. generateDecodedMap(options = {}) {
  1236. const names = [];
  1237. let x_google_ignoreList = undefined;
  1238. this.sources.forEach((source) => {
  1239. Object.keys(source.content.storedNames).forEach((name) => {
  1240. if (!~names.indexOf(name)) names.push(name);
  1241. });
  1242. });
  1243. const mappings = new Mappings(options.hires);
  1244. if (this.intro) {
  1245. mappings.advance(this.intro);
  1246. }
  1247. this.sources.forEach((source, i) => {
  1248. if (i > 0) {
  1249. mappings.advance(this.separator);
  1250. }
  1251. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1252. const magicString = source.content;
  1253. const locate = getLocator(magicString.original);
  1254. if (magicString.intro) {
  1255. mappings.advance(magicString.intro);
  1256. }
  1257. magicString.firstChunk.eachNext((chunk) => {
  1258. const loc = locate(chunk.start);
  1259. if (chunk.intro.length) mappings.advance(chunk.intro);
  1260. if (source.filename) {
  1261. if (chunk.edited) {
  1262. mappings.addEdit(
  1263. sourceIndex,
  1264. chunk.content,
  1265. loc,
  1266. chunk.storeName ? names.indexOf(chunk.original) : -1,
  1267. );
  1268. } else {
  1269. mappings.addUneditedChunk(
  1270. sourceIndex,
  1271. chunk,
  1272. magicString.original,
  1273. loc,
  1274. magicString.sourcemapLocations,
  1275. );
  1276. }
  1277. } else {
  1278. mappings.advance(chunk.content);
  1279. }
  1280. if (chunk.outro.length) mappings.advance(chunk.outro);
  1281. });
  1282. if (magicString.outro) {
  1283. mappings.advance(magicString.outro);
  1284. }
  1285. if (source.ignoreList && sourceIndex !== -1) {
  1286. if (x_google_ignoreList === undefined) {
  1287. x_google_ignoreList = [];
  1288. }
  1289. x_google_ignoreList.push(sourceIndex);
  1290. }
  1291. });
  1292. return {
  1293. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  1294. sources: this.uniqueSources.map((source) => {
  1295. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1296. }),
  1297. sourcesContent: this.uniqueSources.map((source) => {
  1298. return options.includeContent ? source.content : null;
  1299. }),
  1300. names,
  1301. mappings: mappings.raw,
  1302. x_google_ignoreList,
  1303. };
  1304. }
  1305. generateMap(options) {
  1306. return new SourceMap(this.generateDecodedMap(options));
  1307. }
  1308. getIndentString() {
  1309. const indentStringCounts = {};
  1310. this.sources.forEach((source) => {
  1311. const indentStr = source.content._getRawIndentString();
  1312. if (indentStr === null) return;
  1313. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1314. indentStringCounts[indentStr] += 1;
  1315. });
  1316. return (
  1317. Object.keys(indentStringCounts).sort((a, b) => {
  1318. return indentStringCounts[a] - indentStringCounts[b];
  1319. })[0] || '\t'
  1320. );
  1321. }
  1322. indent(indentStr) {
  1323. if (!arguments.length) {
  1324. indentStr = this.getIndentString();
  1325. }
  1326. if (indentStr === '') return this; // noop
  1327. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1328. this.sources.forEach((source, i) => {
  1329. const separator = source.separator !== undefined ? source.separator : this.separator;
  1330. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1331. source.content.indent(indentStr, {
  1332. exclude: source.indentExclusionRanges,
  1333. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1334. });
  1335. trailingNewline = source.content.lastChar() === '\n';
  1336. });
  1337. if (this.intro) {
  1338. this.intro =
  1339. indentStr +
  1340. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1341. return index > 0 ? indentStr + match : match;
  1342. });
  1343. }
  1344. return this;
  1345. }
  1346. prepend(str) {
  1347. this.intro = str + this.intro;
  1348. return this;
  1349. }
  1350. toString() {
  1351. const body = this.sources
  1352. .map((source, i) => {
  1353. const separator = source.separator !== undefined ? source.separator : this.separator;
  1354. const str = (i > 0 ? separator : '') + source.content.toString();
  1355. return str;
  1356. })
  1357. .join('');
  1358. return this.intro + body;
  1359. }
  1360. isEmpty() {
  1361. if (this.intro.length && this.intro.trim()) return false;
  1362. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1363. return true;
  1364. }
  1365. length() {
  1366. return this.sources.reduce(
  1367. (length, source) => length + source.content.length(),
  1368. this.intro.length,
  1369. );
  1370. }
  1371. trimLines() {
  1372. return this.trim('[\\r\\n]');
  1373. }
  1374. trim(charType) {
  1375. return this.trimStart(charType).trimEnd(charType);
  1376. }
  1377. trimStart(charType) {
  1378. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1379. this.intro = this.intro.replace(rx, '');
  1380. if (!this.intro) {
  1381. let source;
  1382. let i = 0;
  1383. do {
  1384. source = this.sources[i++];
  1385. if (!source) {
  1386. break;
  1387. }
  1388. } while (!source.content.trimStartAborted(charType));
  1389. }
  1390. return this;
  1391. }
  1392. trimEnd(charType) {
  1393. const rx = new RegExp((charType || '\\s') + '+$');
  1394. let source;
  1395. let i = this.sources.length - 1;
  1396. do {
  1397. source = this.sources[i--];
  1398. if (!source) {
  1399. this.intro = this.intro.replace(rx, '');
  1400. break;
  1401. }
  1402. } while (!source.content.trimEndAborted(charType));
  1403. return this;
  1404. }
  1405. };
  1406. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  1407. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  1408. const backSlashRegEx = /\\/g;
  1409. function escapeId(id) {
  1410. if (!needsEscapeRegEx.test(id))
  1411. return id;
  1412. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  1413. }
  1414. class ExternalChunk {
  1415. constructor(module, options, inputBase) {
  1416. this.options = options;
  1417. this.inputBase = inputBase;
  1418. this.defaultVariableName = '';
  1419. this.namespaceVariableName = '';
  1420. this.variableName = '';
  1421. this.fileName = null;
  1422. this.importAttributes = null;
  1423. this.id = module.id;
  1424. this.moduleInfo = module.info;
  1425. this.renormalizeRenderPath = module.renormalizeRenderPath;
  1426. this.suggestedVariableName = module.suggestedVariableName;
  1427. }
  1428. getFileName() {
  1429. if (this.fileName) {
  1430. return this.fileName;
  1431. }
  1432. const { paths } = this.options;
  1433. return (this.fileName =
  1434. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  1435. (this.renormalizeRenderPath ? normalize(relative(this.inputBase, this.id)) : this.id));
  1436. }
  1437. getImportAttributes(snippets) {
  1438. return (this.importAttributes ||= formatAttributes(this.options.format === 'es' &&
  1439. this.options.externalImportAttributes &&
  1440. this.moduleInfo.attributes, snippets));
  1441. }
  1442. getImportPath(importer) {
  1443. return escapeId(this.renormalizeRenderPath
  1444. ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  1445. : this.getFileName());
  1446. }
  1447. }
  1448. function formatAttributes(attributes, { getObject }) {
  1449. if (!attributes) {
  1450. return null;
  1451. }
  1452. const assertionEntries = Object.entries(attributes).map(([key, value]) => [key, `'${value}'`]);
  1453. if (assertionEntries.length > 0) {
  1454. return getObject(assertionEntries, { lineBreakIndent: null });
  1455. }
  1456. return null;
  1457. }
  1458. function getOrCreate(map, key, init) {
  1459. const existing = map.get(key);
  1460. if (existing !== undefined) {
  1461. return existing;
  1462. }
  1463. const value = init();
  1464. map.set(key, value);
  1465. return value;
  1466. }
  1467. function getNewSet() {
  1468. return new Set();
  1469. }
  1470. function getNewArray() {
  1471. return [];
  1472. }
  1473. const UnknownKey = Symbol('Unknown Key');
  1474. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  1475. const UnknownInteger = Symbol('Unknown Integer');
  1476. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  1477. const EMPTY_PATH = [];
  1478. const UNKNOWN_PATH = [UnknownKey];
  1479. // For deoptimizations, this means we are modifying an unknown property but did
  1480. // not lose track of the object or are creating a setter/getter;
  1481. // For assignment effects it means we do not check for setter/getter effects
  1482. // but only if something is mutated that is included, which is relevant for
  1483. // Object.defineProperty
  1484. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1485. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1486. const EntitiesKey = Symbol('Entities');
  1487. class PathTracker {
  1488. constructor() {
  1489. this.entityPaths = Object.create(null, {
  1490. [EntitiesKey]: { value: new Set() }
  1491. });
  1492. }
  1493. trackEntityAtPathAndGetIfTracked(path, entity) {
  1494. const trackedEntities = this.getEntities(path);
  1495. if (trackedEntities.has(entity))
  1496. return true;
  1497. trackedEntities.add(entity);
  1498. return false;
  1499. }
  1500. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1501. const trackedEntities = this.getEntities(path);
  1502. if (trackedEntities.has(entity))
  1503. return returnIfTracked;
  1504. trackedEntities.add(entity);
  1505. const result = onUntracked();
  1506. trackedEntities.delete(entity);
  1507. return result;
  1508. }
  1509. getEntities(path) {
  1510. let currentPaths = this.entityPaths;
  1511. for (const pathSegment of path) {
  1512. currentPaths = currentPaths[pathSegment] =
  1513. currentPaths[pathSegment] ||
  1514. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1515. }
  1516. return currentPaths[EntitiesKey];
  1517. }
  1518. }
  1519. const SHARED_RECURSION_TRACKER = new PathTracker();
  1520. class DiscriminatedPathTracker {
  1521. constructor() {
  1522. this.entityPaths = Object.create(null, {
  1523. [EntitiesKey]: { value: new Map() }
  1524. });
  1525. }
  1526. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1527. let currentPaths = this.entityPaths;
  1528. for (const pathSegment of path) {
  1529. currentPaths = currentPaths[pathSegment] =
  1530. currentPaths[pathSegment] ||
  1531. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1532. }
  1533. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  1534. if (trackedEntities.has(entity))
  1535. return true;
  1536. trackedEntities.add(entity);
  1537. return false;
  1538. }
  1539. }
  1540. function isFlagSet(flags, flag) {
  1541. return (flags & flag) !== 0;
  1542. }
  1543. function setFlag(flags, flag, value) {
  1544. return (flags & ~flag) | (-value & flag);
  1545. }
  1546. const UnknownValue = Symbol('Unknown Value');
  1547. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1548. class ExpressionEntity {
  1549. constructor() {
  1550. this.flags = 0;
  1551. }
  1552. get included() {
  1553. return isFlagSet(this.flags, 1 /* Flag.included */);
  1554. }
  1555. set included(value) {
  1556. this.flags = setFlag(this.flags, 1 /* Flag.included */, value);
  1557. }
  1558. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  1559. deoptimizeInteraction(interaction);
  1560. }
  1561. deoptimizePath(_path) { }
  1562. /**
  1563. * If possible it returns a stringifyable literal value for this node that
  1564. * can be used for inlining or comparing values. Otherwise, it should return
  1565. * UnknownValue.
  1566. */
  1567. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1568. return UnknownValue;
  1569. }
  1570. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1571. return UNKNOWN_RETURN_EXPRESSION;
  1572. }
  1573. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1574. return true;
  1575. }
  1576. include(_context, _includeChildrenRecursively, _options) {
  1577. this.included = true;
  1578. }
  1579. includeCallArguments(context, parameters) {
  1580. for (const argument of parameters) {
  1581. argument.include(context, false);
  1582. }
  1583. }
  1584. shouldBeIncluded(_context) {
  1585. return true;
  1586. }
  1587. }
  1588. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1589. })();
  1590. const UNKNOWN_RETURN_EXPRESSION = [
  1591. UNKNOWN_EXPRESSION,
  1592. false
  1593. ];
  1594. const deoptimizeInteraction = (interaction) => {
  1595. for (const argument of interaction.args) {
  1596. argument?.deoptimizePath(UNKNOWN_PATH);
  1597. }
  1598. };
  1599. const INTERACTION_ACCESSED = 0;
  1600. const INTERACTION_ASSIGNED = 1;
  1601. const INTERACTION_CALLED = 2;
  1602. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1603. args: [null],
  1604. type: INTERACTION_ACCESSED
  1605. };
  1606. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  1607. args: [null, UNKNOWN_EXPRESSION],
  1608. type: INTERACTION_ASSIGNED
  1609. };
  1610. // While this is technically a call without arguments, we can compare against
  1611. // this reference in places where precise values or this argument would make a
  1612. // difference
  1613. const NODE_INTERACTION_UNKNOWN_CALL = {
  1614. args: [null],
  1615. type: INTERACTION_CALLED,
  1616. withNew: false
  1617. };
  1618. class Variable extends ExpressionEntity {
  1619. constructor(name) {
  1620. super();
  1621. this.name = name;
  1622. this.alwaysRendered = false;
  1623. this.forbiddenNames = null;
  1624. this.initReached = false;
  1625. this.isId = false;
  1626. this.isReassigned = false;
  1627. this.kind = null;
  1628. this.renderBaseName = null;
  1629. this.renderName = null;
  1630. }
  1631. /**
  1632. * Binds identifiers that reference this variable to this variable.
  1633. * Necessary to be able to change variable names.
  1634. */
  1635. addReference(_identifier) { }
  1636. /**
  1637. * Prevent this variable from being renamed to this name to avoid name
  1638. * collisions
  1639. */
  1640. forbidName(name) {
  1641. (this.forbiddenNames ||= new Set()).add(name);
  1642. }
  1643. getBaseVariableName() {
  1644. return (this.renderedLikeHoisted?.getBaseVariableName() ||
  1645. this.renderBaseName ||
  1646. this.renderName ||
  1647. this.name);
  1648. }
  1649. getName(getPropertyAccess, useOriginalName) {
  1650. if (useOriginalName?.(this)) {
  1651. return this.name;
  1652. }
  1653. if (this.renderedLikeHoisted) {
  1654. return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
  1655. }
  1656. const name = this.renderName || this.name;
  1657. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  1658. }
  1659. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  1660. return type !== INTERACTION_ACCESSED || path.length > 0;
  1661. }
  1662. /**
  1663. * Marks this variable as being part of the bundle, which is usually the case when one of
  1664. * its identifiers becomes part of the bundle. Returns true if it has not been included
  1665. * previously.
  1666. * Once a variable is included, it should take care all its declarations are included.
  1667. */
  1668. include() {
  1669. this.included = true;
  1670. this.renderedLikeHoisted?.include();
  1671. }
  1672. /**
  1673. * Links the rendered name of this variable to another variable and includes
  1674. * this variable if the other variable is included.
  1675. */
  1676. renderLikeHoisted(variable) {
  1677. this.renderedLikeHoisted = variable;
  1678. }
  1679. markCalledFromTryStatement() { }
  1680. setRenderNames(baseName, name) {
  1681. this.renderBaseName = baseName;
  1682. this.renderName = name;
  1683. }
  1684. }
  1685. class ExternalVariable extends Variable {
  1686. constructor(module, name) {
  1687. super(name);
  1688. this.referenced = false;
  1689. this.module = module;
  1690. this.isNamespace = name === '*';
  1691. }
  1692. addReference(identifier) {
  1693. this.referenced = true;
  1694. if (this.name === 'default' || this.name === '*') {
  1695. this.module.suggestName(identifier.name);
  1696. }
  1697. }
  1698. hasEffectsOnInteractionAtPath(path, { type }) {
  1699. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  1700. }
  1701. include() {
  1702. super.include();
  1703. this.module.used = true;
  1704. }
  1705. }
  1706. function cacheObjectGetters(object, getterProperties) {
  1707. for (const property of getterProperties) {
  1708. const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
  1709. Object.defineProperty(object, property, {
  1710. get() {
  1711. const value = propertyGetter.call(object);
  1712. // This replaces the getter with a fixed value for subsequent calls
  1713. Object.defineProperty(object, property, { value });
  1714. return value;
  1715. }
  1716. });
  1717. }
  1718. }
  1719. const RESERVED_NAMES = new Set([
  1720. 'await',
  1721. 'break',
  1722. 'case',
  1723. 'catch',
  1724. 'class',
  1725. 'const',
  1726. 'continue',
  1727. 'debugger',
  1728. 'default',
  1729. 'delete',
  1730. 'do',
  1731. 'else',
  1732. 'enum',
  1733. 'eval',
  1734. 'export',
  1735. 'extends',
  1736. 'false',
  1737. 'finally',
  1738. 'for',
  1739. 'function',
  1740. 'if',
  1741. 'implements',
  1742. 'import',
  1743. 'in',
  1744. 'instanceof',
  1745. 'interface',
  1746. 'let',
  1747. 'NaN',
  1748. 'new',
  1749. 'null',
  1750. 'package',
  1751. 'private',
  1752. 'protected',
  1753. 'public',
  1754. 'return',
  1755. 'static',
  1756. 'super',
  1757. 'switch',
  1758. 'this',
  1759. 'throw',
  1760. 'true',
  1761. 'try',
  1762. 'typeof',
  1763. 'undefined',
  1764. 'var',
  1765. 'void',
  1766. 'while',
  1767. 'with',
  1768. 'yield'
  1769. ]);
  1770. const illegalCharacters = /[^\w$]/g;
  1771. const startsWithDigit = (value) => /\d/.test(value[0]);
  1772. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES.has(value) || value === 'arguments';
  1773. function isLegal(value) {
  1774. if (needsEscape(value)) {
  1775. return false;
  1776. }
  1777. return !illegalCharacters.test(value);
  1778. }
  1779. function makeLegal(value) {
  1780. value = value
  1781. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  1782. .replace(illegalCharacters, '_');
  1783. if (needsEscape(value))
  1784. value = `_${value}`;
  1785. return value || '_';
  1786. }
  1787. const VALID_IDENTIFIER_REGEXP = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
  1788. const NUMBER_REGEXP = /^(?:0|[1-9]\d*)$/;
  1789. function stringifyObjectKeyIfNeeded(key) {
  1790. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  1791. return key === '__proto__' ? '["__proto__"]' : key;
  1792. }
  1793. if (NUMBER_REGEXP.test(key) && +key <= Number.MAX_SAFE_INTEGER) {
  1794. return key;
  1795. }
  1796. return JSON.stringify(key);
  1797. }
  1798. function stringifyIdentifierIfNeeded(key) {
  1799. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  1800. return key;
  1801. }
  1802. return JSON.stringify(key);
  1803. }
  1804. class ExternalModule {
  1805. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
  1806. this.options = options;
  1807. this.id = id;
  1808. this.renormalizeRenderPath = renormalizeRenderPath;
  1809. this.dynamicImporters = [];
  1810. this.execIndex = Infinity;
  1811. this.exportedVariables = new Map();
  1812. this.importers = [];
  1813. this.reexported = false;
  1814. this.used = false;
  1815. this.declarations = new Map();
  1816. this.mostCommonSuggestion = 0;
  1817. this.nameSuggestions = new Map();
  1818. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  1819. const { importers, dynamicImporters } = this;
  1820. this.info = {
  1821. ast: null,
  1822. attributes,
  1823. code: null,
  1824. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  1825. dynamicallyImportedIds: EMPTY_ARRAY,
  1826. get dynamicImporters() {
  1827. return dynamicImporters.sort();
  1828. },
  1829. exportedBindings: null,
  1830. exports: null,
  1831. hasDefaultExport: null,
  1832. id,
  1833. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  1834. implicitlyLoadedBefore: EMPTY_ARRAY,
  1835. importedIdResolutions: EMPTY_ARRAY,
  1836. importedIds: EMPTY_ARRAY,
  1837. get importers() {
  1838. return importers.sort();
  1839. },
  1840. isEntry: false,
  1841. isExternal: true,
  1842. isIncluded: null,
  1843. meta,
  1844. moduleSideEffects,
  1845. syntheticNamedExports: false
  1846. };
  1847. }
  1848. cacheInfoGetters() {
  1849. cacheObjectGetters(this.info, ['dynamicImporters', 'importers']);
  1850. }
  1851. getVariableForExportName(name) {
  1852. const declaration = this.declarations.get(name);
  1853. if (declaration)
  1854. return [declaration];
  1855. const externalVariable = new ExternalVariable(this, name);
  1856. this.declarations.set(name, externalVariable);
  1857. this.exportedVariables.set(externalVariable, name);
  1858. return [externalVariable];
  1859. }
  1860. suggestName(name) {
  1861. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  1862. this.nameSuggestions.set(name, value);
  1863. if (value > this.mostCommonSuggestion) {
  1864. this.mostCommonSuggestion = value;
  1865. this.suggestedVariableName = name;
  1866. }
  1867. }
  1868. warnUnusedImports() {
  1869. const unused = [...this.declarations]
  1870. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  1871. .map(([name]) => name);
  1872. if (unused.length === 0)
  1873. return;
  1874. const importersSet = new Set();
  1875. for (const name of unused) {
  1876. for (const importer of this.declarations.get(name).module.importers) {
  1877. importersSet.add(importer);
  1878. }
  1879. }
  1880. const importersArray = [...importersSet];
  1881. this.options.onLog(LOGLEVEL_WARN, logUnusedExternalImports(this.id, unused, importersArray));
  1882. }
  1883. }
  1884. function getDefaultExportFromCjs (x) {
  1885. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  1886. }
  1887. function getAugmentedNamespace(n) {
  1888. if (n.__esModule) return n;
  1889. var f = n.default;
  1890. if (typeof f == "function") {
  1891. var a = function a () {
  1892. if (this instanceof a) {
  1893. return Reflect.construct(f, arguments, this.constructor);
  1894. }
  1895. return f.apply(this, arguments);
  1896. };
  1897. a.prototype = f.prototype;
  1898. } else a = {};
  1899. Object.defineProperty(a, '__esModule', {value: true});
  1900. Object.keys(n).forEach(function (k) {
  1901. var d = Object.getOwnPropertyDescriptor(n, k);
  1902. Object.defineProperty(a, k, d.get ? d : {
  1903. enumerable: true,
  1904. get: function () {
  1905. return n[k];
  1906. }
  1907. });
  1908. });
  1909. return a;
  1910. }
  1911. var utils$3 = {};
  1912. const path$1 = require$$0$1;
  1913. const WIN_SLASH = '\\\\/';
  1914. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  1915. /**
  1916. * Posix glob regex
  1917. */
  1918. const DOT_LITERAL = '\\.';
  1919. const PLUS_LITERAL = '\\+';
  1920. const QMARK_LITERAL = '\\?';
  1921. const SLASH_LITERAL = '\\/';
  1922. const ONE_CHAR = '(?=.)';
  1923. const QMARK = '[^/]';
  1924. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  1925. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  1926. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  1927. const NO_DOT = `(?!${DOT_LITERAL})`;
  1928. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  1929. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  1930. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  1931. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  1932. const STAR = `${QMARK}*?`;
  1933. const POSIX_CHARS = {
  1934. DOT_LITERAL,
  1935. PLUS_LITERAL,
  1936. QMARK_LITERAL,
  1937. SLASH_LITERAL,
  1938. ONE_CHAR,
  1939. QMARK,
  1940. END_ANCHOR,
  1941. DOTS_SLASH,
  1942. NO_DOT,
  1943. NO_DOTS,
  1944. NO_DOT_SLASH,
  1945. NO_DOTS_SLASH,
  1946. QMARK_NO_DOT,
  1947. STAR,
  1948. START_ANCHOR
  1949. };
  1950. /**
  1951. * Windows glob regex
  1952. */
  1953. const WINDOWS_CHARS = {
  1954. ...POSIX_CHARS,
  1955. SLASH_LITERAL: `[${WIN_SLASH}]`,
  1956. QMARK: WIN_NO_SLASH,
  1957. STAR: `${WIN_NO_SLASH}*?`,
  1958. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  1959. NO_DOT: `(?!${DOT_LITERAL})`,
  1960. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1961. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  1962. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1963. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  1964. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  1965. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  1966. };
  1967. /**
  1968. * POSIX Bracket Regex
  1969. */
  1970. const POSIX_REGEX_SOURCE$1 = {
  1971. alnum: 'a-zA-Z0-9',
  1972. alpha: 'a-zA-Z',
  1973. ascii: '\\x00-\\x7F',
  1974. blank: ' \\t',
  1975. cntrl: '\\x00-\\x1F\\x7F',
  1976. digit: '0-9',
  1977. graph: '\\x21-\\x7E',
  1978. lower: 'a-z',
  1979. print: '\\x20-\\x7E ',
  1980. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  1981. space: ' \\t\\r\\n\\v\\f',
  1982. upper: 'A-Z',
  1983. word: 'A-Za-z0-9_',
  1984. xdigit: 'A-Fa-f0-9'
  1985. };
  1986. var constants$2 = {
  1987. MAX_LENGTH: 1024 * 64,
  1988. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  1989. // regular expressions
  1990. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  1991. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  1992. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  1993. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  1994. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  1995. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  1996. // Replace globs with equivalent patterns to reduce parsing time.
  1997. REPLACEMENTS: {
  1998. '***': '*',
  1999. '**/**': '**',
  2000. '**/**/**': '**'
  2001. },
  2002. // Digits
  2003. CHAR_0: 48, /* 0 */
  2004. CHAR_9: 57, /* 9 */
  2005. // Alphabet chars.
  2006. CHAR_UPPERCASE_A: 65, /* A */
  2007. CHAR_LOWERCASE_A: 97, /* a */
  2008. CHAR_UPPERCASE_Z: 90, /* Z */
  2009. CHAR_LOWERCASE_Z: 122, /* z */
  2010. CHAR_LEFT_PARENTHESES: 40, /* ( */
  2011. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  2012. CHAR_ASTERISK: 42, /* * */
  2013. // Non-alphabetic chars.
  2014. CHAR_AMPERSAND: 38, /* & */
  2015. CHAR_AT: 64, /* @ */
  2016. CHAR_BACKWARD_SLASH: 92, /* \ */
  2017. CHAR_CARRIAGE_RETURN: 13, /* \r */
  2018. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  2019. CHAR_COLON: 58, /* : */
  2020. CHAR_COMMA: 44, /* , */
  2021. CHAR_DOT: 46, /* . */
  2022. CHAR_DOUBLE_QUOTE: 34, /* " */
  2023. CHAR_EQUAL: 61, /* = */
  2024. CHAR_EXCLAMATION_MARK: 33, /* ! */
  2025. CHAR_FORM_FEED: 12, /* \f */
  2026. CHAR_FORWARD_SLASH: 47, /* / */
  2027. CHAR_GRAVE_ACCENT: 96, /* ` */
  2028. CHAR_HASH: 35, /* # */
  2029. CHAR_HYPHEN_MINUS: 45, /* - */
  2030. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  2031. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  2032. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  2033. CHAR_LINE_FEED: 10, /* \n */
  2034. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  2035. CHAR_PERCENT: 37, /* % */
  2036. CHAR_PLUS: 43, /* + */
  2037. CHAR_QUESTION_MARK: 63, /* ? */
  2038. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  2039. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  2040. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  2041. CHAR_SEMICOLON: 59, /* ; */
  2042. CHAR_SINGLE_QUOTE: 39, /* ' */
  2043. CHAR_SPACE: 32, /* */
  2044. CHAR_TAB: 9, /* \t */
  2045. CHAR_UNDERSCORE: 95, /* _ */
  2046. CHAR_VERTICAL_LINE: 124, /* | */
  2047. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  2048. SEP: path$1.sep,
  2049. /**
  2050. * Create EXTGLOB_CHARS
  2051. */
  2052. extglobChars(chars) {
  2053. return {
  2054. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  2055. '?': { type: 'qmark', open: '(?:', close: ')?' },
  2056. '+': { type: 'plus', open: '(?:', close: ')+' },
  2057. '*': { type: 'star', open: '(?:', close: ')*' },
  2058. '@': { type: 'at', open: '(?:', close: ')' }
  2059. };
  2060. },
  2061. /**
  2062. * Create GLOB_CHARS
  2063. */
  2064. globChars(win32) {
  2065. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  2066. }
  2067. };
  2068. (function (exports) {
  2069. const path = require$$0$1;
  2070. const win32 = process.platform === 'win32';
  2071. const {
  2072. REGEX_BACKSLASH,
  2073. REGEX_REMOVE_BACKSLASH,
  2074. REGEX_SPECIAL_CHARS,
  2075. REGEX_SPECIAL_CHARS_GLOBAL
  2076. } = constants$2;
  2077. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  2078. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  2079. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  2080. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  2081. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  2082. exports.removeBackslashes = str => {
  2083. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  2084. return match === '\\' ? '' : match;
  2085. });
  2086. };
  2087. exports.supportsLookbehinds = () => {
  2088. const segs = process.version.slice(1).split('.').map(Number);
  2089. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  2090. return true;
  2091. }
  2092. return false;
  2093. };
  2094. exports.isWindows = options => {
  2095. if (options && typeof options.windows === 'boolean') {
  2096. return options.windows;
  2097. }
  2098. return win32 === true || path.sep === '\\';
  2099. };
  2100. exports.escapeLast = (input, char, lastIdx) => {
  2101. const idx = input.lastIndexOf(char, lastIdx);
  2102. if (idx === -1) return input;
  2103. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  2104. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  2105. };
  2106. exports.removePrefix = (input, state = {}) => {
  2107. let output = input;
  2108. if (output.startsWith('./')) {
  2109. output = output.slice(2);
  2110. state.prefix = './';
  2111. }
  2112. return output;
  2113. };
  2114. exports.wrapOutput = (input, state = {}, options = {}) => {
  2115. const prepend = options.contains ? '' : '^';
  2116. const append = options.contains ? '' : '$';
  2117. let output = `${prepend}(?:${input})${append}`;
  2118. if (state.negated === true) {
  2119. output = `(?:^(?!${output}).*$)`;
  2120. }
  2121. return output;
  2122. };
  2123. } (utils$3));
  2124. const utils$2 = utils$3;
  2125. const {
  2126. CHAR_ASTERISK, /* * */
  2127. CHAR_AT, /* @ */
  2128. CHAR_BACKWARD_SLASH, /* \ */
  2129. CHAR_COMMA, /* , */
  2130. CHAR_DOT, /* . */
  2131. CHAR_EXCLAMATION_MARK, /* ! */
  2132. CHAR_FORWARD_SLASH, /* / */
  2133. CHAR_LEFT_CURLY_BRACE, /* { */
  2134. CHAR_LEFT_PARENTHESES, /* ( */
  2135. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  2136. CHAR_PLUS, /* + */
  2137. CHAR_QUESTION_MARK, /* ? */
  2138. CHAR_RIGHT_CURLY_BRACE, /* } */
  2139. CHAR_RIGHT_PARENTHESES, /* ) */
  2140. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  2141. } = constants$2;
  2142. const isPathSeparator = code => {
  2143. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  2144. };
  2145. const depth = token => {
  2146. if (token.isPrefix !== true) {
  2147. token.depth = token.isGlobstar ? Infinity : 1;
  2148. }
  2149. };
  2150. /**
  2151. * Quickly scans a glob pattern and returns an object with a handful of
  2152. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  2153. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  2154. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  2155. *
  2156. * ```js
  2157. * const pm = require('picomatch');
  2158. * console.log(pm.scan('foo/bar/*.js'));
  2159. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  2160. * ```
  2161. * @param {String} `str`
  2162. * @param {Object} `options`
  2163. * @return {Object} Returns an object with tokens and regex source string.
  2164. * @api public
  2165. */
  2166. const scan$1 = (input, options) => {
  2167. const opts = options || {};
  2168. const length = input.length - 1;
  2169. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  2170. const slashes = [];
  2171. const tokens = [];
  2172. const parts = [];
  2173. let str = input;
  2174. let index = -1;
  2175. let start = 0;
  2176. let lastIndex = 0;
  2177. let isBrace = false;
  2178. let isBracket = false;
  2179. let isGlob = false;
  2180. let isExtglob = false;
  2181. let isGlobstar = false;
  2182. let braceEscaped = false;
  2183. let backslashes = false;
  2184. let negated = false;
  2185. let negatedExtglob = false;
  2186. let finished = false;
  2187. let braces = 0;
  2188. let prev;
  2189. let code;
  2190. let token = { value: '', depth: 0, isGlob: false };
  2191. const eos = () => index >= length;
  2192. const peek = () => str.charCodeAt(index + 1);
  2193. const advance = () => {
  2194. prev = code;
  2195. return str.charCodeAt(++index);
  2196. };
  2197. while (index < length) {
  2198. code = advance();
  2199. let next;
  2200. if (code === CHAR_BACKWARD_SLASH) {
  2201. backslashes = token.backslashes = true;
  2202. code = advance();
  2203. if (code === CHAR_LEFT_CURLY_BRACE) {
  2204. braceEscaped = true;
  2205. }
  2206. continue;
  2207. }
  2208. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  2209. braces++;
  2210. while (eos() !== true && (code = advance())) {
  2211. if (code === CHAR_BACKWARD_SLASH) {
  2212. backslashes = token.backslashes = true;
  2213. advance();
  2214. continue;
  2215. }
  2216. if (code === CHAR_LEFT_CURLY_BRACE) {
  2217. braces++;
  2218. continue;
  2219. }
  2220. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  2221. isBrace = token.isBrace = true;
  2222. isGlob = token.isGlob = true;
  2223. finished = true;
  2224. if (scanToEnd === true) {
  2225. continue;
  2226. }
  2227. break;
  2228. }
  2229. if (braceEscaped !== true && code === CHAR_COMMA) {
  2230. isBrace = token.isBrace = true;
  2231. isGlob = token.isGlob = true;
  2232. finished = true;
  2233. if (scanToEnd === true) {
  2234. continue;
  2235. }
  2236. break;
  2237. }
  2238. if (code === CHAR_RIGHT_CURLY_BRACE) {
  2239. braces--;
  2240. if (braces === 0) {
  2241. braceEscaped = false;
  2242. isBrace = token.isBrace = true;
  2243. finished = true;
  2244. break;
  2245. }
  2246. }
  2247. }
  2248. if (scanToEnd === true) {
  2249. continue;
  2250. }
  2251. break;
  2252. }
  2253. if (code === CHAR_FORWARD_SLASH) {
  2254. slashes.push(index);
  2255. tokens.push(token);
  2256. token = { value: '', depth: 0, isGlob: false };
  2257. if (finished === true) continue;
  2258. if (prev === CHAR_DOT && index === (start + 1)) {
  2259. start += 2;
  2260. continue;
  2261. }
  2262. lastIndex = index + 1;
  2263. continue;
  2264. }
  2265. if (opts.noext !== true) {
  2266. const isExtglobChar = code === CHAR_PLUS
  2267. || code === CHAR_AT
  2268. || code === CHAR_ASTERISK
  2269. || code === CHAR_QUESTION_MARK
  2270. || code === CHAR_EXCLAMATION_MARK;
  2271. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  2272. isGlob = token.isGlob = true;
  2273. isExtglob = token.isExtglob = true;
  2274. finished = true;
  2275. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  2276. negatedExtglob = true;
  2277. }
  2278. if (scanToEnd === true) {
  2279. while (eos() !== true && (code = advance())) {
  2280. if (code === CHAR_BACKWARD_SLASH) {
  2281. backslashes = token.backslashes = true;
  2282. code = advance();
  2283. continue;
  2284. }
  2285. if (code === CHAR_RIGHT_PARENTHESES) {
  2286. isGlob = token.isGlob = true;
  2287. finished = true;
  2288. break;
  2289. }
  2290. }
  2291. continue;
  2292. }
  2293. break;
  2294. }
  2295. }
  2296. if (code === CHAR_ASTERISK) {
  2297. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  2298. isGlob = token.isGlob = true;
  2299. finished = true;
  2300. if (scanToEnd === true) {
  2301. continue;
  2302. }
  2303. break;
  2304. }
  2305. if (code === CHAR_QUESTION_MARK) {
  2306. isGlob = token.isGlob = true;
  2307. finished = true;
  2308. if (scanToEnd === true) {
  2309. continue;
  2310. }
  2311. break;
  2312. }
  2313. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  2314. while (eos() !== true && (next = advance())) {
  2315. if (next === CHAR_BACKWARD_SLASH) {
  2316. backslashes = token.backslashes = true;
  2317. advance();
  2318. continue;
  2319. }
  2320. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  2321. isBracket = token.isBracket = true;
  2322. isGlob = token.isGlob = true;
  2323. finished = true;
  2324. break;
  2325. }
  2326. }
  2327. if (scanToEnd === true) {
  2328. continue;
  2329. }
  2330. break;
  2331. }
  2332. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  2333. negated = token.negated = true;
  2334. start++;
  2335. continue;
  2336. }
  2337. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  2338. isGlob = token.isGlob = true;
  2339. if (scanToEnd === true) {
  2340. while (eos() !== true && (code = advance())) {
  2341. if (code === CHAR_LEFT_PARENTHESES) {
  2342. backslashes = token.backslashes = true;
  2343. code = advance();
  2344. continue;
  2345. }
  2346. if (code === CHAR_RIGHT_PARENTHESES) {
  2347. finished = true;
  2348. break;
  2349. }
  2350. }
  2351. continue;
  2352. }
  2353. break;
  2354. }
  2355. if (isGlob === true) {
  2356. finished = true;
  2357. if (scanToEnd === true) {
  2358. continue;
  2359. }
  2360. break;
  2361. }
  2362. }
  2363. if (opts.noext === true) {
  2364. isExtglob = false;
  2365. isGlob = false;
  2366. }
  2367. let base = str;
  2368. let prefix = '';
  2369. let glob = '';
  2370. if (start > 0) {
  2371. prefix = str.slice(0, start);
  2372. str = str.slice(start);
  2373. lastIndex -= start;
  2374. }
  2375. if (base && isGlob === true && lastIndex > 0) {
  2376. base = str.slice(0, lastIndex);
  2377. glob = str.slice(lastIndex);
  2378. } else if (isGlob === true) {
  2379. base = '';
  2380. glob = str;
  2381. } else {
  2382. base = str;
  2383. }
  2384. if (base && base !== '' && base !== '/' && base !== str) {
  2385. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  2386. base = base.slice(0, -1);
  2387. }
  2388. }
  2389. if (opts.unescape === true) {
  2390. if (glob) glob = utils$2.removeBackslashes(glob);
  2391. if (base && backslashes === true) {
  2392. base = utils$2.removeBackslashes(base);
  2393. }
  2394. }
  2395. const state = {
  2396. prefix,
  2397. input,
  2398. start,
  2399. base,
  2400. glob,
  2401. isBrace,
  2402. isBracket,
  2403. isGlob,
  2404. isExtglob,
  2405. isGlobstar,
  2406. negated,
  2407. negatedExtglob
  2408. };
  2409. if (opts.tokens === true) {
  2410. state.maxDepth = 0;
  2411. if (!isPathSeparator(code)) {
  2412. tokens.push(token);
  2413. }
  2414. state.tokens = tokens;
  2415. }
  2416. if (opts.parts === true || opts.tokens === true) {
  2417. let prevIndex;
  2418. for (let idx = 0; idx < slashes.length; idx++) {
  2419. const n = prevIndex ? prevIndex + 1 : start;
  2420. const i = slashes[idx];
  2421. const value = input.slice(n, i);
  2422. if (opts.tokens) {
  2423. if (idx === 0 && start !== 0) {
  2424. tokens[idx].isPrefix = true;
  2425. tokens[idx].value = prefix;
  2426. } else {
  2427. tokens[idx].value = value;
  2428. }
  2429. depth(tokens[idx]);
  2430. state.maxDepth += tokens[idx].depth;
  2431. }
  2432. if (idx !== 0 || value !== '') {
  2433. parts.push(value);
  2434. }
  2435. prevIndex = i;
  2436. }
  2437. if (prevIndex && prevIndex + 1 < input.length) {
  2438. const value = input.slice(prevIndex + 1);
  2439. parts.push(value);
  2440. if (opts.tokens) {
  2441. tokens[tokens.length - 1].value = value;
  2442. depth(tokens[tokens.length - 1]);
  2443. state.maxDepth += tokens[tokens.length - 1].depth;
  2444. }
  2445. }
  2446. state.slashes = slashes;
  2447. state.parts = parts;
  2448. }
  2449. return state;
  2450. };
  2451. var scan_1 = scan$1;
  2452. const constants$1 = constants$2;
  2453. const utils$1 = utils$3;
  2454. /**
  2455. * Constants
  2456. */
  2457. const {
  2458. MAX_LENGTH,
  2459. POSIX_REGEX_SOURCE,
  2460. REGEX_NON_SPECIAL_CHARS,
  2461. REGEX_SPECIAL_CHARS_BACKREF,
  2462. REPLACEMENTS
  2463. } = constants$1;
  2464. /**
  2465. * Helpers
  2466. */
  2467. const expandRange = (args, options) => {
  2468. if (typeof options.expandRange === 'function') {
  2469. return options.expandRange(...args, options);
  2470. }
  2471. args.sort();
  2472. const value = `[${args.join('-')}]`;
  2473. return value;
  2474. };
  2475. /**
  2476. * Create the message for a syntax error
  2477. */
  2478. const syntaxError = (type, char) => {
  2479. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  2480. };
  2481. /**
  2482. * Parse the given input string.
  2483. * @param {String} input
  2484. * @param {Object} options
  2485. * @return {Object}
  2486. */
  2487. const parse$1 = (input, options) => {
  2488. if (typeof input !== 'string') {
  2489. throw new TypeError('Expected a string');
  2490. }
  2491. input = REPLACEMENTS[input] || input;
  2492. const opts = { ...options };
  2493. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2494. let len = input.length;
  2495. if (len > max) {
  2496. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2497. }
  2498. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  2499. const tokens = [bos];
  2500. const capture = opts.capture ? '' : '?:';
  2501. const win32 = utils$1.isWindows(options);
  2502. // create constants based on platform, for windows or posix
  2503. const PLATFORM_CHARS = constants$1.globChars(win32);
  2504. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  2505. const {
  2506. DOT_LITERAL,
  2507. PLUS_LITERAL,
  2508. SLASH_LITERAL,
  2509. ONE_CHAR,
  2510. DOTS_SLASH,
  2511. NO_DOT,
  2512. NO_DOT_SLASH,
  2513. NO_DOTS_SLASH,
  2514. QMARK,
  2515. QMARK_NO_DOT,
  2516. STAR,
  2517. START_ANCHOR
  2518. } = PLATFORM_CHARS;
  2519. const globstar = opts => {
  2520. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2521. };
  2522. const nodot = opts.dot ? '' : NO_DOT;
  2523. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  2524. let star = opts.bash === true ? globstar(opts) : STAR;
  2525. if (opts.capture) {
  2526. star = `(${star})`;
  2527. }
  2528. // minimatch options support
  2529. if (typeof opts.noext === 'boolean') {
  2530. opts.noextglob = opts.noext;
  2531. }
  2532. const state = {
  2533. input,
  2534. index: -1,
  2535. start: 0,
  2536. dot: opts.dot === true,
  2537. consumed: '',
  2538. output: '',
  2539. prefix: '',
  2540. backtrack: false,
  2541. negated: false,
  2542. brackets: 0,
  2543. braces: 0,
  2544. parens: 0,
  2545. quotes: 0,
  2546. globstar: false,
  2547. tokens
  2548. };
  2549. input = utils$1.removePrefix(input, state);
  2550. len = input.length;
  2551. const extglobs = [];
  2552. const braces = [];
  2553. const stack = [];
  2554. let prev = bos;
  2555. let value;
  2556. /**
  2557. * Tokenizing helpers
  2558. */
  2559. const eos = () => state.index === len - 1;
  2560. const peek = state.peek = (n = 1) => input[state.index + n];
  2561. const advance = state.advance = () => input[++state.index] || '';
  2562. const remaining = () => input.slice(state.index + 1);
  2563. const consume = (value = '', num = 0) => {
  2564. state.consumed += value;
  2565. state.index += num;
  2566. };
  2567. const append = token => {
  2568. state.output += token.output != null ? token.output : token.value;
  2569. consume(token.value);
  2570. };
  2571. const negate = () => {
  2572. let count = 1;
  2573. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  2574. advance();
  2575. state.start++;
  2576. count++;
  2577. }
  2578. if (count % 2 === 0) {
  2579. return false;
  2580. }
  2581. state.negated = true;
  2582. state.start++;
  2583. return true;
  2584. };
  2585. const increment = type => {
  2586. state[type]++;
  2587. stack.push(type);
  2588. };
  2589. const decrement = type => {
  2590. state[type]--;
  2591. stack.pop();
  2592. };
  2593. /**
  2594. * Push tokens onto the tokens array. This helper speeds up
  2595. * tokenizing by 1) helping us avoid backtracking as much as possible,
  2596. * and 2) helping us avoid creating extra tokens when consecutive
  2597. * characters are plain text. This improves performance and simplifies
  2598. * lookbehinds.
  2599. */
  2600. const push = tok => {
  2601. if (prev.type === 'globstar') {
  2602. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  2603. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  2604. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  2605. state.output = state.output.slice(0, -prev.output.length);
  2606. prev.type = 'star';
  2607. prev.value = '*';
  2608. prev.output = star;
  2609. state.output += prev.output;
  2610. }
  2611. }
  2612. if (extglobs.length && tok.type !== 'paren') {
  2613. extglobs[extglobs.length - 1].inner += tok.value;
  2614. }
  2615. if (tok.value || tok.output) append(tok);
  2616. if (prev && prev.type === 'text' && tok.type === 'text') {
  2617. prev.value += tok.value;
  2618. prev.output = (prev.output || '') + tok.value;
  2619. return;
  2620. }
  2621. tok.prev = prev;
  2622. tokens.push(tok);
  2623. prev = tok;
  2624. };
  2625. const extglobOpen = (type, value) => {
  2626. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  2627. token.prev = prev;
  2628. token.parens = state.parens;
  2629. token.output = state.output;
  2630. const output = (opts.capture ? '(' : '') + token.open;
  2631. increment('parens');
  2632. push({ type, value, output: state.output ? '' : ONE_CHAR });
  2633. push({ type: 'paren', extglob: true, value: advance(), output });
  2634. extglobs.push(token);
  2635. };
  2636. const extglobClose = token => {
  2637. let output = token.close + (opts.capture ? ')' : '');
  2638. let rest;
  2639. if (token.type === 'negate') {
  2640. let extglobStar = star;
  2641. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  2642. extglobStar = globstar(opts);
  2643. }
  2644. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  2645. output = token.close = `)$))${extglobStar}`;
  2646. }
  2647. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  2648. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  2649. // In this case, we need to parse the string and use it in the output of the original pattern.
  2650. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  2651. //
  2652. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  2653. const expression = parse$1(rest, { ...options, fastpaths: false }).output;
  2654. output = token.close = `)${expression})${extglobStar})`;
  2655. }
  2656. if (token.prev.type === 'bos') {
  2657. state.negatedExtglob = true;
  2658. }
  2659. }
  2660. push({ type: 'paren', extglob: true, value, output });
  2661. decrement('parens');
  2662. };
  2663. /**
  2664. * Fast paths
  2665. */
  2666. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  2667. let backslashes = false;
  2668. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  2669. if (first === '\\') {
  2670. backslashes = true;
  2671. return m;
  2672. }
  2673. if (first === '?') {
  2674. if (esc) {
  2675. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  2676. }
  2677. if (index === 0) {
  2678. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  2679. }
  2680. return QMARK.repeat(chars.length);
  2681. }
  2682. if (first === '.') {
  2683. return DOT_LITERAL.repeat(chars.length);
  2684. }
  2685. if (first === '*') {
  2686. if (esc) {
  2687. return esc + first + (rest ? star : '');
  2688. }
  2689. return star;
  2690. }
  2691. return esc ? m : `\\${m}`;
  2692. });
  2693. if (backslashes === true) {
  2694. if (opts.unescape === true) {
  2695. output = output.replace(/\\/g, '');
  2696. } else {
  2697. output = output.replace(/\\+/g, m => {
  2698. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  2699. });
  2700. }
  2701. }
  2702. if (output === input && opts.contains === true) {
  2703. state.output = input;
  2704. return state;
  2705. }
  2706. state.output = utils$1.wrapOutput(output, state, options);
  2707. return state;
  2708. }
  2709. /**
  2710. * Tokenize input until we reach end-of-string
  2711. */
  2712. while (!eos()) {
  2713. value = advance();
  2714. if (value === '\u0000') {
  2715. continue;
  2716. }
  2717. /**
  2718. * Escaped characters
  2719. */
  2720. if (value === '\\') {
  2721. const next = peek();
  2722. if (next === '/' && opts.bash !== true) {
  2723. continue;
  2724. }
  2725. if (next === '.' || next === ';') {
  2726. continue;
  2727. }
  2728. if (!next) {
  2729. value += '\\';
  2730. push({ type: 'text', value });
  2731. continue;
  2732. }
  2733. // collapse slashes to reduce potential for exploits
  2734. const match = /^\\+/.exec(remaining());
  2735. let slashes = 0;
  2736. if (match && match[0].length > 2) {
  2737. slashes = match[0].length;
  2738. state.index += slashes;
  2739. if (slashes % 2 !== 0) {
  2740. value += '\\';
  2741. }
  2742. }
  2743. if (opts.unescape === true) {
  2744. value = advance();
  2745. } else {
  2746. value += advance();
  2747. }
  2748. if (state.brackets === 0) {
  2749. push({ type: 'text', value });
  2750. continue;
  2751. }
  2752. }
  2753. /**
  2754. * If we're inside a regex character class, continue
  2755. * until we reach the closing bracket.
  2756. */
  2757. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  2758. if (opts.posix !== false && value === ':') {
  2759. const inner = prev.value.slice(1);
  2760. if (inner.includes('[')) {
  2761. prev.posix = true;
  2762. if (inner.includes(':')) {
  2763. const idx = prev.value.lastIndexOf('[');
  2764. const pre = prev.value.slice(0, idx);
  2765. const rest = prev.value.slice(idx + 2);
  2766. const posix = POSIX_REGEX_SOURCE[rest];
  2767. if (posix) {
  2768. prev.value = pre + posix;
  2769. state.backtrack = true;
  2770. advance();
  2771. if (!bos.output && tokens.indexOf(prev) === 1) {
  2772. bos.output = ONE_CHAR;
  2773. }
  2774. continue;
  2775. }
  2776. }
  2777. }
  2778. }
  2779. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  2780. value = `\\${value}`;
  2781. }
  2782. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  2783. value = `\\${value}`;
  2784. }
  2785. if (opts.posix === true && value === '!' && prev.value === '[') {
  2786. value = '^';
  2787. }
  2788. prev.value += value;
  2789. append({ value });
  2790. continue;
  2791. }
  2792. /**
  2793. * If we're inside a quoted string, continue
  2794. * until we reach the closing double quote.
  2795. */
  2796. if (state.quotes === 1 && value !== '"') {
  2797. value = utils$1.escapeRegex(value);
  2798. prev.value += value;
  2799. append({ value });
  2800. continue;
  2801. }
  2802. /**
  2803. * Double quotes
  2804. */
  2805. if (value === '"') {
  2806. state.quotes = state.quotes === 1 ? 0 : 1;
  2807. if (opts.keepQuotes === true) {
  2808. push({ type: 'text', value });
  2809. }
  2810. continue;
  2811. }
  2812. /**
  2813. * Parentheses
  2814. */
  2815. if (value === '(') {
  2816. increment('parens');
  2817. push({ type: 'paren', value });
  2818. continue;
  2819. }
  2820. if (value === ')') {
  2821. if (state.parens === 0 && opts.strictBrackets === true) {
  2822. throw new SyntaxError(syntaxError('opening', '('));
  2823. }
  2824. const extglob = extglobs[extglobs.length - 1];
  2825. if (extglob && state.parens === extglob.parens + 1) {
  2826. extglobClose(extglobs.pop());
  2827. continue;
  2828. }
  2829. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  2830. decrement('parens');
  2831. continue;
  2832. }
  2833. /**
  2834. * Square brackets
  2835. */
  2836. if (value === '[') {
  2837. if (opts.nobracket === true || !remaining().includes(']')) {
  2838. if (opts.nobracket !== true && opts.strictBrackets === true) {
  2839. throw new SyntaxError(syntaxError('closing', ']'));
  2840. }
  2841. value = `\\${value}`;
  2842. } else {
  2843. increment('brackets');
  2844. }
  2845. push({ type: 'bracket', value });
  2846. continue;
  2847. }
  2848. if (value === ']') {
  2849. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  2850. push({ type: 'text', value, output: `\\${value}` });
  2851. continue;
  2852. }
  2853. if (state.brackets === 0) {
  2854. if (opts.strictBrackets === true) {
  2855. throw new SyntaxError(syntaxError('opening', '['));
  2856. }
  2857. push({ type: 'text', value, output: `\\${value}` });
  2858. continue;
  2859. }
  2860. decrement('brackets');
  2861. const prevValue = prev.value.slice(1);
  2862. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  2863. value = `/${value}`;
  2864. }
  2865. prev.value += value;
  2866. append({ value });
  2867. // when literal brackets are explicitly disabled
  2868. // assume we should match with a regex character class
  2869. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  2870. continue;
  2871. }
  2872. const escaped = utils$1.escapeRegex(prev.value);
  2873. state.output = state.output.slice(0, -prev.value.length);
  2874. // when literal brackets are explicitly enabled
  2875. // assume we should escape the brackets to match literal characters
  2876. if (opts.literalBrackets === true) {
  2877. state.output += escaped;
  2878. prev.value = escaped;
  2879. continue;
  2880. }
  2881. // when the user specifies nothing, try to match both
  2882. prev.value = `(${capture}${escaped}|${prev.value})`;
  2883. state.output += prev.value;
  2884. continue;
  2885. }
  2886. /**
  2887. * Braces
  2888. */
  2889. if (value === '{' && opts.nobrace !== true) {
  2890. increment('braces');
  2891. const open = {
  2892. type: 'brace',
  2893. value,
  2894. output: '(',
  2895. outputIndex: state.output.length,
  2896. tokensIndex: state.tokens.length
  2897. };
  2898. braces.push(open);
  2899. push(open);
  2900. continue;
  2901. }
  2902. if (value === '}') {
  2903. const brace = braces[braces.length - 1];
  2904. if (opts.nobrace === true || !brace) {
  2905. push({ type: 'text', value, output: value });
  2906. continue;
  2907. }
  2908. let output = ')';
  2909. if (brace.dots === true) {
  2910. const arr = tokens.slice();
  2911. const range = [];
  2912. for (let i = arr.length - 1; i >= 0; i--) {
  2913. tokens.pop();
  2914. if (arr[i].type === 'brace') {
  2915. break;
  2916. }
  2917. if (arr[i].type !== 'dots') {
  2918. range.unshift(arr[i].value);
  2919. }
  2920. }
  2921. output = expandRange(range, opts);
  2922. state.backtrack = true;
  2923. }
  2924. if (brace.comma !== true && brace.dots !== true) {
  2925. const out = state.output.slice(0, brace.outputIndex);
  2926. const toks = state.tokens.slice(brace.tokensIndex);
  2927. brace.value = brace.output = '\\{';
  2928. value = output = '\\}';
  2929. state.output = out;
  2930. for (const t of toks) {
  2931. state.output += (t.output || t.value);
  2932. }
  2933. }
  2934. push({ type: 'brace', value, output });
  2935. decrement('braces');
  2936. braces.pop();
  2937. continue;
  2938. }
  2939. /**
  2940. * Pipes
  2941. */
  2942. if (value === '|') {
  2943. if (extglobs.length > 0) {
  2944. extglobs[extglobs.length - 1].conditions++;
  2945. }
  2946. push({ type: 'text', value });
  2947. continue;
  2948. }
  2949. /**
  2950. * Commas
  2951. */
  2952. if (value === ',') {
  2953. let output = value;
  2954. const brace = braces[braces.length - 1];
  2955. if (brace && stack[stack.length - 1] === 'braces') {
  2956. brace.comma = true;
  2957. output = '|';
  2958. }
  2959. push({ type: 'comma', value, output });
  2960. continue;
  2961. }
  2962. /**
  2963. * Slashes
  2964. */
  2965. if (value === '/') {
  2966. // if the beginning of the glob is "./", advance the start
  2967. // to the current index, and don't add the "./" characters
  2968. // to the state. This greatly simplifies lookbehinds when
  2969. // checking for BOS characters like "!" and "." (not "./")
  2970. if (prev.type === 'dot' && state.index === state.start + 1) {
  2971. state.start = state.index + 1;
  2972. state.consumed = '';
  2973. state.output = '';
  2974. tokens.pop();
  2975. prev = bos; // reset "prev" to the first token
  2976. continue;
  2977. }
  2978. push({ type: 'slash', value, output: SLASH_LITERAL });
  2979. continue;
  2980. }
  2981. /**
  2982. * Dots
  2983. */
  2984. if (value === '.') {
  2985. if (state.braces > 0 && prev.type === 'dot') {
  2986. if (prev.value === '.') prev.output = DOT_LITERAL;
  2987. const brace = braces[braces.length - 1];
  2988. prev.type = 'dots';
  2989. prev.output += value;
  2990. prev.value += value;
  2991. brace.dots = true;
  2992. continue;
  2993. }
  2994. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  2995. push({ type: 'text', value, output: DOT_LITERAL });
  2996. continue;
  2997. }
  2998. push({ type: 'dot', value, output: DOT_LITERAL });
  2999. continue;
  3000. }
  3001. /**
  3002. * Question marks
  3003. */
  3004. if (value === '?') {
  3005. const isGroup = prev && prev.value === '(';
  3006. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3007. extglobOpen('qmark', value);
  3008. continue;
  3009. }
  3010. if (prev && prev.type === 'paren') {
  3011. const next = peek();
  3012. let output = value;
  3013. if (next === '<' && !utils$1.supportsLookbehinds()) {
  3014. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  3015. }
  3016. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  3017. output = `\\${value}`;
  3018. }
  3019. push({ type: 'text', value, output });
  3020. continue;
  3021. }
  3022. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  3023. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  3024. continue;
  3025. }
  3026. push({ type: 'qmark', value, output: QMARK });
  3027. continue;
  3028. }
  3029. /**
  3030. * Exclamation
  3031. */
  3032. if (value === '!') {
  3033. if (opts.noextglob !== true && peek() === '(') {
  3034. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  3035. extglobOpen('negate', value);
  3036. continue;
  3037. }
  3038. }
  3039. if (opts.nonegate !== true && state.index === 0) {
  3040. negate();
  3041. continue;
  3042. }
  3043. }
  3044. /**
  3045. * Plus
  3046. */
  3047. if (value === '+') {
  3048. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3049. extglobOpen('plus', value);
  3050. continue;
  3051. }
  3052. if ((prev && prev.value === '(') || opts.regex === false) {
  3053. push({ type: 'plus', value, output: PLUS_LITERAL });
  3054. continue;
  3055. }
  3056. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  3057. push({ type: 'plus', value });
  3058. continue;
  3059. }
  3060. push({ type: 'plus', value: PLUS_LITERAL });
  3061. continue;
  3062. }
  3063. /**
  3064. * Plain text
  3065. */
  3066. if (value === '@') {
  3067. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3068. push({ type: 'at', extglob: true, value, output: '' });
  3069. continue;
  3070. }
  3071. push({ type: 'text', value });
  3072. continue;
  3073. }
  3074. /**
  3075. * Plain text
  3076. */
  3077. if (value !== '*') {
  3078. if (value === '$' || value === '^') {
  3079. value = `\\${value}`;
  3080. }
  3081. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  3082. if (match) {
  3083. value += match[0];
  3084. state.index += match[0].length;
  3085. }
  3086. push({ type: 'text', value });
  3087. continue;
  3088. }
  3089. /**
  3090. * Stars
  3091. */
  3092. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  3093. prev.type = 'star';
  3094. prev.star = true;
  3095. prev.value += value;
  3096. prev.output = star;
  3097. state.backtrack = true;
  3098. state.globstar = true;
  3099. consume(value);
  3100. continue;
  3101. }
  3102. let rest = remaining();
  3103. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  3104. extglobOpen('star', value);
  3105. continue;
  3106. }
  3107. if (prev.type === 'star') {
  3108. if (opts.noglobstar === true) {
  3109. consume(value);
  3110. continue;
  3111. }
  3112. const prior = prev.prev;
  3113. const before = prior.prev;
  3114. const isStart = prior.type === 'slash' || prior.type === 'bos';
  3115. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  3116. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  3117. push({ type: 'star', value, output: '' });
  3118. continue;
  3119. }
  3120. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  3121. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  3122. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  3123. push({ type: 'star', value, output: '' });
  3124. continue;
  3125. }
  3126. // strip consecutive `/**/`
  3127. while (rest.slice(0, 3) === '/**') {
  3128. const after = input[state.index + 4];
  3129. if (after && after !== '/') {
  3130. break;
  3131. }
  3132. rest = rest.slice(3);
  3133. consume('/**', 3);
  3134. }
  3135. if (prior.type === 'bos' && eos()) {
  3136. prev.type = 'globstar';
  3137. prev.value += value;
  3138. prev.output = globstar(opts);
  3139. state.output = prev.output;
  3140. state.globstar = true;
  3141. consume(value);
  3142. continue;
  3143. }
  3144. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  3145. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3146. prior.output = `(?:${prior.output}`;
  3147. prev.type = 'globstar';
  3148. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  3149. prev.value += value;
  3150. state.globstar = true;
  3151. state.output += prior.output + prev.output;
  3152. consume(value);
  3153. continue;
  3154. }
  3155. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  3156. const end = rest[1] !== void 0 ? '|$' : '';
  3157. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3158. prior.output = `(?:${prior.output}`;
  3159. prev.type = 'globstar';
  3160. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  3161. prev.value += value;
  3162. state.output += prior.output + prev.output;
  3163. state.globstar = true;
  3164. consume(value + advance());
  3165. push({ type: 'slash', value: '/', output: '' });
  3166. continue;
  3167. }
  3168. if (prior.type === 'bos' && rest[0] === '/') {
  3169. prev.type = 'globstar';
  3170. prev.value += value;
  3171. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  3172. state.output = prev.output;
  3173. state.globstar = true;
  3174. consume(value + advance());
  3175. push({ type: 'slash', value: '/', output: '' });
  3176. continue;
  3177. }
  3178. // remove single star from output
  3179. state.output = state.output.slice(0, -prev.output.length);
  3180. // reset previous token to globstar
  3181. prev.type = 'globstar';
  3182. prev.output = globstar(opts);
  3183. prev.value += value;
  3184. // reset output with globstar
  3185. state.output += prev.output;
  3186. state.globstar = true;
  3187. consume(value);
  3188. continue;
  3189. }
  3190. const token = { type: 'star', value, output: star };
  3191. if (opts.bash === true) {
  3192. token.output = '.*?';
  3193. if (prev.type === 'bos' || prev.type === 'slash') {
  3194. token.output = nodot + token.output;
  3195. }
  3196. push(token);
  3197. continue;
  3198. }
  3199. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  3200. token.output = value;
  3201. push(token);
  3202. continue;
  3203. }
  3204. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  3205. if (prev.type === 'dot') {
  3206. state.output += NO_DOT_SLASH;
  3207. prev.output += NO_DOT_SLASH;
  3208. } else if (opts.dot === true) {
  3209. state.output += NO_DOTS_SLASH;
  3210. prev.output += NO_DOTS_SLASH;
  3211. } else {
  3212. state.output += nodot;
  3213. prev.output += nodot;
  3214. }
  3215. if (peek() !== '*') {
  3216. state.output += ONE_CHAR;
  3217. prev.output += ONE_CHAR;
  3218. }
  3219. }
  3220. push(token);
  3221. }
  3222. while (state.brackets > 0) {
  3223. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  3224. state.output = utils$1.escapeLast(state.output, '[');
  3225. decrement('brackets');
  3226. }
  3227. while (state.parens > 0) {
  3228. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  3229. state.output = utils$1.escapeLast(state.output, '(');
  3230. decrement('parens');
  3231. }
  3232. while (state.braces > 0) {
  3233. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  3234. state.output = utils$1.escapeLast(state.output, '{');
  3235. decrement('braces');
  3236. }
  3237. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  3238. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  3239. }
  3240. // rebuild the output if we had to backtrack at any point
  3241. if (state.backtrack === true) {
  3242. state.output = '';
  3243. for (const token of state.tokens) {
  3244. state.output += token.output != null ? token.output : token.value;
  3245. if (token.suffix) {
  3246. state.output += token.suffix;
  3247. }
  3248. }
  3249. }
  3250. return state;
  3251. };
  3252. /**
  3253. * Fast paths for creating regular expressions for common glob patterns.
  3254. * This can significantly speed up processing and has very little downside
  3255. * impact when none of the fast paths match.
  3256. */
  3257. parse$1.fastpaths = (input, options) => {
  3258. const opts = { ...options };
  3259. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3260. const len = input.length;
  3261. if (len > max) {
  3262. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3263. }
  3264. input = REPLACEMENTS[input] || input;
  3265. const win32 = utils$1.isWindows(options);
  3266. // create constants based on platform, for windows or posix
  3267. const {
  3268. DOT_LITERAL,
  3269. SLASH_LITERAL,
  3270. ONE_CHAR,
  3271. DOTS_SLASH,
  3272. NO_DOT,
  3273. NO_DOTS,
  3274. NO_DOTS_SLASH,
  3275. STAR,
  3276. START_ANCHOR
  3277. } = constants$1.globChars(win32);
  3278. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  3279. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  3280. const capture = opts.capture ? '' : '?:';
  3281. const state = { negated: false, prefix: '' };
  3282. let star = opts.bash === true ? '.*?' : STAR;
  3283. if (opts.capture) {
  3284. star = `(${star})`;
  3285. }
  3286. const globstar = opts => {
  3287. if (opts.noglobstar === true) return star;
  3288. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3289. };
  3290. const create = str => {
  3291. switch (str) {
  3292. case '*':
  3293. return `${nodot}${ONE_CHAR}${star}`;
  3294. case '.*':
  3295. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  3296. case '*.*':
  3297. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3298. case '*/*':
  3299. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  3300. case '**':
  3301. return nodot + globstar(opts);
  3302. case '**/*':
  3303. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  3304. case '**/*.*':
  3305. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3306. case '**/.*':
  3307. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  3308. default: {
  3309. const match = /^(.*?)\.(\w+)$/.exec(str);
  3310. if (!match) return;
  3311. const source = create(match[1]);
  3312. if (!source) return;
  3313. return source + DOT_LITERAL + match[2];
  3314. }
  3315. }
  3316. };
  3317. const output = utils$1.removePrefix(input, state);
  3318. let source = create(output);
  3319. if (source && opts.strictSlashes !== true) {
  3320. source += `${SLASH_LITERAL}?`;
  3321. }
  3322. return source;
  3323. };
  3324. var parse_1 = parse$1;
  3325. const path = require$$0$1;
  3326. const scan = scan_1;
  3327. const parse = parse_1;
  3328. const utils = utils$3;
  3329. const constants = constants$2;
  3330. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  3331. /**
  3332. * Creates a matcher function from one or more glob patterns. The
  3333. * returned function takes a string to match as its first argument,
  3334. * and returns true if the string is a match. The returned matcher
  3335. * function also takes a boolean as the second argument that, when true,
  3336. * returns an object with additional information.
  3337. *
  3338. * ```js
  3339. * const picomatch = require('picomatch');
  3340. * // picomatch(glob[, options]);
  3341. *
  3342. * const isMatch = picomatch('*.!(*a)');
  3343. * console.log(isMatch('a.a')); //=> false
  3344. * console.log(isMatch('a.b')); //=> true
  3345. * ```
  3346. * @name picomatch
  3347. * @param {String|Array} `globs` One or more glob patterns.
  3348. * @param {Object=} `options`
  3349. * @return {Function=} Returns a matcher function.
  3350. * @api public
  3351. */
  3352. const picomatch$1 = (glob, options, returnState = false) => {
  3353. if (Array.isArray(glob)) {
  3354. const fns = glob.map(input => picomatch$1(input, options, returnState));
  3355. const arrayMatcher = str => {
  3356. for (const isMatch of fns) {
  3357. const state = isMatch(str);
  3358. if (state) return state;
  3359. }
  3360. return false;
  3361. };
  3362. return arrayMatcher;
  3363. }
  3364. const isState = isObject(glob) && glob.tokens && glob.input;
  3365. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  3366. throw new TypeError('Expected pattern to be a non-empty string');
  3367. }
  3368. const opts = options || {};
  3369. const posix = utils.isWindows(options);
  3370. const regex = isState
  3371. ? picomatch$1.compileRe(glob, options)
  3372. : picomatch$1.makeRe(glob, options, false, true);
  3373. const state = regex.state;
  3374. delete regex.state;
  3375. let isIgnored = () => false;
  3376. if (opts.ignore) {
  3377. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  3378. isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
  3379. }
  3380. const matcher = (input, returnObject = false) => {
  3381. const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix });
  3382. const result = { glob, state, regex, posix, input, output, match, isMatch };
  3383. if (typeof opts.onResult === 'function') {
  3384. opts.onResult(result);
  3385. }
  3386. if (isMatch === false) {
  3387. result.isMatch = false;
  3388. return returnObject ? result : false;
  3389. }
  3390. if (isIgnored(input)) {
  3391. if (typeof opts.onIgnore === 'function') {
  3392. opts.onIgnore(result);
  3393. }
  3394. result.isMatch = false;
  3395. return returnObject ? result : false;
  3396. }
  3397. if (typeof opts.onMatch === 'function') {
  3398. opts.onMatch(result);
  3399. }
  3400. return returnObject ? result : true;
  3401. };
  3402. if (returnState) {
  3403. matcher.state = state;
  3404. }
  3405. return matcher;
  3406. };
  3407. /**
  3408. * Test `input` with the given `regex`. This is used by the main
  3409. * `picomatch()` function to test the input string.
  3410. *
  3411. * ```js
  3412. * const picomatch = require('picomatch');
  3413. * // picomatch.test(input, regex[, options]);
  3414. *
  3415. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  3416. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  3417. * ```
  3418. * @param {String} `input` String to test.
  3419. * @param {RegExp} `regex`
  3420. * @return {Object} Returns an object with matching info.
  3421. * @api public
  3422. */
  3423. picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
  3424. if (typeof input !== 'string') {
  3425. throw new TypeError('Expected input to be a string');
  3426. }
  3427. if (input === '') {
  3428. return { isMatch: false, output: '' };
  3429. }
  3430. const opts = options || {};
  3431. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  3432. let match = input === glob;
  3433. let output = (match && format) ? format(input) : input;
  3434. if (match === false) {
  3435. output = format ? format(input) : input;
  3436. match = output === glob;
  3437. }
  3438. if (match === false || opts.capture === true) {
  3439. if (opts.matchBase === true || opts.basename === true) {
  3440. match = picomatch$1.matchBase(input, regex, options, posix);
  3441. } else {
  3442. match = regex.exec(output);
  3443. }
  3444. }
  3445. return { isMatch: Boolean(match), match, output };
  3446. };
  3447. /**
  3448. * Match the basename of a filepath.
  3449. *
  3450. * ```js
  3451. * const picomatch = require('picomatch');
  3452. * // picomatch.matchBase(input, glob[, options]);
  3453. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  3454. * ```
  3455. * @param {String} `input` String to test.
  3456. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  3457. * @return {Boolean}
  3458. * @api public
  3459. */
  3460. picomatch$1.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  3461. const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options);
  3462. return regex.test(path.basename(input));
  3463. };
  3464. /**
  3465. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  3466. *
  3467. * ```js
  3468. * const picomatch = require('picomatch');
  3469. * // picomatch.isMatch(string, patterns[, options]);
  3470. *
  3471. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  3472. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  3473. * ```
  3474. * @param {String|Array} str The string to test.
  3475. * @param {String|Array} patterns One or more glob patterns to use for matching.
  3476. * @param {Object} [options] See available [options](#options).
  3477. * @return {Boolean} Returns true if any patterns match `str`
  3478. * @api public
  3479. */
  3480. picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  3481. /**
  3482. * Parse a glob pattern to create the source string for a regular
  3483. * expression.
  3484. *
  3485. * ```js
  3486. * const picomatch = require('picomatch');
  3487. * const result = picomatch.parse(pattern[, options]);
  3488. * ```
  3489. * @param {String} `pattern`
  3490. * @param {Object} `options`
  3491. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  3492. * @api public
  3493. */
  3494. picomatch$1.parse = (pattern, options) => {
  3495. if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options));
  3496. return parse(pattern, { ...options, fastpaths: false });
  3497. };
  3498. /**
  3499. * Scan a glob pattern to separate the pattern into segments.
  3500. *
  3501. * ```js
  3502. * const picomatch = require('picomatch');
  3503. * // picomatch.scan(input[, options]);
  3504. *
  3505. * const result = picomatch.scan('!./foo/*.js');
  3506. * console.log(result);
  3507. * { prefix: '!./',
  3508. * input: '!./foo/*.js',
  3509. * start: 3,
  3510. * base: 'foo',
  3511. * glob: '*.js',
  3512. * isBrace: false,
  3513. * isBracket: false,
  3514. * isGlob: true,
  3515. * isExtglob: false,
  3516. * isGlobstar: false,
  3517. * negated: true }
  3518. * ```
  3519. * @param {String} `input` Glob pattern to scan.
  3520. * @param {Object} `options`
  3521. * @return {Object} Returns an object with
  3522. * @api public
  3523. */
  3524. picomatch$1.scan = (input, options) => scan(input, options);
  3525. /**
  3526. * Compile a regular expression from the `state` object returned by the
  3527. * [parse()](#parse) method.
  3528. *
  3529. * @param {Object} `state`
  3530. * @param {Object} `options`
  3531. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  3532. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  3533. * @return {RegExp}
  3534. * @api public
  3535. */
  3536. picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
  3537. if (returnOutput === true) {
  3538. return state.output;
  3539. }
  3540. const opts = options || {};
  3541. const prepend = opts.contains ? '' : '^';
  3542. const append = opts.contains ? '' : '$';
  3543. let source = `${prepend}(?:${state.output})${append}`;
  3544. if (state && state.negated === true) {
  3545. source = `^(?!${source}).*$`;
  3546. }
  3547. const regex = picomatch$1.toRegex(source, options);
  3548. if (returnState === true) {
  3549. regex.state = state;
  3550. }
  3551. return regex;
  3552. };
  3553. /**
  3554. * Create a regular expression from a parsed glob pattern.
  3555. *
  3556. * ```js
  3557. * const picomatch = require('picomatch');
  3558. * const state = picomatch.parse('*.js');
  3559. * // picomatch.compileRe(state[, options]);
  3560. *
  3561. * console.log(picomatch.compileRe(state));
  3562. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3563. * ```
  3564. * @param {String} `state` The object returned from the `.parse` method.
  3565. * @param {Object} `options`
  3566. * @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.
  3567. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  3568. * @return {RegExp} Returns a regex created from the given pattern.
  3569. * @api public
  3570. */
  3571. picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  3572. if (!input || typeof input !== 'string') {
  3573. throw new TypeError('Expected a non-empty string');
  3574. }
  3575. let parsed = { negated: false, fastpaths: true };
  3576. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  3577. parsed.output = parse.fastpaths(input, options);
  3578. }
  3579. if (!parsed.output) {
  3580. parsed = parse(input, options);
  3581. }
  3582. return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
  3583. };
  3584. /**
  3585. * Create a regular expression from the given regex source string.
  3586. *
  3587. * ```js
  3588. * const picomatch = require('picomatch');
  3589. * // picomatch.toRegex(source[, options]);
  3590. *
  3591. * const { output } = picomatch.parse('*.js');
  3592. * console.log(picomatch.toRegex(output));
  3593. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3594. * ```
  3595. * @param {String} `source` Regular expression source string.
  3596. * @param {Object} `options`
  3597. * @return {RegExp}
  3598. * @api public
  3599. */
  3600. picomatch$1.toRegex = (source, options) => {
  3601. try {
  3602. const opts = options || {};
  3603. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  3604. } catch (err) {
  3605. if (options && options.debug === true) throw err;
  3606. return /$^/;
  3607. }
  3608. };
  3609. /**
  3610. * Picomatch constants.
  3611. * @return {Object}
  3612. */
  3613. picomatch$1.constants = constants;
  3614. /**
  3615. * Expose "picomatch"
  3616. */
  3617. var picomatch_1 = picomatch$1;
  3618. var picomatch = picomatch_1;
  3619. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch);
  3620. const extractors = {
  3621. ArrayPattern(names, param) {
  3622. for (const element of param.elements) {
  3623. if (element)
  3624. extractors[element.type](names, element);
  3625. }
  3626. },
  3627. AssignmentPattern(names, param) {
  3628. extractors[param.left.type](names, param.left);
  3629. },
  3630. Identifier(names, param) {
  3631. names.push(param.name);
  3632. },
  3633. MemberExpression() { },
  3634. ObjectPattern(names, param) {
  3635. for (const prop of param.properties) {
  3636. // @ts-ignore Typescript reports that this is not a valid type
  3637. if (prop.type === 'RestElement') {
  3638. extractors.RestElement(names, prop);
  3639. }
  3640. else {
  3641. extractors[prop.value.type](names, prop.value);
  3642. }
  3643. }
  3644. },
  3645. RestElement(names, param) {
  3646. extractors[param.argument.type](names, param.argument);
  3647. }
  3648. };
  3649. const extractAssignedNames = function extractAssignedNames(param) {
  3650. const names = [];
  3651. extractors[param.type](names, param);
  3652. return names;
  3653. };
  3654. // Helper since Typescript can't detect readonly arrays with Array.isArray
  3655. function isArray(arg) {
  3656. return Array.isArray(arg);
  3657. }
  3658. function ensureArray$1(thing) {
  3659. if (isArray(thing))
  3660. return thing;
  3661. if (thing == null)
  3662. return [];
  3663. return [thing];
  3664. }
  3665. const normalizePath = function normalizePath(filename) {
  3666. return filename.split(win32.sep).join(posix.sep);
  3667. };
  3668. function getMatcherString(id, resolutionBase) {
  3669. if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) {
  3670. return normalizePath(id);
  3671. }
  3672. // resolve('') is valid and will default to process.cwd()
  3673. const basePath = normalizePath(resolve(resolutionBase || ''))
  3674. // escape all possible (posix + win) path characters that might interfere with regex
  3675. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  3676. // Note that we use posix.join because:
  3677. // 1. the basePath has been normalized to use /
  3678. // 2. the incoming glob (id) matcher, also uses /
  3679. // otherwise Node will force backslash (\) on windows
  3680. return posix.join(basePath, normalizePath(id));
  3681. }
  3682. const createFilter = function createFilter(include, exclude, options) {
  3683. const resolutionBase = options && options.resolve;
  3684. const getMatcher = (id) => id instanceof RegExp
  3685. ? id
  3686. : {
  3687. test: (what) => {
  3688. // this refactor is a tad overly verbose but makes for easy debugging
  3689. const pattern = getMatcherString(id, resolutionBase);
  3690. const fn = pm(pattern, { dot: true });
  3691. const result = fn(what);
  3692. return result;
  3693. }
  3694. };
  3695. const includeMatchers = ensureArray$1(include).map(getMatcher);
  3696. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  3697. return function result(id) {
  3698. if (typeof id !== 'string')
  3699. return false;
  3700. if (/\0/.test(id))
  3701. return false;
  3702. const pathId = normalizePath(id);
  3703. for (let i = 0; i < excludeMatchers.length; ++i) {
  3704. const matcher = excludeMatchers[i];
  3705. if (matcher.test(pathId))
  3706. return false;
  3707. }
  3708. for (let i = 0; i < includeMatchers.length; ++i) {
  3709. const matcher = includeMatchers[i];
  3710. if (matcher.test(pathId))
  3711. return true;
  3712. }
  3713. return !includeMatchers.length;
  3714. };
  3715. };
  3716. 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';
  3717. 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';
  3718. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  3719. forbiddenIdentifiers.add('');
  3720. function createInclusionContext() {
  3721. return {
  3722. brokenFlow: false,
  3723. hasBreak: false,
  3724. hasContinue: false,
  3725. includedCallArguments: new Set(),
  3726. includedLabels: new Set()
  3727. };
  3728. }
  3729. function createHasEffectsContext() {
  3730. return {
  3731. accessed: new PathTracker(),
  3732. assigned: new PathTracker(),
  3733. brokenFlow: false,
  3734. called: new DiscriminatedPathTracker(),
  3735. hasBreak: false,
  3736. hasContinue: false,
  3737. ignore: {
  3738. breaks: false,
  3739. continues: false,
  3740. labels: new Set(),
  3741. returnYield: false,
  3742. this: false
  3743. },
  3744. includedLabels: new Set(),
  3745. instantiated: new DiscriminatedPathTracker(),
  3746. replacedVariableInits: new Map()
  3747. };
  3748. }
  3749. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  3750. return Object.create(inheritedDescriptions, memberDescriptions);
  3751. }
  3752. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  3753. getLiteralValueAtPath() {
  3754. return undefined;
  3755. }
  3756. })();
  3757. const returnsUnknown = {
  3758. value: {
  3759. hasEffectsWhenCalled: null,
  3760. returns: UNKNOWN_EXPRESSION
  3761. }
  3762. };
  3763. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  3764. getReturnExpressionWhenCalledAtPath(path) {
  3765. if (path.length === 1) {
  3766. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  3767. }
  3768. return UNKNOWN_RETURN_EXPRESSION;
  3769. }
  3770. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3771. if (interaction.type === INTERACTION_ACCESSED) {
  3772. return path.length > 1;
  3773. }
  3774. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3775. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  3776. }
  3777. return true;
  3778. }
  3779. })();
  3780. const returnsBoolean = {
  3781. value: {
  3782. hasEffectsWhenCalled: null,
  3783. returns: UNKNOWN_LITERAL_BOOLEAN
  3784. }
  3785. };
  3786. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  3787. getReturnExpressionWhenCalledAtPath(path) {
  3788. if (path.length === 1) {
  3789. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  3790. }
  3791. return UNKNOWN_RETURN_EXPRESSION;
  3792. }
  3793. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3794. if (interaction.type === INTERACTION_ACCESSED) {
  3795. return path.length > 1;
  3796. }
  3797. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3798. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  3799. }
  3800. return true;
  3801. }
  3802. })();
  3803. const returnsNumber = {
  3804. value: {
  3805. hasEffectsWhenCalled: null,
  3806. returns: UNKNOWN_LITERAL_NUMBER
  3807. }
  3808. };
  3809. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  3810. getReturnExpressionWhenCalledAtPath(path) {
  3811. if (path.length === 1) {
  3812. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  3813. }
  3814. return UNKNOWN_RETURN_EXPRESSION;
  3815. }
  3816. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3817. if (interaction.type === INTERACTION_ACCESSED) {
  3818. return path.length > 1;
  3819. }
  3820. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3821. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  3822. }
  3823. return true;
  3824. }
  3825. })();
  3826. const returnsString = {
  3827. value: {
  3828. hasEffectsWhenCalled: null,
  3829. returns: UNKNOWN_LITERAL_STRING
  3830. }
  3831. };
  3832. const stringReplace = {
  3833. value: {
  3834. hasEffectsWhenCalled({ args }, context) {
  3835. const argument1 = args[2];
  3836. return (args.length < 3 ||
  3837. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  3838. deoptimizeCache() { }
  3839. }) === 'symbol' &&
  3840. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  3841. },
  3842. returns: UNKNOWN_LITERAL_STRING
  3843. }
  3844. };
  3845. const objectMembers = assembleMemberDescriptions({
  3846. hasOwnProperty: returnsBoolean,
  3847. isPrototypeOf: returnsBoolean,
  3848. propertyIsEnumerable: returnsBoolean,
  3849. toLocaleString: returnsString,
  3850. toString: returnsString,
  3851. valueOf: returnsUnknown
  3852. });
  3853. const literalBooleanMembers = assembleMemberDescriptions({
  3854. valueOf: returnsBoolean
  3855. }, objectMembers);
  3856. const literalNumberMembers = assembleMemberDescriptions({
  3857. toExponential: returnsString,
  3858. toFixed: returnsString,
  3859. toLocaleString: returnsString,
  3860. toPrecision: returnsString,
  3861. valueOf: returnsNumber
  3862. }, objectMembers);
  3863. /**
  3864. * RegExp are stateful when they have the global or sticky flags set.
  3865. * But if we actually don't use them, the side effect does not matter.
  3866. * the check logic in `hasEffectsOnInteractionAtPath`.
  3867. */
  3868. const literalRegExpMembers = assembleMemberDescriptions({
  3869. exec: returnsUnknown,
  3870. test: returnsBoolean
  3871. }, objectMembers);
  3872. const literalStringMembers = assembleMemberDescriptions({
  3873. anchor: returnsString,
  3874. at: returnsUnknown,
  3875. big: returnsString,
  3876. blink: returnsString,
  3877. bold: returnsString,
  3878. charAt: returnsString,
  3879. charCodeAt: returnsNumber,
  3880. codePointAt: returnsUnknown,
  3881. concat: returnsString,
  3882. endsWith: returnsBoolean,
  3883. fixed: returnsString,
  3884. fontcolor: returnsString,
  3885. fontsize: returnsString,
  3886. includes: returnsBoolean,
  3887. indexOf: returnsNumber,
  3888. italics: returnsString,
  3889. lastIndexOf: returnsNumber,
  3890. link: returnsString,
  3891. localeCompare: returnsNumber,
  3892. match: returnsUnknown,
  3893. matchAll: returnsUnknown,
  3894. normalize: returnsString,
  3895. padEnd: returnsString,
  3896. padStart: returnsString,
  3897. repeat: returnsString,
  3898. replace: stringReplace,
  3899. replaceAll: stringReplace,
  3900. search: returnsNumber,
  3901. slice: returnsString,
  3902. small: returnsString,
  3903. split: returnsUnknown,
  3904. startsWith: returnsBoolean,
  3905. strike: returnsString,
  3906. sub: returnsString,
  3907. substr: returnsString,
  3908. substring: returnsString,
  3909. sup: returnsString,
  3910. toLocaleLowerCase: returnsString,
  3911. toLocaleUpperCase: returnsString,
  3912. toLowerCase: returnsString,
  3913. toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
  3914. toUpperCase: returnsString,
  3915. trim: returnsString,
  3916. trimEnd: returnsString,
  3917. trimLeft: returnsString,
  3918. trimRight: returnsString,
  3919. trimStart: returnsString,
  3920. valueOf: returnsString
  3921. }, objectMembers);
  3922. function getLiteralMembersForValue(value) {
  3923. if (value instanceof RegExp) {
  3924. return literalRegExpMembers;
  3925. }
  3926. switch (typeof value) {
  3927. case 'boolean': {
  3928. return literalBooleanMembers;
  3929. }
  3930. case 'number': {
  3931. return literalNumberMembers;
  3932. }
  3933. case 'string': {
  3934. return literalStringMembers;
  3935. }
  3936. }
  3937. return Object.create(null);
  3938. }
  3939. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  3940. if (typeof memberName !== 'string' || !members[memberName]) {
  3941. return true;
  3942. }
  3943. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  3944. }
  3945. function getMemberReturnExpressionWhenCalled(members, memberName) {
  3946. if (typeof memberName !== 'string' || !members[memberName])
  3947. return UNKNOWN_RETURN_EXPRESSION;
  3948. return [members[memberName].returns, false];
  3949. }
  3950. // This file is generated by scripts/generate-child-node-keys.js.
  3951. // Do not edit this file directly.
  3952. const childNodeKeys = {
  3953. ArrayExpression: ['elements'],
  3954. ArrayPattern: ['elements'],
  3955. ArrowFunctionExpression: ['params', 'body'],
  3956. AssignmentExpression: ['left', 'right'],
  3957. AssignmentPattern: ['left', 'right'],
  3958. AwaitExpression: ['argument'],
  3959. BinaryExpression: ['left', 'right'],
  3960. BlockStatement: ['body'],
  3961. BreakStatement: ['label'],
  3962. CallExpression: ['callee', 'arguments'],
  3963. CatchClause: ['param', 'body'],
  3964. ChainExpression: ['expression'],
  3965. ClassBody: ['body'],
  3966. ClassDeclaration: ['id', 'superClass', 'body'],
  3967. ClassExpression: ['id', 'superClass', 'body'],
  3968. ConditionalExpression: ['test', 'consequent', 'alternate'],
  3969. ContinueStatement: ['label'],
  3970. DebuggerStatement: [],
  3971. DoWhileStatement: ['body', 'test'],
  3972. EmptyStatement: [],
  3973. ExportAllDeclaration: ['exported', 'source', 'attributes'],
  3974. ExportDefaultDeclaration: ['declaration'],
  3975. ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
  3976. ExportSpecifier: ['local', 'exported'],
  3977. ExpressionStatement: ['expression'],
  3978. ForInStatement: ['left', 'right', 'body'],
  3979. ForOfStatement: ['left', 'right', 'body'],
  3980. ForStatement: ['init', 'test', 'update', 'body'],
  3981. FunctionDeclaration: ['id', 'params', 'body'],
  3982. FunctionExpression: ['id', 'params', 'body'],
  3983. Identifier: [],
  3984. IfStatement: ['test', 'consequent', 'alternate'],
  3985. ImportAttribute: ['key', 'value'],
  3986. ImportDeclaration: ['specifiers', 'source', 'attributes'],
  3987. ImportDefaultSpecifier: ['local'],
  3988. ImportExpression: ['source', 'options'],
  3989. ImportNamespaceSpecifier: ['local'],
  3990. ImportSpecifier: ['imported', 'local'],
  3991. LabeledStatement: ['label', 'body'],
  3992. Literal: [],
  3993. LogicalExpression: ['left', 'right'],
  3994. MemberExpression: ['object', 'property'],
  3995. MetaProperty: ['meta', 'property'],
  3996. MethodDefinition: ['key', 'value'],
  3997. NewExpression: ['callee', 'arguments'],
  3998. ObjectExpression: ['properties'],
  3999. ObjectPattern: ['properties'],
  4000. PanicError: [],
  4001. ParseError: [],
  4002. PrivateIdentifier: [],
  4003. Program: ['body'],
  4004. Property: ['key', 'value'],
  4005. PropertyDefinition: ['key', 'value'],
  4006. RestElement: ['argument'],
  4007. ReturnStatement: ['argument'],
  4008. SequenceExpression: ['expressions'],
  4009. SpreadElement: ['argument'],
  4010. StaticBlock: ['body'],
  4011. Super: [],
  4012. SwitchCase: ['test', 'consequent'],
  4013. SwitchStatement: ['discriminant', 'cases'],
  4014. TaggedTemplateExpression: ['tag', 'quasi'],
  4015. TemplateElement: [],
  4016. TemplateLiteral: ['quasis', 'expressions'],
  4017. ThisExpression: [],
  4018. ThrowStatement: ['argument'],
  4019. TryStatement: ['block', 'handler', 'finalizer'],
  4020. UnaryExpression: ['argument'],
  4021. UpdateExpression: ['argument'],
  4022. VariableDeclaration: ['declarations'],
  4023. VariableDeclarator: ['id', 'init'],
  4024. WhileStatement: ['test', 'body'],
  4025. YieldExpression: ['argument']
  4026. };
  4027. const INCLUDE_PARAMETERS = 'variables';
  4028. class NodeBase extends ExpressionEntity {
  4029. /**
  4030. * Nodes can apply custom deoptimizations once they become part of the
  4031. * executed code. To do this, they must initialize this as false, implement
  4032. * applyDeoptimizations and call this from include and hasEffects if they have
  4033. * custom handlers
  4034. */
  4035. get deoptimized() {
  4036. return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
  4037. }
  4038. set deoptimized(value) {
  4039. this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
  4040. }
  4041. constructor(parent, parentScope) {
  4042. super();
  4043. this.parent = parent;
  4044. this.scope = parentScope;
  4045. this.createScope(parentScope);
  4046. }
  4047. addExportedVariables(_variables, _exportNamesByVariable) { }
  4048. /**
  4049. * Override this to bind assignments to variables and do any initialisations
  4050. * that require the scopes to be populated with variables.
  4051. */
  4052. bind() {
  4053. for (const key of childNodeKeys[this.type]) {
  4054. const value = this[key];
  4055. if (Array.isArray(value)) {
  4056. for (const child of value) {
  4057. child?.bind();
  4058. }
  4059. }
  4060. else if (value) {
  4061. value.bind();
  4062. }
  4063. }
  4064. }
  4065. /**
  4066. * Override if this node should receive a different scope than the parent
  4067. * scope.
  4068. */
  4069. createScope(parentScope) {
  4070. this.scope = parentScope;
  4071. }
  4072. hasEffects(context) {
  4073. if (!this.deoptimized)
  4074. this.applyDeoptimizations();
  4075. for (const key of childNodeKeys[this.type]) {
  4076. const value = this[key];
  4077. if (value === null)
  4078. continue;
  4079. if (Array.isArray(value)) {
  4080. for (const child of value) {
  4081. if (child?.hasEffects(context))
  4082. return true;
  4083. }
  4084. }
  4085. else if (value.hasEffects(context))
  4086. return true;
  4087. }
  4088. return false;
  4089. }
  4090. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  4091. return (this.hasEffects(context) ||
  4092. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  4093. }
  4094. include(context, includeChildrenRecursively, _options) {
  4095. if (!this.deoptimized)
  4096. this.applyDeoptimizations();
  4097. this.included = true;
  4098. for (const key of childNodeKeys[this.type]) {
  4099. const value = this[key];
  4100. if (value === null)
  4101. continue;
  4102. if (Array.isArray(value)) {
  4103. for (const child of value) {
  4104. child?.include(context, includeChildrenRecursively);
  4105. }
  4106. }
  4107. else {
  4108. value.include(context, includeChildrenRecursively);
  4109. }
  4110. }
  4111. }
  4112. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  4113. this.include(context, includeChildrenRecursively);
  4114. }
  4115. /**
  4116. * Override to perform special initialisation steps after the scope is
  4117. * initialised
  4118. */
  4119. initialise() {
  4120. this.scope.context.magicString.addSourcemapLocation(this.start);
  4121. this.scope.context.magicString.addSourcemapLocation(this.end);
  4122. }
  4123. parseNode(esTreeNode) {
  4124. for (const [key, value] of Object.entries(esTreeNode)) {
  4125. // Skip properties defined on the class already.
  4126. // This way, we can override this function to add custom initialisation and then call super.parseNode
  4127. // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
  4128. // in bitfields. Those are still assigned from the value in the esTreeNode.
  4129. if (this.hasOwnProperty(key))
  4130. continue;
  4131. if (key.charCodeAt(0) === 95 /* _ */) {
  4132. if (key === ANNOTATION_KEY) {
  4133. this.annotations = value;
  4134. }
  4135. else if (key === INVALID_ANNOTATION_KEY) {
  4136. this.invalidAnnotations = value;
  4137. }
  4138. }
  4139. else if (typeof value !== 'object' || value === null) {
  4140. this[key] = value;
  4141. }
  4142. else if (Array.isArray(value)) {
  4143. this[key] = [];
  4144. for (const child of value) {
  4145. this[key].push(child === null
  4146. ? null
  4147. : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child));
  4148. }
  4149. }
  4150. else {
  4151. this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
  4152. }
  4153. }
  4154. // extend child keys for unknown node types
  4155. childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
  4156. this.initialise();
  4157. return this;
  4158. }
  4159. removeAnnotations(code) {
  4160. if (this.annotations) {
  4161. for (const annotation of this.annotations) {
  4162. code.remove(annotation.start, annotation.end);
  4163. }
  4164. }
  4165. }
  4166. render(code, options) {
  4167. for (const key of childNodeKeys[this.type]) {
  4168. const value = this[key];
  4169. if (value === null)
  4170. continue;
  4171. if (Array.isArray(value)) {
  4172. for (const child of value) {
  4173. child?.render(code, options);
  4174. }
  4175. }
  4176. else {
  4177. value.render(code, options);
  4178. }
  4179. }
  4180. }
  4181. setAssignedValue(value) {
  4182. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  4183. }
  4184. shouldBeIncluded(context) {
  4185. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  4186. }
  4187. /**
  4188. * Just deoptimize everything by default so that when e.g. we do not track
  4189. * something properly, it is deoptimized.
  4190. * @protected
  4191. */
  4192. applyDeoptimizations() {
  4193. this.deoptimized = true;
  4194. for (const key of childNodeKeys[this.type]) {
  4195. const value = this[key];
  4196. if (value === null)
  4197. continue;
  4198. if (Array.isArray(value)) {
  4199. for (const child of value) {
  4200. child?.deoptimizePath(UNKNOWN_PATH);
  4201. }
  4202. }
  4203. else {
  4204. value.deoptimizePath(UNKNOWN_PATH);
  4205. }
  4206. }
  4207. this.scope.context.requestTreeshakingPass();
  4208. }
  4209. }
  4210. function createChildNodeKeysForNode(esTreeNode) {
  4211. return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  4212. }
  4213. class SpreadElement extends NodeBase {
  4214. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4215. if (path.length > 0) {
  4216. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  4217. }
  4218. }
  4219. hasEffects(context) {
  4220. if (!this.deoptimized)
  4221. this.applyDeoptimizations();
  4222. const { propertyReadSideEffects } = this.scope.context.options
  4223. .treeshake;
  4224. return (this.argument.hasEffects(context) ||
  4225. (propertyReadSideEffects &&
  4226. (propertyReadSideEffects === 'always' ||
  4227. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  4228. }
  4229. applyDeoptimizations() {
  4230. this.deoptimized = true;
  4231. // Only properties of properties of the argument could become subject to reassignment
  4232. // This will also reassign the return values of iterators
  4233. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  4234. this.scope.context.requestTreeshakingPass();
  4235. }
  4236. }
  4237. class Method extends ExpressionEntity {
  4238. constructor(description) {
  4239. super();
  4240. this.description = description;
  4241. }
  4242. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  4243. if (type === INTERACTION_CALLED && path.length === 0) {
  4244. if (this.description.mutatesSelfAsArray) {
  4245. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4246. }
  4247. if (this.description.mutatesArgs) {
  4248. for (let index = 1; index < args.length; index++) {
  4249. args[index].deoptimizePath(UNKNOWN_PATH);
  4250. }
  4251. }
  4252. }
  4253. }
  4254. getReturnExpressionWhenCalledAtPath(path, { args }) {
  4255. if (path.length > 0) {
  4256. return UNKNOWN_RETURN_EXPRESSION;
  4257. }
  4258. return [
  4259. this.description.returnsPrimitive ||
  4260. (this.description.returns === 'self'
  4261. ? args[0] || UNKNOWN_EXPRESSION
  4262. : this.description.returns()),
  4263. false
  4264. ];
  4265. }
  4266. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4267. const { type } = interaction;
  4268. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  4269. return true;
  4270. }
  4271. if (type === INTERACTION_CALLED) {
  4272. const { args } = interaction;
  4273. if (this.description.mutatesSelfAsArray === true &&
  4274. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  4275. return true;
  4276. }
  4277. if (this.description.callsArgs) {
  4278. for (const argumentIndex of this.description.callsArgs) {
  4279. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  4280. return true;
  4281. }
  4282. }
  4283. }
  4284. }
  4285. return false;
  4286. }
  4287. }
  4288. const METHOD_RETURNS_BOOLEAN = [
  4289. new Method({
  4290. callsArgs: null,
  4291. mutatesArgs: false,
  4292. mutatesSelfAsArray: false,
  4293. returns: null,
  4294. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4295. })
  4296. ];
  4297. const METHOD_RETURNS_STRING = [
  4298. new Method({
  4299. callsArgs: null,
  4300. mutatesArgs: false,
  4301. mutatesSelfAsArray: false,
  4302. returns: null,
  4303. returnsPrimitive: UNKNOWN_LITERAL_STRING
  4304. })
  4305. ];
  4306. const METHOD_RETURNS_NUMBER = [
  4307. new Method({
  4308. callsArgs: null,
  4309. mutatesArgs: false,
  4310. mutatesSelfAsArray: false,
  4311. returns: null,
  4312. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4313. })
  4314. ];
  4315. const METHOD_RETURNS_UNKNOWN = [
  4316. new Method({
  4317. callsArgs: null,
  4318. mutatesArgs: false,
  4319. mutatesSelfAsArray: false,
  4320. returns: null,
  4321. returnsPrimitive: UNKNOWN_EXPRESSION
  4322. })
  4323. ];
  4324. const INTEGER_REG_EXP = /^\d+$/;
  4325. class ObjectEntity extends ExpressionEntity {
  4326. get hasLostTrack() {
  4327. return isFlagSet(this.flags, 2048 /* Flag.hasLostTrack */);
  4328. }
  4329. set hasLostTrack(value) {
  4330. this.flags = setFlag(this.flags, 2048 /* Flag.hasLostTrack */, value);
  4331. }
  4332. get hasUnknownDeoptimizedInteger() {
  4333. return isFlagSet(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */);
  4334. }
  4335. set hasUnknownDeoptimizedInteger(value) {
  4336. this.flags = setFlag(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */, value);
  4337. }
  4338. get hasUnknownDeoptimizedProperty() {
  4339. return isFlagSet(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */);
  4340. }
  4341. set hasUnknownDeoptimizedProperty(value) {
  4342. this.flags = setFlag(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */, value);
  4343. }
  4344. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  4345. // and we assume there are no setters or getters
  4346. constructor(properties, prototypeExpression, immutable = false) {
  4347. super();
  4348. this.prototypeExpression = prototypeExpression;
  4349. this.immutable = immutable;
  4350. this.additionalExpressionsToBeDeoptimized = new Set();
  4351. this.allProperties = [];
  4352. this.deoptimizedPaths = Object.create(null);
  4353. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  4354. this.gettersByKey = Object.create(null);
  4355. this.propertiesAndGettersByKey = Object.create(null);
  4356. this.propertiesAndSettersByKey = Object.create(null);
  4357. this.settersByKey = Object.create(null);
  4358. this.unknownIntegerProps = [];
  4359. this.unmatchableGetters = [];
  4360. this.unmatchablePropertiesAndGetters = [];
  4361. this.unmatchableSetters = [];
  4362. if (Array.isArray(properties)) {
  4363. this.buildPropertyMaps(properties);
  4364. }
  4365. else {
  4366. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  4367. for (const propertiesForKey of Object.values(properties)) {
  4368. this.allProperties.push(...propertiesForKey);
  4369. }
  4370. }
  4371. }
  4372. deoptimizeAllProperties(noAccessors) {
  4373. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  4374. if (noAccessors) {
  4375. this.hasUnknownDeoptimizedProperty = true;
  4376. }
  4377. else {
  4378. this.hasLostTrack = true;
  4379. }
  4380. if (isDeoptimized) {
  4381. return;
  4382. }
  4383. for (const properties of [
  4384. ...Object.values(this.propertiesAndGettersByKey),
  4385. ...Object.values(this.settersByKey)
  4386. ]) {
  4387. for (const property of properties) {
  4388. property.deoptimizePath(UNKNOWN_PATH);
  4389. }
  4390. }
  4391. // While the prototype itself cannot be mutated, each property can
  4392. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  4393. this.deoptimizeCachedEntities();
  4394. }
  4395. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4396. const [key, ...subPath] = path;
  4397. const { args, type } = interaction;
  4398. if (this.hasLostTrack ||
  4399. // single paths that are deoptimized will not become getters or setters
  4400. ((type === INTERACTION_CALLED || path.length > 1) &&
  4401. (this.hasUnknownDeoptimizedProperty ||
  4402. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  4403. deoptimizeInteraction(interaction);
  4404. return;
  4405. }
  4406. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  4407. ? [
  4408. this.propertiesAndGettersByKey,
  4409. this.propertiesAndGettersByKey,
  4410. this.unmatchablePropertiesAndGetters
  4411. ]
  4412. : type === INTERACTION_ACCESSED
  4413. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4414. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4415. if (typeof key === 'string') {
  4416. if (propertiesForExactMatchByKey[key]) {
  4417. const properties = relevantPropertiesByKey[key];
  4418. if (properties) {
  4419. for (const property of properties) {
  4420. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4421. }
  4422. }
  4423. if (!this.immutable) {
  4424. for (const argument of args) {
  4425. if (argument) {
  4426. this.additionalExpressionsToBeDeoptimized.add(argument);
  4427. }
  4428. }
  4429. }
  4430. return;
  4431. }
  4432. for (const property of relevantUnmatchableProperties) {
  4433. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4434. }
  4435. if (INTEGER_REG_EXP.test(key)) {
  4436. for (const property of this.unknownIntegerProps) {
  4437. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4438. }
  4439. }
  4440. }
  4441. else {
  4442. for (const properties of [
  4443. ...Object.values(relevantPropertiesByKey),
  4444. relevantUnmatchableProperties
  4445. ]) {
  4446. for (const property of properties) {
  4447. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4448. }
  4449. }
  4450. for (const property of this.unknownIntegerProps) {
  4451. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4452. }
  4453. }
  4454. if (!this.immutable) {
  4455. for (const argument of args) {
  4456. if (argument) {
  4457. this.additionalExpressionsToBeDeoptimized.add(argument);
  4458. }
  4459. }
  4460. }
  4461. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4462. }
  4463. deoptimizeIntegerProperties() {
  4464. if (this.hasLostTrack ||
  4465. this.hasUnknownDeoptimizedProperty ||
  4466. this.hasUnknownDeoptimizedInteger) {
  4467. return;
  4468. }
  4469. this.hasUnknownDeoptimizedInteger = true;
  4470. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  4471. if (INTEGER_REG_EXP.test(key)) {
  4472. for (const property of propertiesAndGetters) {
  4473. property.deoptimizePath(UNKNOWN_PATH);
  4474. }
  4475. }
  4476. }
  4477. this.deoptimizeCachedIntegerEntities();
  4478. }
  4479. // Assumption: If only a specific path is deoptimized, no accessors are created
  4480. deoptimizePath(path) {
  4481. if (this.hasLostTrack || this.immutable) {
  4482. return;
  4483. }
  4484. const key = path[0];
  4485. if (path.length === 1) {
  4486. if (typeof key !== 'string') {
  4487. if (key === UnknownInteger) {
  4488. return this.deoptimizeIntegerProperties();
  4489. }
  4490. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  4491. }
  4492. if (!this.deoptimizedPaths[key]) {
  4493. this.deoptimizedPaths[key] = true;
  4494. // we only deoptimizeCache exact matches as in all other cases,
  4495. // we do not return a literal value or return expression
  4496. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  4497. if (expressionsToBeDeoptimized) {
  4498. for (const expression of expressionsToBeDeoptimized) {
  4499. expression.deoptimizeCache();
  4500. }
  4501. }
  4502. }
  4503. }
  4504. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  4505. for (const property of typeof key === 'string'
  4506. ? [
  4507. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  4508. ...(this.settersByKey[key] || this.unmatchableSetters)
  4509. ]
  4510. : this.allProperties) {
  4511. property.deoptimizePath(subPath);
  4512. }
  4513. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  4514. }
  4515. getLiteralValueAtPath(path, recursionTracker, origin) {
  4516. if (path.length === 0) {
  4517. return UnknownTruthyValue;
  4518. }
  4519. const key = path[0];
  4520. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4521. if (expressionAtPath) {
  4522. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  4523. }
  4524. if (this.prototypeExpression) {
  4525. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  4526. }
  4527. if (path.length === 1) {
  4528. return undefined;
  4529. }
  4530. return UnknownValue;
  4531. }
  4532. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4533. if (path.length === 0) {
  4534. return UNKNOWN_RETURN_EXPRESSION;
  4535. }
  4536. const [key, ...subPath] = path;
  4537. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4538. if (expressionAtPath) {
  4539. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  4540. }
  4541. if (this.prototypeExpression) {
  4542. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4543. }
  4544. return UNKNOWN_RETURN_EXPRESSION;
  4545. }
  4546. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4547. const [key, ...subPath] = path;
  4548. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  4549. const expressionAtPath = this.getMemberExpression(key);
  4550. if (expressionAtPath) {
  4551. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  4552. }
  4553. if (this.prototypeExpression) {
  4554. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  4555. }
  4556. return true;
  4557. }
  4558. if (key === UnknownNonAccessorKey)
  4559. return false;
  4560. if (this.hasLostTrack)
  4561. return true;
  4562. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  4563. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4564. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4565. if (typeof key === 'string') {
  4566. if (propertiesAndAccessorsByKey[key]) {
  4567. const accessors = accessorsByKey[key];
  4568. if (accessors) {
  4569. for (const accessor of accessors) {
  4570. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  4571. return true;
  4572. }
  4573. }
  4574. return false;
  4575. }
  4576. for (const accessor of unmatchableAccessors) {
  4577. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  4578. return true;
  4579. }
  4580. }
  4581. }
  4582. else {
  4583. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  4584. for (const accessor of accessors) {
  4585. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  4586. return true;
  4587. }
  4588. }
  4589. }
  4590. if (this.prototypeExpression) {
  4591. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  4592. }
  4593. return false;
  4594. }
  4595. buildPropertyMaps(properties) {
  4596. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  4597. const unmatchablePropertiesAndSetters = [];
  4598. for (let index = properties.length - 1; index >= 0; index--) {
  4599. const { key, kind, property } = properties[index];
  4600. allProperties.push(property);
  4601. if (typeof key === 'string') {
  4602. if (kind === 'set') {
  4603. if (!propertiesAndSettersByKey[key]) {
  4604. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  4605. settersByKey[key] = [property, ...unmatchableSetters];
  4606. }
  4607. }
  4608. else if (kind === 'get') {
  4609. if (!propertiesAndGettersByKey[key]) {
  4610. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  4611. gettersByKey[key] = [property, ...unmatchableGetters];
  4612. }
  4613. }
  4614. else {
  4615. if (!propertiesAndSettersByKey[key]) {
  4616. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  4617. }
  4618. if (!propertiesAndGettersByKey[key]) {
  4619. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  4620. }
  4621. }
  4622. }
  4623. else {
  4624. if (key === UnknownInteger) {
  4625. unknownIntegerProps.push(property);
  4626. continue;
  4627. }
  4628. if (kind === 'set')
  4629. unmatchableSetters.push(property);
  4630. if (kind === 'get')
  4631. unmatchableGetters.push(property);
  4632. if (kind !== 'get')
  4633. unmatchablePropertiesAndSetters.push(property);
  4634. if (kind !== 'set')
  4635. unmatchablePropertiesAndGetters.push(property);
  4636. }
  4637. }
  4638. }
  4639. deoptimizeCachedEntities() {
  4640. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  4641. for (const expression of expressionsToBeDeoptimized) {
  4642. expression.deoptimizeCache();
  4643. }
  4644. }
  4645. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  4646. expression.deoptimizePath(UNKNOWN_PATH);
  4647. }
  4648. }
  4649. deoptimizeCachedIntegerEntities() {
  4650. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  4651. if (INTEGER_REG_EXP.test(key)) {
  4652. for (const expression of expressionsToBeDeoptimized) {
  4653. expression.deoptimizeCache();
  4654. }
  4655. }
  4656. }
  4657. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  4658. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4659. }
  4660. }
  4661. getMemberExpression(key) {
  4662. if (this.hasLostTrack ||
  4663. this.hasUnknownDeoptimizedProperty ||
  4664. typeof key !== 'string' ||
  4665. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  4666. this.deoptimizedPaths[key]) {
  4667. return UNKNOWN_EXPRESSION;
  4668. }
  4669. const properties = this.propertiesAndGettersByKey[key];
  4670. if (properties?.length === 1) {
  4671. return properties[0];
  4672. }
  4673. if (properties ||
  4674. this.unmatchablePropertiesAndGetters.length > 0 ||
  4675. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  4676. return UNKNOWN_EXPRESSION;
  4677. }
  4678. return null;
  4679. }
  4680. getMemberExpressionAndTrackDeopt(key, origin) {
  4681. if (typeof key !== 'string') {
  4682. return UNKNOWN_EXPRESSION;
  4683. }
  4684. const expression = this.getMemberExpression(key);
  4685. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  4686. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  4687. this.expressionsToBeDeoptimizedByKey[key] || []);
  4688. expressionsToBeDeoptimized.push(origin);
  4689. }
  4690. return expression;
  4691. }
  4692. }
  4693. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  4694. // This makes sure unknown properties are not handled as "undefined" but as
  4695. // "unknown" but without access side effects. An exception is done for numeric
  4696. // properties as we do not expect new builtin properties to be numbers, this
  4697. // will improve tree-shaking for out-of-bounds array properties
  4698. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  4699. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  4700. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  4701. deoptimizeInteraction(interaction);
  4702. }
  4703. }
  4704. getLiteralValueAtPath(path) {
  4705. // We ignore number properties as we do not expect new properties to be
  4706. // numbers and also want to keep handling out-of-bound array elements as
  4707. // "undefined"
  4708. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  4709. }
  4710. hasEffectsOnInteractionAtPath(path, { type }) {
  4711. return path.length > 1 || type === INTERACTION_CALLED;
  4712. }
  4713. })();
  4714. const OBJECT_PROTOTYPE = new ObjectEntity({
  4715. __proto__: null,
  4716. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  4717. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  4718. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  4719. toLocaleString: METHOD_RETURNS_STRING,
  4720. toString: METHOD_RETURNS_STRING,
  4721. valueOf: METHOD_RETURNS_UNKNOWN
  4722. }, OBJECT_PROTOTYPE_FALLBACK, true);
  4723. const NEW_ARRAY_PROPERTIES = [
  4724. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  4725. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  4726. ];
  4727. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  4728. new Method({
  4729. callsArgs: [0],
  4730. mutatesArgs: false,
  4731. mutatesSelfAsArray: 'deopt-only',
  4732. returns: null,
  4733. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4734. })
  4735. ];
  4736. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  4737. new Method({
  4738. callsArgs: [0],
  4739. mutatesArgs: false,
  4740. mutatesSelfAsArray: 'deopt-only',
  4741. returns: null,
  4742. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4743. })
  4744. ];
  4745. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  4746. new Method({
  4747. callsArgs: null,
  4748. mutatesArgs: false,
  4749. mutatesSelfAsArray: true,
  4750. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  4751. returnsPrimitive: null
  4752. })
  4753. ];
  4754. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  4755. new Method({
  4756. callsArgs: null,
  4757. mutatesArgs: false,
  4758. mutatesSelfAsArray: 'deopt-only',
  4759. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  4760. returnsPrimitive: null
  4761. })
  4762. ];
  4763. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  4764. new Method({
  4765. callsArgs: [0],
  4766. mutatesArgs: false,
  4767. mutatesSelfAsArray: 'deopt-only',
  4768. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  4769. returnsPrimitive: null
  4770. })
  4771. ];
  4772. const METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER = [
  4773. new Method({
  4774. callsArgs: null,
  4775. mutatesArgs: true,
  4776. mutatesSelfAsArray: true,
  4777. returns: null,
  4778. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4779. })
  4780. ];
  4781. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  4782. new Method({
  4783. callsArgs: null,
  4784. mutatesArgs: false,
  4785. mutatesSelfAsArray: true,
  4786. returns: null,
  4787. returnsPrimitive: UNKNOWN_EXPRESSION
  4788. })
  4789. ];
  4790. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  4791. new Method({
  4792. callsArgs: null,
  4793. mutatesArgs: false,
  4794. mutatesSelfAsArray: 'deopt-only',
  4795. returns: null,
  4796. returnsPrimitive: UNKNOWN_EXPRESSION
  4797. })
  4798. ];
  4799. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  4800. new Method({
  4801. callsArgs: [0],
  4802. mutatesArgs: false,
  4803. mutatesSelfAsArray: 'deopt-only',
  4804. returns: null,
  4805. returnsPrimitive: UNKNOWN_EXPRESSION
  4806. })
  4807. ];
  4808. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  4809. new Method({
  4810. callsArgs: null,
  4811. mutatesArgs: false,
  4812. mutatesSelfAsArray: true,
  4813. returns: 'self',
  4814. returnsPrimitive: null
  4815. })
  4816. ];
  4817. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  4818. new Method({
  4819. callsArgs: [0],
  4820. mutatesArgs: false,
  4821. mutatesSelfAsArray: true,
  4822. returns: 'self',
  4823. returnsPrimitive: null
  4824. })
  4825. ];
  4826. const ARRAY_PROTOTYPE = new ObjectEntity({
  4827. __proto__: null,
  4828. // We assume that accessors have effects as we do not track the accessed value afterwards
  4829. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  4830. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4831. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  4832. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4833. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  4834. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  4835. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4836. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4837. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  4838. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4839. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  4840. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4841. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4842. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4843. includes: METHOD_RETURNS_BOOLEAN,
  4844. indexOf: METHOD_RETURNS_NUMBER,
  4845. join: METHOD_RETURNS_STRING,
  4846. keys: METHOD_RETURNS_UNKNOWN,
  4847. lastIndexOf: METHOD_RETURNS_NUMBER,
  4848. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4849. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  4850. push: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  4851. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4852. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4853. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  4854. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  4855. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4856. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  4857. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  4858. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  4859. toLocaleString: METHOD_RETURNS_STRING,
  4860. toString: METHOD_RETURNS_STRING,
  4861. unshift: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  4862. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  4863. }, OBJECT_PROTOTYPE, true);
  4864. class ArrayExpression extends NodeBase {
  4865. constructor() {
  4866. super(...arguments);
  4867. this.objectEntity = null;
  4868. }
  4869. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4870. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4871. }
  4872. deoptimizePath(path) {
  4873. this.getObjectEntity().deoptimizePath(path);
  4874. }
  4875. getLiteralValueAtPath(path, recursionTracker, origin) {
  4876. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  4877. }
  4878. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4879. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4880. }
  4881. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4882. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  4883. }
  4884. applyDeoptimizations() {
  4885. this.deoptimized = true;
  4886. let hasSpread = false;
  4887. for (let index = 0; index < this.elements.length; index++) {
  4888. const element = this.elements[index];
  4889. if (element && (hasSpread || element instanceof SpreadElement)) {
  4890. hasSpread = true;
  4891. element.deoptimizePath(UNKNOWN_PATH);
  4892. }
  4893. }
  4894. this.scope.context.requestTreeshakingPass();
  4895. }
  4896. getObjectEntity() {
  4897. if (this.objectEntity !== null) {
  4898. return this.objectEntity;
  4899. }
  4900. const properties = [
  4901. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  4902. ];
  4903. let hasSpread = false;
  4904. for (let index = 0; index < this.elements.length; index++) {
  4905. const element = this.elements[index];
  4906. if (hasSpread || element instanceof SpreadElement) {
  4907. if (element) {
  4908. hasSpread = true;
  4909. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  4910. }
  4911. }
  4912. else if (element) {
  4913. properties.push({ key: String(index), kind: 'init', property: element });
  4914. }
  4915. else {
  4916. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  4917. }
  4918. }
  4919. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  4920. }
  4921. }
  4922. class ArrayPattern extends NodeBase {
  4923. addExportedVariables(variables, exportNamesByVariable) {
  4924. for (const element of this.elements) {
  4925. element?.addExportedVariables(variables, exportNamesByVariable);
  4926. }
  4927. }
  4928. declare(kind) {
  4929. const variables = [];
  4930. for (const element of this.elements) {
  4931. if (element !== null) {
  4932. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  4933. }
  4934. }
  4935. return variables;
  4936. }
  4937. // Patterns can only be deoptimized at the empty path at the moment
  4938. deoptimizePath() {
  4939. for (const element of this.elements) {
  4940. element?.deoptimizePath(EMPTY_PATH);
  4941. }
  4942. }
  4943. // Patterns are only checked at the empty path at the moment
  4944. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  4945. for (const element of this.elements) {
  4946. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  4947. return true;
  4948. }
  4949. return false;
  4950. }
  4951. markDeclarationReached() {
  4952. for (const element of this.elements) {
  4953. element?.markDeclarationReached();
  4954. }
  4955. }
  4956. }
  4957. class LocalVariable extends Variable {
  4958. constructor(name, declarator, init, context, kind) {
  4959. super(name);
  4960. this.init = init;
  4961. this.calledFromTryStatement = false;
  4962. this.additionalInitializers = null;
  4963. this.expressionsToBeDeoptimized = [];
  4964. this.declarations = declarator ? [declarator] : [];
  4965. this.deoptimizationTracker = context.deoptimizationTracker;
  4966. this.module = context.module;
  4967. this.kind = kind;
  4968. }
  4969. addDeclaration(identifier, init) {
  4970. this.declarations.push(identifier);
  4971. this.markInitializersForDeoptimization().push(init);
  4972. }
  4973. consolidateInitializers() {
  4974. if (this.additionalInitializers) {
  4975. for (const initializer of this.additionalInitializers) {
  4976. initializer.deoptimizePath(UNKNOWN_PATH);
  4977. }
  4978. this.additionalInitializers = null;
  4979. }
  4980. }
  4981. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4982. if (this.isReassigned) {
  4983. deoptimizeInteraction(interaction);
  4984. return;
  4985. }
  4986. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  4987. }
  4988. deoptimizePath(path) {
  4989. if (this.isReassigned ||
  4990. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  4991. return;
  4992. }
  4993. if (path.length === 0) {
  4994. this.isReassigned = true;
  4995. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  4996. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  4997. for (const expression of expressionsToBeDeoptimized) {
  4998. expression.deoptimizeCache();
  4999. }
  5000. this.init.deoptimizePath(UNKNOWN_PATH);
  5001. }
  5002. else {
  5003. this.init.deoptimizePath(path);
  5004. }
  5005. }
  5006. getLiteralValueAtPath(path, recursionTracker, origin) {
  5007. if (this.isReassigned) {
  5008. return UnknownValue;
  5009. }
  5010. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5011. this.expressionsToBeDeoptimized.push(origin);
  5012. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  5013. }, UnknownValue);
  5014. }
  5015. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5016. if (this.isReassigned) {
  5017. return UNKNOWN_RETURN_EXPRESSION;
  5018. }
  5019. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5020. this.expressionsToBeDeoptimized.push(origin);
  5021. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5022. }, UNKNOWN_RETURN_EXPRESSION);
  5023. }
  5024. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5025. switch (interaction.type) {
  5026. case INTERACTION_ACCESSED: {
  5027. if (this.isReassigned)
  5028. return true;
  5029. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  5030. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5031. }
  5032. case INTERACTION_ASSIGNED: {
  5033. if (this.included)
  5034. return true;
  5035. if (path.length === 0)
  5036. return false;
  5037. if (this.isReassigned)
  5038. return true;
  5039. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  5040. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5041. }
  5042. case INTERACTION_CALLED: {
  5043. if (this.isReassigned)
  5044. return true;
  5045. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  5046. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5047. }
  5048. }
  5049. }
  5050. include() {
  5051. if (!this.included) {
  5052. super.include();
  5053. for (const declaration of this.declarations) {
  5054. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  5055. if (!declaration.included)
  5056. declaration.include(createInclusionContext(), false);
  5057. let node = declaration.parent;
  5058. while (!node.included) {
  5059. // We do not want to properly include parents in case they are part of a dead branch
  5060. // in which case .include() might pull in more dead code
  5061. node.included = true;
  5062. if (node.type === Program$1)
  5063. break;
  5064. node = node.parent;
  5065. }
  5066. }
  5067. }
  5068. }
  5069. includeCallArguments(context, parameters) {
  5070. if (this.isReassigned || context.includedCallArguments.has(this.init)) {
  5071. for (const argument of parameters) {
  5072. argument.include(context, false);
  5073. }
  5074. }
  5075. else {
  5076. context.includedCallArguments.add(this.init);
  5077. this.init.includeCallArguments(context, parameters);
  5078. context.includedCallArguments.delete(this.init);
  5079. }
  5080. }
  5081. markCalledFromTryStatement() {
  5082. this.calledFromTryStatement = true;
  5083. }
  5084. markInitializersForDeoptimization() {
  5085. if (this.additionalInitializers === null) {
  5086. this.additionalInitializers = [this.init];
  5087. this.init = UNKNOWN_EXPRESSION;
  5088. this.isReassigned = true;
  5089. }
  5090. return this.additionalInitializers;
  5091. }
  5092. }
  5093. const MAX_TRACKED_INTERACTIONS = 20;
  5094. const NO_INTERACTIONS = EMPTY_ARRAY;
  5095. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  5096. const EMPTY_PATH_TRACKER = new PathTracker();
  5097. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  5098. class ParameterVariable extends LocalVariable {
  5099. constructor(name, declarator, context) {
  5100. super(name, declarator, UNKNOWN_EXPRESSION, context, 'parameter');
  5101. this.deoptimizationInteractions = [];
  5102. this.deoptimizations = new PathTracker();
  5103. this.deoptimizedFields = new Set();
  5104. this.entitiesToBeDeoptimized = new Set();
  5105. }
  5106. addEntityToBeDeoptimized(entity) {
  5107. if (entity === UNKNOWN_EXPRESSION) {
  5108. // As unknown expressions fully deoptimize all interactions, we can clear
  5109. // the interaction cache at this point provided we keep this optimization
  5110. // in mind when adding new interactions
  5111. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5112. this.entitiesToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  5113. for (const { interaction } of this.deoptimizationInteractions) {
  5114. deoptimizeInteraction(interaction);
  5115. }
  5116. this.deoptimizationInteractions = NO_INTERACTIONS;
  5117. }
  5118. }
  5119. else if (this.deoptimizedFields.has(UnknownKey)) {
  5120. // This means that we already deoptimized all interactions and no longer
  5121. // track them
  5122. entity.deoptimizePath(UNKNOWN_PATH);
  5123. }
  5124. else if (!this.entitiesToBeDeoptimized.has(entity)) {
  5125. this.entitiesToBeDeoptimized.add(entity);
  5126. for (const field of this.deoptimizedFields) {
  5127. entity.deoptimizePath([field]);
  5128. }
  5129. for (const { interaction, path } of this.deoptimizationInteractions) {
  5130. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  5131. }
  5132. }
  5133. }
  5134. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  5135. // For performance reasons, we fully deoptimize all deeper interactions
  5136. if (path.length >= 2 ||
  5137. this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  5138. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  5139. (path.length === 1 &&
  5140. (this.deoptimizedFields.has(UnknownKey) ||
  5141. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0]))))) {
  5142. deoptimizeInteraction(interaction);
  5143. return;
  5144. }
  5145. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  5146. for (const entity of this.entitiesToBeDeoptimized) {
  5147. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  5148. }
  5149. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5150. this.deoptimizationInteractions.push({
  5151. interaction,
  5152. path
  5153. });
  5154. }
  5155. }
  5156. }
  5157. deoptimizePath(path) {
  5158. if (path.length === 0 || this.deoptimizedFields.has(UnknownKey)) {
  5159. return;
  5160. }
  5161. const key = path[0];
  5162. if (this.deoptimizedFields.has(key)) {
  5163. return;
  5164. }
  5165. this.deoptimizedFields.add(key);
  5166. for (const entity of this.entitiesToBeDeoptimized) {
  5167. // We do not need a recursion tracker here as we already track whether
  5168. // this field is deoptimized
  5169. entity.deoptimizePath([key]);
  5170. }
  5171. if (key === UnknownKey) {
  5172. // save some memory
  5173. this.deoptimizationInteractions = NO_INTERACTIONS;
  5174. this.deoptimizations = EMPTY_PATH_TRACKER;
  5175. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  5176. this.entitiesToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  5177. }
  5178. }
  5179. getReturnExpressionWhenCalledAtPath(path) {
  5180. // We deoptimize everything that is called as that will trivially deoptimize
  5181. // the corresponding return expressions as well and avoid badly performing
  5182. // and complicated alternatives
  5183. if (path.length === 0) {
  5184. this.deoptimizePath(UNKNOWN_PATH);
  5185. }
  5186. else if (!this.deoptimizedFields.has(path[0])) {
  5187. this.deoptimizePath([path[0]]);
  5188. }
  5189. return UNKNOWN_RETURN_EXPRESSION;
  5190. }
  5191. }
  5192. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  5193. const base = 64;
  5194. function toBase64(value) {
  5195. let outString = '';
  5196. do {
  5197. const currentDigit = value % base;
  5198. value = (value / base) | 0;
  5199. outString = chars[currentDigit] + outString;
  5200. } while (value !== 0);
  5201. return outString;
  5202. }
  5203. function getSafeName(baseName, usedNames, forbiddenNames) {
  5204. let safeName = baseName;
  5205. let count = 1;
  5206. while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
  5207. safeName = `${baseName}$${toBase64(count++)}`;
  5208. }
  5209. usedNames.add(safeName);
  5210. return safeName;
  5211. }
  5212. class Scope {
  5213. constructor() {
  5214. this.children = [];
  5215. this.variables = new Map();
  5216. }
  5217. /*
  5218. Redeclaration rules:
  5219. - var can redeclare var
  5220. - in function scopes, function and var can redeclare function and var
  5221. - var is hoisted across scopes, function remains in the scope it is declared
  5222. - var and function can redeclare function parameters, but parameters cannot redeclare parameters
  5223. - function cannot redeclare catch scope parameters
  5224. - var can redeclare catch scope parameters in a way
  5225. - if the parameter is an identifier and not a pattern
  5226. - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
  5227. - const, let, class, and function except in the cases above cannot redeclare anything
  5228. */
  5229. addDeclaration(identifier, context, init, kind) {
  5230. const name = identifier.name;
  5231. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5232. if (existingVariable) {
  5233. const existingKind = existingVariable.kind;
  5234. if (kind === 'var' && existingKind === 'var') {
  5235. existingVariable.addDeclaration(identifier, init);
  5236. return existingVariable;
  5237. }
  5238. context.error(logRedeclarationError(name), identifier.start);
  5239. }
  5240. const newVariable = new LocalVariable(identifier.name, identifier, init, context, kind);
  5241. this.variables.set(name, newVariable);
  5242. return newVariable;
  5243. }
  5244. addHoistedVariable(name, variable) {
  5245. (this.hoistedVariables ||= new Map()).set(name, variable);
  5246. }
  5247. contains(name) {
  5248. return this.variables.has(name);
  5249. }
  5250. findVariable(_name) {
  5251. /* istanbul ignore next */
  5252. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  5253. }
  5254. }
  5255. class ChildScope extends Scope {
  5256. constructor(parent, context) {
  5257. super();
  5258. this.parent = parent;
  5259. this.context = context;
  5260. this.accessedOutsideVariables = new Map();
  5261. parent.children.push(this);
  5262. }
  5263. addAccessedDynamicImport(importExpression) {
  5264. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  5265. if (this.parent instanceof ChildScope) {
  5266. this.parent.addAccessedDynamicImport(importExpression);
  5267. }
  5268. }
  5269. addAccessedGlobals(globals, accessedGlobalsByScope) {
  5270. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  5271. for (const name of globals) {
  5272. accessedGlobals.add(name);
  5273. }
  5274. accessedGlobalsByScope.set(this, accessedGlobals);
  5275. if (this.parent instanceof ChildScope) {
  5276. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  5277. }
  5278. }
  5279. addNamespaceMemberAccess(name, variable) {
  5280. this.accessedOutsideVariables.set(name, variable);
  5281. this.parent.addNamespaceMemberAccess(name, variable);
  5282. }
  5283. addReturnExpression(expression) {
  5284. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  5285. }
  5286. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  5287. for (const variable of this.accessedOutsideVariables.values()) {
  5288. if (variable.included) {
  5289. usedNames.add(variable.getBaseVariableName());
  5290. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5291. usedNames.add('exports');
  5292. }
  5293. }
  5294. }
  5295. const accessedGlobals = accessedGlobalsByScope.get(this);
  5296. if (accessedGlobals) {
  5297. for (const name of accessedGlobals) {
  5298. usedNames.add(name);
  5299. }
  5300. }
  5301. }
  5302. contains(name) {
  5303. return this.variables.has(name) || this.parent.contains(name);
  5304. }
  5305. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  5306. const usedNames = new Set();
  5307. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  5308. if (this.accessedDynamicImports) {
  5309. for (const importExpression of this.accessedDynamicImports) {
  5310. if (importExpression.inlineNamespace) {
  5311. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  5312. }
  5313. }
  5314. }
  5315. for (const [name, variable] of this.variables) {
  5316. if (variable.included || variable.alwaysRendered) {
  5317. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  5318. }
  5319. }
  5320. for (const scope of this.children) {
  5321. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  5322. }
  5323. }
  5324. findLexicalBoundary() {
  5325. return this.parent.findLexicalBoundary();
  5326. }
  5327. findVariable(name) {
  5328. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  5329. if (knownVariable) {
  5330. return knownVariable;
  5331. }
  5332. const variable = this.parent.findVariable(name);
  5333. this.accessedOutsideVariables.set(name, variable);
  5334. return variable;
  5335. }
  5336. }
  5337. class CatchBodyScope extends ChildScope {
  5338. constructor(parent) {
  5339. super(parent, parent.context);
  5340. this.parent = parent;
  5341. }
  5342. addDeclaration(identifier, context, init, kind) {
  5343. if (kind === 'var') {
  5344. const name = identifier.name;
  5345. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5346. if (existingVariable) {
  5347. const existingKind = existingVariable.kind;
  5348. if (existingKind === 'parameter' &&
  5349. // If this is a destructured parameter, it is forbidden to redeclare
  5350. existingVariable.declarations[0].parent.type === CatchClause$1) {
  5351. // If this is a var with the same name as the catch scope parameter,
  5352. // the assignment actually goes to the parameter and the var is
  5353. // hoisted without assignment. Locally, it is shadowed by the
  5354. // parameter
  5355. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, kind);
  5356. // To avoid the need to rewrite the declaration, we link the variable
  5357. // names. If we ever implement a logic that splits initialization and
  5358. // assignment for hoisted vars, the "renderLikeHoisted" logic can be
  5359. // removed again.
  5360. // We do not need to check whether there already is a linked
  5361. // variable because then declaredVariable would be that linked
  5362. // variable.
  5363. existingVariable.renderLikeHoisted(declaredVariable);
  5364. this.addHoistedVariable(name, declaredVariable);
  5365. return declaredVariable;
  5366. }
  5367. if (existingKind === 'var') {
  5368. existingVariable.addDeclaration(identifier, init);
  5369. return existingVariable;
  5370. }
  5371. return context.error(logRedeclarationError(name), identifier.start);
  5372. }
  5373. // We only add parameters to parameter scopes
  5374. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, init, kind);
  5375. // Necessary to make sure the init is deoptimized for conditional declarations.
  5376. // We cannot call deoptimizePath here.
  5377. declaredVariable.markInitializersForDeoptimization();
  5378. // We add the variable to this and all parent scopes to reliably detect conflicts
  5379. this.addHoistedVariable(name, declaredVariable);
  5380. return declaredVariable;
  5381. }
  5382. return super.addDeclaration(identifier, context, init, kind);
  5383. }
  5384. }
  5385. class FunctionBodyScope extends ChildScope {
  5386. constructor(parent) {
  5387. super(parent, parent.context);
  5388. }
  5389. // There is stuff that is only allowed in function scopes, i.e. functions can
  5390. // be redeclared, functions and var can redeclare each other
  5391. addDeclaration(identifier, context, init, kind) {
  5392. const name = identifier.name;
  5393. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5394. if (existingVariable) {
  5395. const existingKind = existingVariable.kind;
  5396. if ((kind === 'var' || kind === 'function') &&
  5397. (existingKind === 'var' || existingKind === 'function' || existingKind === 'parameter')) {
  5398. existingVariable.addDeclaration(identifier, init);
  5399. return existingVariable;
  5400. }
  5401. context.error(logRedeclarationError(name), identifier.start);
  5402. }
  5403. const newVariable = new LocalVariable(identifier.name, identifier, init, context, kind);
  5404. this.variables.set(name, newVariable);
  5405. return newVariable;
  5406. }
  5407. }
  5408. class ParameterScope extends ChildScope {
  5409. constructor(parent, isCatchScope) {
  5410. super(parent, parent.context);
  5411. this.parameters = [];
  5412. this.hasRest = false;
  5413. this.bodyScope = isCatchScope ? new CatchBodyScope(this) : new FunctionBodyScope(this);
  5414. }
  5415. /**
  5416. * Adds a parameter to this scope. Parameters must be added in the correct
  5417. * order, i.e. from left to right.
  5418. */
  5419. addParameterDeclaration(identifier) {
  5420. const { name, start } = identifier;
  5421. const existingParameter = this.variables.get(name);
  5422. if (existingParameter) {
  5423. return this.context.error(logDuplicateArgumentNameError(name), start);
  5424. }
  5425. const variable = new ParameterVariable(name, identifier, this.context);
  5426. this.variables.set(name, variable);
  5427. // We also add it to the body scope to detect name conflicts with local
  5428. // variables. We still need the intermediate scope, though, as parameter
  5429. // defaults are NOT taken from the body scope but from the parameters or
  5430. // outside scope.
  5431. this.bodyScope.addHoistedVariable(name, variable);
  5432. return variable;
  5433. }
  5434. addParameterVariables(parameters, hasRest) {
  5435. this.parameters = parameters;
  5436. for (const parameterList of parameters) {
  5437. for (const parameter of parameterList) {
  5438. parameter.alwaysRendered = true;
  5439. }
  5440. }
  5441. this.hasRest = hasRest;
  5442. }
  5443. includeCallArguments(context, parameters) {
  5444. let calledFromTryStatement = false;
  5445. let argumentIncluded = false;
  5446. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  5447. for (const checkedArgument of parameters) {
  5448. if (checkedArgument instanceof SpreadElement) {
  5449. for (const argument of parameters) {
  5450. argument.include(context, false);
  5451. }
  5452. break;
  5453. }
  5454. }
  5455. for (let index = parameters.length - 1; index >= 0; index--) {
  5456. const parameterVariables = this.parameters[index] || restParameter;
  5457. const argument = parameters[index];
  5458. if (parameterVariables) {
  5459. calledFromTryStatement = false;
  5460. if (parameterVariables.length === 0) {
  5461. // handle empty destructuring
  5462. argumentIncluded = true;
  5463. }
  5464. else {
  5465. for (const variable of parameterVariables) {
  5466. if (variable.included) {
  5467. argumentIncluded = true;
  5468. }
  5469. if (variable.calledFromTryStatement) {
  5470. calledFromTryStatement = true;
  5471. }
  5472. }
  5473. }
  5474. }
  5475. if (!argumentIncluded && argument.shouldBeIncluded(context)) {
  5476. argumentIncluded = true;
  5477. }
  5478. if (argumentIncluded) {
  5479. argument.include(context, calledFromTryStatement);
  5480. }
  5481. }
  5482. }
  5483. }
  5484. class ReturnValueScope extends ParameterScope {
  5485. constructor() {
  5486. super(...arguments);
  5487. this.returnExpression = null;
  5488. this.returnExpressions = [];
  5489. }
  5490. addReturnExpression(expression) {
  5491. this.returnExpressions.push(expression);
  5492. }
  5493. getReturnExpression() {
  5494. if (this.returnExpression === null)
  5495. this.updateReturnExpression();
  5496. return this.returnExpression;
  5497. }
  5498. updateReturnExpression() {
  5499. if (this.returnExpressions.length === 1) {
  5500. this.returnExpression = this.returnExpressions[0];
  5501. }
  5502. else {
  5503. this.returnExpression = UNKNOWN_EXPRESSION;
  5504. for (const expression of this.returnExpressions) {
  5505. expression.deoptimizePath(UNKNOWN_PATH);
  5506. }
  5507. }
  5508. }
  5509. }
  5510. /** @typedef { import('estree').Node} Node */
  5511. /** @typedef {Node | {
  5512. * type: 'PropertyDefinition';
  5513. * computed: boolean;
  5514. * value: Node
  5515. * }} NodeWithPropertyDefinition */
  5516. /**
  5517. *
  5518. * @param {NodeWithPropertyDefinition} node
  5519. * @param {NodeWithPropertyDefinition} parent
  5520. * @returns {boolean}
  5521. */
  5522. function is_reference (node, parent) {
  5523. if (node.type === 'MemberExpression') {
  5524. return !node.computed && is_reference(node.object, node);
  5525. }
  5526. if (node.type === 'Identifier') {
  5527. if (!parent) return true;
  5528. switch (parent.type) {
  5529. // disregard `bar` in `foo.bar`
  5530. case 'MemberExpression': return parent.computed || node === parent.object;
  5531. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  5532. case 'MethodDefinition': return parent.computed;
  5533. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  5534. case 'PropertyDefinition': return parent.computed || node === parent.value;
  5535. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  5536. case 'Property': return parent.computed || node === parent.value;
  5537. // disregard the `bar` in `export { foo as bar }` or
  5538. // the foo in `import { foo as bar }`
  5539. case 'ExportSpecifier':
  5540. case 'ImportSpecifier': return node === parent.local;
  5541. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  5542. case 'LabeledStatement':
  5543. case 'BreakStatement':
  5544. case 'ContinueStatement': return false;
  5545. default: return true;
  5546. }
  5547. }
  5548. return false;
  5549. }
  5550. const PureFunctionKey = Symbol('PureFunction');
  5551. const getPureFunctions = ({ treeshake }) => {
  5552. const pureFunctions = Object.create(null);
  5553. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  5554. let currentFunctions = pureFunctions;
  5555. for (const pathSegment of functionName.split('.')) {
  5556. currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
  5557. }
  5558. currentFunctions[PureFunctionKey] = true;
  5559. }
  5560. return pureFunctions;
  5561. };
  5562. const doNothing = () => { };
  5563. /* eslint sort-keys: "off" */
  5564. const ValueProperties = Symbol('Value Properties');
  5565. const getTruthyLiteralValue = () => UnknownTruthyValue;
  5566. const returnFalse = () => false;
  5567. const returnTrue = () => true;
  5568. const PURE = {
  5569. deoptimizeArgumentsOnCall: doNothing,
  5570. getLiteralValue: getTruthyLiteralValue,
  5571. hasEffectsWhenCalled: returnFalse
  5572. };
  5573. const IMPURE = {
  5574. deoptimizeArgumentsOnCall: doNothing,
  5575. getLiteralValue: getTruthyLiteralValue,
  5576. hasEffectsWhenCalled: returnTrue
  5577. };
  5578. const PURE_WITH_ARRAY = {
  5579. deoptimizeArgumentsOnCall: doNothing,
  5580. getLiteralValue: getTruthyLiteralValue,
  5581. hasEffectsWhenCalled({ args }) {
  5582. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  5583. }
  5584. };
  5585. const GETTER_ACCESS = {
  5586. deoptimizeArgumentsOnCall: doNothing,
  5587. getLiteralValue: getTruthyLiteralValue,
  5588. hasEffectsWhenCalled({ args }, context) {
  5589. const [_thisArgument, firstArgument] = args;
  5590. return (!(firstArgument instanceof ExpressionEntity) ||
  5591. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  5592. }
  5593. };
  5594. // We use shortened variables to reduce file size here
  5595. /* OBJECT */
  5596. const O = {
  5597. __proto__: null,
  5598. [ValueProperties]: IMPURE
  5599. };
  5600. /* PURE FUNCTION */
  5601. const PF = {
  5602. __proto__: null,
  5603. [ValueProperties]: PURE
  5604. };
  5605. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  5606. const PF_NO_GETTER = {
  5607. __proto__: null,
  5608. [ValueProperties]: GETTER_ACCESS
  5609. };
  5610. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  5611. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  5612. __proto__: null,
  5613. [ValueProperties]: {
  5614. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  5615. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  5616. },
  5617. getLiteralValue: getTruthyLiteralValue,
  5618. hasEffectsWhenCalled({ args }, context) {
  5619. return (args.length <= 1 ||
  5620. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  5621. }
  5622. }
  5623. };
  5624. /* CONSTRUCTOR */
  5625. const C = {
  5626. __proto__: null,
  5627. [ValueProperties]: IMPURE,
  5628. prototype: O
  5629. };
  5630. /* PURE CONSTRUCTOR */
  5631. const PC = {
  5632. __proto__: null,
  5633. [ValueProperties]: PURE,
  5634. prototype: O
  5635. };
  5636. const PC_WITH_ARRAY = {
  5637. __proto__: null,
  5638. [ValueProperties]: PURE_WITH_ARRAY,
  5639. prototype: O
  5640. };
  5641. const ARRAY_TYPE = {
  5642. __proto__: null,
  5643. [ValueProperties]: PURE,
  5644. from: O,
  5645. of: PF,
  5646. prototype: O
  5647. };
  5648. const INTL_MEMBER = {
  5649. __proto__: null,
  5650. [ValueProperties]: PURE,
  5651. supportedLocalesOf: PC
  5652. };
  5653. const knownGlobals = {
  5654. // Placeholders for global objects to avoid shape mutations
  5655. global: O,
  5656. globalThis: O,
  5657. self: O,
  5658. window: O,
  5659. // Common globals
  5660. __proto__: null,
  5661. [ValueProperties]: IMPURE,
  5662. Array: {
  5663. __proto__: null,
  5664. [ValueProperties]: IMPURE,
  5665. from: O,
  5666. isArray: PF,
  5667. of: PF,
  5668. prototype: O
  5669. },
  5670. ArrayBuffer: {
  5671. __proto__: null,
  5672. [ValueProperties]: PURE,
  5673. isView: PF,
  5674. prototype: O
  5675. },
  5676. Atomics: O,
  5677. BigInt: C,
  5678. BigInt64Array: C,
  5679. BigUint64Array: C,
  5680. Boolean: PC,
  5681. constructor: C,
  5682. DataView: PC,
  5683. Date: {
  5684. __proto__: null,
  5685. [ValueProperties]: PURE,
  5686. now: PF,
  5687. parse: PF,
  5688. prototype: O,
  5689. UTC: PF
  5690. },
  5691. decodeURI: PF,
  5692. decodeURIComponent: PF,
  5693. encodeURI: PF,
  5694. encodeURIComponent: PF,
  5695. Error: PC,
  5696. escape: PF,
  5697. eval: O,
  5698. EvalError: PC,
  5699. Float32Array: ARRAY_TYPE,
  5700. Float64Array: ARRAY_TYPE,
  5701. Function: C,
  5702. hasOwnProperty: O,
  5703. Infinity: O,
  5704. Int16Array: ARRAY_TYPE,
  5705. Int32Array: ARRAY_TYPE,
  5706. Int8Array: ARRAY_TYPE,
  5707. isFinite: PF,
  5708. isNaN: PF,
  5709. isPrototypeOf: O,
  5710. JSON: O,
  5711. Map: PC_WITH_ARRAY,
  5712. Math: {
  5713. __proto__: null,
  5714. [ValueProperties]: IMPURE,
  5715. abs: PF,
  5716. acos: PF,
  5717. acosh: PF,
  5718. asin: PF,
  5719. asinh: PF,
  5720. atan: PF,
  5721. atan2: PF,
  5722. atanh: PF,
  5723. cbrt: PF,
  5724. ceil: PF,
  5725. clz32: PF,
  5726. cos: PF,
  5727. cosh: PF,
  5728. exp: PF,
  5729. expm1: PF,
  5730. floor: PF,
  5731. fround: PF,
  5732. hypot: PF,
  5733. imul: PF,
  5734. log: PF,
  5735. log10: PF,
  5736. log1p: PF,
  5737. log2: PF,
  5738. max: PF,
  5739. min: PF,
  5740. pow: PF,
  5741. random: PF,
  5742. round: PF,
  5743. sign: PF,
  5744. sin: PF,
  5745. sinh: PF,
  5746. sqrt: PF,
  5747. tan: PF,
  5748. tanh: PF,
  5749. trunc: PF
  5750. },
  5751. NaN: O,
  5752. Number: {
  5753. __proto__: null,
  5754. [ValueProperties]: PURE,
  5755. isFinite: PF,
  5756. isInteger: PF,
  5757. isNaN: PF,
  5758. isSafeInteger: PF,
  5759. parseFloat: PF,
  5760. parseInt: PF,
  5761. prototype: O
  5762. },
  5763. Object: {
  5764. __proto__: null,
  5765. [ValueProperties]: PURE,
  5766. create: PF,
  5767. // Technically those can throw in certain situations, but we ignore this as
  5768. // code that relies on this will hopefully wrap this in a try-catch, which
  5769. // deoptimizes everything anyway
  5770. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  5771. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  5772. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  5773. getOwnPropertyDescriptor: PF,
  5774. getOwnPropertyDescriptors: PF,
  5775. getOwnPropertyNames: PF,
  5776. getOwnPropertySymbols: PF,
  5777. getPrototypeOf: PF,
  5778. hasOwn: PF,
  5779. is: PF,
  5780. isExtensible: PF,
  5781. isFrozen: PF,
  5782. isSealed: PF,
  5783. keys: PF,
  5784. fromEntries: O,
  5785. entries: PF_NO_GETTER,
  5786. values: PF_NO_GETTER,
  5787. prototype: O
  5788. },
  5789. parseFloat: PF,
  5790. parseInt: PF,
  5791. Promise: {
  5792. __proto__: null,
  5793. [ValueProperties]: IMPURE,
  5794. all: O,
  5795. allSettled: O,
  5796. any: O,
  5797. prototype: O,
  5798. race: O,
  5799. reject: O,
  5800. resolve: O
  5801. },
  5802. propertyIsEnumerable: O,
  5803. Proxy: O,
  5804. RangeError: PC,
  5805. ReferenceError: PC,
  5806. Reflect: O,
  5807. RegExp: PC,
  5808. Set: PC_WITH_ARRAY,
  5809. SharedArrayBuffer: C,
  5810. String: {
  5811. __proto__: null,
  5812. [ValueProperties]: PURE,
  5813. fromCharCode: PF,
  5814. fromCodePoint: PF,
  5815. prototype: O,
  5816. raw: PF
  5817. },
  5818. Symbol: {
  5819. __proto__: null,
  5820. [ValueProperties]: PURE,
  5821. for: PF,
  5822. keyFor: PF,
  5823. prototype: O,
  5824. toStringTag: {
  5825. __proto__: null,
  5826. [ValueProperties]: {
  5827. deoptimizeArgumentsOnCall: doNothing,
  5828. getLiteralValue() {
  5829. return SymbolToStringTag;
  5830. },
  5831. hasEffectsWhenCalled: returnTrue
  5832. }
  5833. }
  5834. },
  5835. SyntaxError: PC,
  5836. toLocaleString: O,
  5837. toString: O,
  5838. TypeError: PC,
  5839. Uint16Array: ARRAY_TYPE,
  5840. Uint32Array: ARRAY_TYPE,
  5841. Uint8Array: ARRAY_TYPE,
  5842. Uint8ClampedArray: ARRAY_TYPE,
  5843. // Technically, this is a global, but it needs special handling
  5844. // undefined: ?,
  5845. unescape: PF,
  5846. URIError: PC,
  5847. valueOf: O,
  5848. WeakMap: PC_WITH_ARRAY,
  5849. WeakSet: PC_WITH_ARRAY,
  5850. // Additional globals shared by Node and Browser that are not strictly part of the language
  5851. clearInterval: C,
  5852. clearTimeout: C,
  5853. console: {
  5854. __proto__: null,
  5855. [ValueProperties]: IMPURE,
  5856. assert: C,
  5857. clear: C,
  5858. count: C,
  5859. countReset: C,
  5860. debug: C,
  5861. dir: C,
  5862. dirxml: C,
  5863. error: C,
  5864. exception: C,
  5865. group: C,
  5866. groupCollapsed: C,
  5867. groupEnd: C,
  5868. info: C,
  5869. log: C,
  5870. table: C,
  5871. time: C,
  5872. timeEnd: C,
  5873. timeLog: C,
  5874. trace: C,
  5875. warn: C
  5876. },
  5877. Intl: {
  5878. __proto__: null,
  5879. [ValueProperties]: IMPURE,
  5880. Collator: INTL_MEMBER,
  5881. DateTimeFormat: INTL_MEMBER,
  5882. DisplayNames: INTL_MEMBER,
  5883. ListFormat: INTL_MEMBER,
  5884. Locale: INTL_MEMBER,
  5885. NumberFormat: INTL_MEMBER,
  5886. PluralRules: INTL_MEMBER,
  5887. RelativeTimeFormat: INTL_MEMBER,
  5888. Segmenter: INTL_MEMBER
  5889. },
  5890. setInterval: C,
  5891. setTimeout: C,
  5892. TextDecoder: C,
  5893. TextEncoder: C,
  5894. URL: {
  5895. __proto__: null,
  5896. [ValueProperties]: IMPURE,
  5897. prototype: O,
  5898. canParse: PF
  5899. },
  5900. URLSearchParams: C,
  5901. // Browser specific globals
  5902. AbortController: C,
  5903. AbortSignal: C,
  5904. addEventListener: O,
  5905. alert: O,
  5906. AnalyserNode: C,
  5907. Animation: C,
  5908. AnimationEvent: C,
  5909. applicationCache: O,
  5910. ApplicationCache: C,
  5911. ApplicationCacheErrorEvent: C,
  5912. atob: O,
  5913. Attr: C,
  5914. Audio: C,
  5915. AudioBuffer: C,
  5916. AudioBufferSourceNode: C,
  5917. AudioContext: C,
  5918. AudioDestinationNode: C,
  5919. AudioListener: C,
  5920. AudioNode: C,
  5921. AudioParam: C,
  5922. AudioProcessingEvent: C,
  5923. AudioScheduledSourceNode: C,
  5924. AudioWorkletNode: C,
  5925. BarProp: C,
  5926. BaseAudioContext: C,
  5927. BatteryManager: C,
  5928. BeforeUnloadEvent: C,
  5929. BiquadFilterNode: C,
  5930. Blob: C,
  5931. BlobEvent: C,
  5932. blur: O,
  5933. BroadcastChannel: C,
  5934. btoa: O,
  5935. ByteLengthQueuingStrategy: C,
  5936. Cache: C,
  5937. caches: O,
  5938. CacheStorage: C,
  5939. cancelAnimationFrame: O,
  5940. cancelIdleCallback: O,
  5941. CanvasCaptureMediaStreamTrack: C,
  5942. CanvasGradient: C,
  5943. CanvasPattern: C,
  5944. CanvasRenderingContext2D: C,
  5945. ChannelMergerNode: C,
  5946. ChannelSplitterNode: C,
  5947. CharacterData: C,
  5948. clientInformation: O,
  5949. ClipboardEvent: C,
  5950. close: O,
  5951. closed: O,
  5952. CloseEvent: C,
  5953. Comment: C,
  5954. CompositionEvent: C,
  5955. confirm: O,
  5956. ConstantSourceNode: C,
  5957. ConvolverNode: C,
  5958. CountQueuingStrategy: C,
  5959. createImageBitmap: O,
  5960. Credential: C,
  5961. CredentialsContainer: C,
  5962. crypto: O,
  5963. Crypto: C,
  5964. CryptoKey: C,
  5965. CSS: C,
  5966. CSSConditionRule: C,
  5967. CSSFontFaceRule: C,
  5968. CSSGroupingRule: C,
  5969. CSSImportRule: C,
  5970. CSSKeyframeRule: C,
  5971. CSSKeyframesRule: C,
  5972. CSSMediaRule: C,
  5973. CSSNamespaceRule: C,
  5974. CSSPageRule: C,
  5975. CSSRule: C,
  5976. CSSRuleList: C,
  5977. CSSStyleDeclaration: C,
  5978. CSSStyleRule: C,
  5979. CSSStyleSheet: C,
  5980. CSSSupportsRule: C,
  5981. CustomElementRegistry: C,
  5982. customElements: O,
  5983. CustomEvent: {
  5984. __proto__: null,
  5985. [ValueProperties]: {
  5986. deoptimizeArgumentsOnCall({ args }) {
  5987. args[2]?.deoptimizePath(['detail']);
  5988. },
  5989. getLiteralValue: getTruthyLiteralValue,
  5990. hasEffectsWhenCalled: returnFalse
  5991. },
  5992. prototype: O
  5993. },
  5994. DataTransfer: C,
  5995. DataTransferItem: C,
  5996. DataTransferItemList: C,
  5997. defaultstatus: O,
  5998. defaultStatus: O,
  5999. DelayNode: C,
  6000. DeviceMotionEvent: C,
  6001. DeviceOrientationEvent: C,
  6002. devicePixelRatio: O,
  6003. dispatchEvent: O,
  6004. document: O,
  6005. Document: C,
  6006. DocumentFragment: C,
  6007. DocumentType: C,
  6008. DOMError: C,
  6009. DOMException: C,
  6010. DOMImplementation: C,
  6011. DOMMatrix: C,
  6012. DOMMatrixReadOnly: C,
  6013. DOMParser: C,
  6014. DOMPoint: C,
  6015. DOMPointReadOnly: C,
  6016. DOMQuad: C,
  6017. DOMRect: C,
  6018. DOMRectReadOnly: C,
  6019. DOMStringList: C,
  6020. DOMStringMap: C,
  6021. DOMTokenList: C,
  6022. DragEvent: C,
  6023. DynamicsCompressorNode: C,
  6024. Element: C,
  6025. ErrorEvent: C,
  6026. Event: C,
  6027. EventSource: C,
  6028. EventTarget: C,
  6029. external: O,
  6030. fetch: O,
  6031. File: C,
  6032. FileList: C,
  6033. FileReader: C,
  6034. find: O,
  6035. focus: O,
  6036. FocusEvent: C,
  6037. FontFace: C,
  6038. FontFaceSetLoadEvent: C,
  6039. FormData: C,
  6040. frames: O,
  6041. GainNode: C,
  6042. Gamepad: C,
  6043. GamepadButton: C,
  6044. GamepadEvent: C,
  6045. getComputedStyle: O,
  6046. getSelection: O,
  6047. HashChangeEvent: C,
  6048. Headers: C,
  6049. history: O,
  6050. History: C,
  6051. HTMLAllCollection: C,
  6052. HTMLAnchorElement: C,
  6053. HTMLAreaElement: C,
  6054. HTMLAudioElement: C,
  6055. HTMLBaseElement: C,
  6056. HTMLBodyElement: C,
  6057. HTMLBRElement: C,
  6058. HTMLButtonElement: C,
  6059. HTMLCanvasElement: C,
  6060. HTMLCollection: C,
  6061. HTMLContentElement: C,
  6062. HTMLDataElement: C,
  6063. HTMLDataListElement: C,
  6064. HTMLDetailsElement: C,
  6065. HTMLDialogElement: C,
  6066. HTMLDirectoryElement: C,
  6067. HTMLDivElement: C,
  6068. HTMLDListElement: C,
  6069. HTMLDocument: C,
  6070. HTMLElement: C,
  6071. HTMLEmbedElement: C,
  6072. HTMLFieldSetElement: C,
  6073. HTMLFontElement: C,
  6074. HTMLFormControlsCollection: C,
  6075. HTMLFormElement: C,
  6076. HTMLFrameElement: C,
  6077. HTMLFrameSetElement: C,
  6078. HTMLHeadElement: C,
  6079. HTMLHeadingElement: C,
  6080. HTMLHRElement: C,
  6081. HTMLHtmlElement: C,
  6082. HTMLIFrameElement: C,
  6083. HTMLImageElement: C,
  6084. HTMLInputElement: C,
  6085. HTMLLabelElement: C,
  6086. HTMLLegendElement: C,
  6087. HTMLLIElement: C,
  6088. HTMLLinkElement: C,
  6089. HTMLMapElement: C,
  6090. HTMLMarqueeElement: C,
  6091. HTMLMediaElement: C,
  6092. HTMLMenuElement: C,
  6093. HTMLMetaElement: C,
  6094. HTMLMeterElement: C,
  6095. HTMLModElement: C,
  6096. HTMLObjectElement: C,
  6097. HTMLOListElement: C,
  6098. HTMLOptGroupElement: C,
  6099. HTMLOptionElement: C,
  6100. HTMLOptionsCollection: C,
  6101. HTMLOutputElement: C,
  6102. HTMLParagraphElement: C,
  6103. HTMLParamElement: C,
  6104. HTMLPictureElement: C,
  6105. HTMLPreElement: C,
  6106. HTMLProgressElement: C,
  6107. HTMLQuoteElement: C,
  6108. HTMLScriptElement: C,
  6109. HTMLSelectElement: C,
  6110. HTMLShadowElement: C,
  6111. HTMLSlotElement: C,
  6112. HTMLSourceElement: C,
  6113. HTMLSpanElement: C,
  6114. HTMLStyleElement: C,
  6115. HTMLTableCaptionElement: C,
  6116. HTMLTableCellElement: C,
  6117. HTMLTableColElement: C,
  6118. HTMLTableElement: C,
  6119. HTMLTableRowElement: C,
  6120. HTMLTableSectionElement: C,
  6121. HTMLTemplateElement: C,
  6122. HTMLTextAreaElement: C,
  6123. HTMLTimeElement: C,
  6124. HTMLTitleElement: C,
  6125. HTMLTrackElement: C,
  6126. HTMLUListElement: C,
  6127. HTMLUnknownElement: C,
  6128. HTMLVideoElement: C,
  6129. IDBCursor: C,
  6130. IDBCursorWithValue: C,
  6131. IDBDatabase: C,
  6132. IDBFactory: C,
  6133. IDBIndex: C,
  6134. IDBKeyRange: C,
  6135. IDBObjectStore: C,
  6136. IDBOpenDBRequest: C,
  6137. IDBRequest: C,
  6138. IDBTransaction: C,
  6139. IDBVersionChangeEvent: C,
  6140. IdleDeadline: C,
  6141. IIRFilterNode: C,
  6142. Image: C,
  6143. ImageBitmap: C,
  6144. ImageBitmapRenderingContext: C,
  6145. ImageCapture: C,
  6146. ImageData: C,
  6147. indexedDB: O,
  6148. innerHeight: O,
  6149. innerWidth: O,
  6150. InputEvent: C,
  6151. IntersectionObserver: C,
  6152. IntersectionObserverEntry: C,
  6153. isSecureContext: O,
  6154. KeyboardEvent: C,
  6155. KeyframeEffect: C,
  6156. length: O,
  6157. localStorage: O,
  6158. location: O,
  6159. Location: C,
  6160. locationbar: O,
  6161. matchMedia: O,
  6162. MediaDeviceInfo: C,
  6163. MediaDevices: C,
  6164. MediaElementAudioSourceNode: C,
  6165. MediaEncryptedEvent: C,
  6166. MediaError: C,
  6167. MediaKeyMessageEvent: C,
  6168. MediaKeySession: C,
  6169. MediaKeyStatusMap: C,
  6170. MediaKeySystemAccess: C,
  6171. MediaList: C,
  6172. MediaQueryList: C,
  6173. MediaQueryListEvent: C,
  6174. MediaRecorder: C,
  6175. MediaSettingsRange: C,
  6176. MediaSource: C,
  6177. MediaStream: C,
  6178. MediaStreamAudioDestinationNode: C,
  6179. MediaStreamAudioSourceNode: C,
  6180. MediaStreamEvent: C,
  6181. MediaStreamTrack: C,
  6182. MediaStreamTrackEvent: C,
  6183. menubar: O,
  6184. MessageChannel: C,
  6185. MessageEvent: C,
  6186. MessagePort: C,
  6187. MIDIAccess: C,
  6188. MIDIConnectionEvent: C,
  6189. MIDIInput: C,
  6190. MIDIInputMap: C,
  6191. MIDIMessageEvent: C,
  6192. MIDIOutput: C,
  6193. MIDIOutputMap: C,
  6194. MIDIPort: C,
  6195. MimeType: C,
  6196. MimeTypeArray: C,
  6197. MouseEvent: C,
  6198. moveBy: O,
  6199. moveTo: O,
  6200. MutationEvent: C,
  6201. MutationObserver: C,
  6202. MutationRecord: C,
  6203. name: O,
  6204. NamedNodeMap: C,
  6205. NavigationPreloadManager: C,
  6206. navigator: O,
  6207. Navigator: C,
  6208. NetworkInformation: C,
  6209. Node: C,
  6210. NodeFilter: O,
  6211. NodeIterator: C,
  6212. NodeList: C,
  6213. Notification: C,
  6214. OfflineAudioCompletionEvent: C,
  6215. OfflineAudioContext: C,
  6216. offscreenBuffering: O,
  6217. OffscreenCanvas: C,
  6218. open: O,
  6219. openDatabase: O,
  6220. Option: C,
  6221. origin: O,
  6222. OscillatorNode: C,
  6223. outerHeight: O,
  6224. outerWidth: O,
  6225. PageTransitionEvent: C,
  6226. pageXOffset: O,
  6227. pageYOffset: O,
  6228. PannerNode: C,
  6229. parent: O,
  6230. Path2D: C,
  6231. PaymentAddress: C,
  6232. PaymentRequest: C,
  6233. PaymentRequestUpdateEvent: C,
  6234. PaymentResponse: C,
  6235. performance: O,
  6236. Performance: C,
  6237. PerformanceEntry: C,
  6238. PerformanceLongTaskTiming: C,
  6239. PerformanceMark: C,
  6240. PerformanceMeasure: C,
  6241. PerformanceNavigation: C,
  6242. PerformanceNavigationTiming: C,
  6243. PerformanceObserver: C,
  6244. PerformanceObserverEntryList: C,
  6245. PerformancePaintTiming: C,
  6246. PerformanceResourceTiming: C,
  6247. PerformanceTiming: C,
  6248. PeriodicWave: C,
  6249. Permissions: C,
  6250. PermissionStatus: C,
  6251. personalbar: O,
  6252. PhotoCapabilities: C,
  6253. Plugin: C,
  6254. PluginArray: C,
  6255. PointerEvent: C,
  6256. PopStateEvent: C,
  6257. postMessage: O,
  6258. Presentation: C,
  6259. PresentationAvailability: C,
  6260. PresentationConnection: C,
  6261. PresentationConnectionAvailableEvent: C,
  6262. PresentationConnectionCloseEvent: C,
  6263. PresentationConnectionList: C,
  6264. PresentationReceiver: C,
  6265. PresentationRequest: C,
  6266. print: O,
  6267. ProcessingInstruction: C,
  6268. ProgressEvent: C,
  6269. PromiseRejectionEvent: C,
  6270. prompt: O,
  6271. PushManager: C,
  6272. PushSubscription: C,
  6273. PushSubscriptionOptions: C,
  6274. queueMicrotask: O,
  6275. RadioNodeList: C,
  6276. Range: C,
  6277. ReadableStream: C,
  6278. RemotePlayback: C,
  6279. removeEventListener: O,
  6280. Request: C,
  6281. requestAnimationFrame: O,
  6282. requestIdleCallback: O,
  6283. resizeBy: O,
  6284. ResizeObserver: C,
  6285. ResizeObserverEntry: C,
  6286. resizeTo: O,
  6287. Response: C,
  6288. RTCCertificate: C,
  6289. RTCDataChannel: C,
  6290. RTCDataChannelEvent: C,
  6291. RTCDtlsTransport: C,
  6292. RTCIceCandidate: C,
  6293. RTCIceTransport: C,
  6294. RTCPeerConnection: C,
  6295. RTCPeerConnectionIceEvent: C,
  6296. RTCRtpReceiver: C,
  6297. RTCRtpSender: C,
  6298. RTCSctpTransport: C,
  6299. RTCSessionDescription: C,
  6300. RTCStatsReport: C,
  6301. RTCTrackEvent: C,
  6302. screen: O,
  6303. Screen: C,
  6304. screenLeft: O,
  6305. ScreenOrientation: C,
  6306. screenTop: O,
  6307. screenX: O,
  6308. screenY: O,
  6309. ScriptProcessorNode: C,
  6310. scroll: O,
  6311. scrollbars: O,
  6312. scrollBy: O,
  6313. scrollTo: O,
  6314. scrollX: O,
  6315. scrollY: O,
  6316. SecurityPolicyViolationEvent: C,
  6317. Selection: C,
  6318. ServiceWorker: C,
  6319. ServiceWorkerContainer: C,
  6320. ServiceWorkerRegistration: C,
  6321. sessionStorage: O,
  6322. ShadowRoot: C,
  6323. SharedWorker: C,
  6324. SourceBuffer: C,
  6325. SourceBufferList: C,
  6326. speechSynthesis: O,
  6327. SpeechSynthesisEvent: C,
  6328. SpeechSynthesisUtterance: C,
  6329. StaticRange: C,
  6330. status: O,
  6331. statusbar: O,
  6332. StereoPannerNode: C,
  6333. stop: O,
  6334. Storage: C,
  6335. StorageEvent: C,
  6336. StorageManager: C,
  6337. styleMedia: O,
  6338. StyleSheet: C,
  6339. StyleSheetList: C,
  6340. SubtleCrypto: C,
  6341. SVGAElement: C,
  6342. SVGAngle: C,
  6343. SVGAnimatedAngle: C,
  6344. SVGAnimatedBoolean: C,
  6345. SVGAnimatedEnumeration: C,
  6346. SVGAnimatedInteger: C,
  6347. SVGAnimatedLength: C,
  6348. SVGAnimatedLengthList: C,
  6349. SVGAnimatedNumber: C,
  6350. SVGAnimatedNumberList: C,
  6351. SVGAnimatedPreserveAspectRatio: C,
  6352. SVGAnimatedRect: C,
  6353. SVGAnimatedString: C,
  6354. SVGAnimatedTransformList: C,
  6355. SVGAnimateElement: C,
  6356. SVGAnimateMotionElement: C,
  6357. SVGAnimateTransformElement: C,
  6358. SVGAnimationElement: C,
  6359. SVGCircleElement: C,
  6360. SVGClipPathElement: C,
  6361. SVGComponentTransferFunctionElement: C,
  6362. SVGDefsElement: C,
  6363. SVGDescElement: C,
  6364. SVGDiscardElement: C,
  6365. SVGElement: C,
  6366. SVGEllipseElement: C,
  6367. SVGFEBlendElement: C,
  6368. SVGFEColorMatrixElement: C,
  6369. SVGFEComponentTransferElement: C,
  6370. SVGFECompositeElement: C,
  6371. SVGFEConvolveMatrixElement: C,
  6372. SVGFEDiffuseLightingElement: C,
  6373. SVGFEDisplacementMapElement: C,
  6374. SVGFEDistantLightElement: C,
  6375. SVGFEDropShadowElement: C,
  6376. SVGFEFloodElement: C,
  6377. SVGFEFuncAElement: C,
  6378. SVGFEFuncBElement: C,
  6379. SVGFEFuncGElement: C,
  6380. SVGFEFuncRElement: C,
  6381. SVGFEGaussianBlurElement: C,
  6382. SVGFEImageElement: C,
  6383. SVGFEMergeElement: C,
  6384. SVGFEMergeNodeElement: C,
  6385. SVGFEMorphologyElement: C,
  6386. SVGFEOffsetElement: C,
  6387. SVGFEPointLightElement: C,
  6388. SVGFESpecularLightingElement: C,
  6389. SVGFESpotLightElement: C,
  6390. SVGFETileElement: C,
  6391. SVGFETurbulenceElement: C,
  6392. SVGFilterElement: C,
  6393. SVGForeignObjectElement: C,
  6394. SVGGElement: C,
  6395. SVGGeometryElement: C,
  6396. SVGGradientElement: C,
  6397. SVGGraphicsElement: C,
  6398. SVGImageElement: C,
  6399. SVGLength: C,
  6400. SVGLengthList: C,
  6401. SVGLinearGradientElement: C,
  6402. SVGLineElement: C,
  6403. SVGMarkerElement: C,
  6404. SVGMaskElement: C,
  6405. SVGMatrix: C,
  6406. SVGMetadataElement: C,
  6407. SVGMPathElement: C,
  6408. SVGNumber: C,
  6409. SVGNumberList: C,
  6410. SVGPathElement: C,
  6411. SVGPatternElement: C,
  6412. SVGPoint: C,
  6413. SVGPointList: C,
  6414. SVGPolygonElement: C,
  6415. SVGPolylineElement: C,
  6416. SVGPreserveAspectRatio: C,
  6417. SVGRadialGradientElement: C,
  6418. SVGRect: C,
  6419. SVGRectElement: C,
  6420. SVGScriptElement: C,
  6421. SVGSetElement: C,
  6422. SVGStopElement: C,
  6423. SVGStringList: C,
  6424. SVGStyleElement: C,
  6425. SVGSVGElement: C,
  6426. SVGSwitchElement: C,
  6427. SVGSymbolElement: C,
  6428. SVGTextContentElement: C,
  6429. SVGTextElement: C,
  6430. SVGTextPathElement: C,
  6431. SVGTextPositioningElement: C,
  6432. SVGTitleElement: C,
  6433. SVGTransform: C,
  6434. SVGTransformList: C,
  6435. SVGTSpanElement: C,
  6436. SVGUnitTypes: C,
  6437. SVGUseElement: C,
  6438. SVGViewElement: C,
  6439. TaskAttributionTiming: C,
  6440. Text: C,
  6441. TextEvent: C,
  6442. TextMetrics: C,
  6443. TextTrack: C,
  6444. TextTrackCue: C,
  6445. TextTrackCueList: C,
  6446. TextTrackList: C,
  6447. TimeRanges: C,
  6448. toolbar: O,
  6449. top: O,
  6450. Touch: C,
  6451. TouchEvent: C,
  6452. TouchList: C,
  6453. TrackEvent: C,
  6454. TransitionEvent: C,
  6455. TreeWalker: C,
  6456. UIEvent: C,
  6457. ValidityState: C,
  6458. visualViewport: O,
  6459. VisualViewport: C,
  6460. VTTCue: C,
  6461. WaveShaperNode: C,
  6462. WebAssembly: O,
  6463. WebGL2RenderingContext: C,
  6464. WebGLActiveInfo: C,
  6465. WebGLBuffer: C,
  6466. WebGLContextEvent: C,
  6467. WebGLFramebuffer: C,
  6468. WebGLProgram: C,
  6469. WebGLQuery: C,
  6470. WebGLRenderbuffer: C,
  6471. WebGLRenderingContext: C,
  6472. WebGLSampler: C,
  6473. WebGLShader: C,
  6474. WebGLShaderPrecisionFormat: C,
  6475. WebGLSync: C,
  6476. WebGLTexture: C,
  6477. WebGLTransformFeedback: C,
  6478. WebGLUniformLocation: C,
  6479. WebGLVertexArrayObject: C,
  6480. WebSocket: C,
  6481. WheelEvent: C,
  6482. Window: C,
  6483. Worker: C,
  6484. WritableStream: C,
  6485. XMLDocument: C,
  6486. XMLHttpRequest: C,
  6487. XMLHttpRequestEventTarget: C,
  6488. XMLHttpRequestUpload: C,
  6489. XMLSerializer: C,
  6490. XPathEvaluator: C,
  6491. XPathExpression: C,
  6492. XPathResult: C,
  6493. XSLTProcessor: C
  6494. };
  6495. for (const global of ['window', 'global', 'self', 'globalThis']) {
  6496. knownGlobals[global] = knownGlobals;
  6497. }
  6498. function getGlobalAtPath(path) {
  6499. let currentGlobal = knownGlobals;
  6500. for (const pathSegment of path) {
  6501. if (typeof pathSegment !== 'string') {
  6502. return null;
  6503. }
  6504. currentGlobal = currentGlobal[pathSegment];
  6505. if (!currentGlobal) {
  6506. return null;
  6507. }
  6508. }
  6509. return currentGlobal[ValueProperties];
  6510. }
  6511. class GlobalVariable extends Variable {
  6512. constructor() {
  6513. super(...arguments);
  6514. // Ensure we use live-bindings for globals as we do not know if they have
  6515. // been reassigned
  6516. this.isReassigned = true;
  6517. }
  6518. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6519. switch (interaction.type) {
  6520. // While there is no point in testing these cases as at the moment, they
  6521. // are also covered via other means, we keep them for completeness
  6522. case INTERACTION_ACCESSED:
  6523. case INTERACTION_ASSIGNED: {
  6524. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  6525. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6526. }
  6527. return;
  6528. }
  6529. case INTERACTION_CALLED: {
  6530. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  6531. if (globalAtPath) {
  6532. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  6533. }
  6534. else {
  6535. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6536. }
  6537. return;
  6538. }
  6539. }
  6540. }
  6541. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  6542. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  6543. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  6544. }
  6545. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6546. switch (interaction.type) {
  6547. case INTERACTION_ACCESSED: {
  6548. if (path.length === 0) {
  6549. // Technically, "undefined" is a global variable of sorts
  6550. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  6551. }
  6552. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  6553. }
  6554. case INTERACTION_ASSIGNED: {
  6555. return true;
  6556. }
  6557. case INTERACTION_CALLED: {
  6558. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  6559. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  6560. }
  6561. }
  6562. }
  6563. }
  6564. const tdzVariableKinds = new Set(['class', 'const', 'let', 'var', 'using', 'await using']);
  6565. class Identifier extends NodeBase {
  6566. constructor() {
  6567. super(...arguments);
  6568. this.variable = null;
  6569. }
  6570. get isTDZAccess() {
  6571. if (!isFlagSet(this.flags, 4 /* Flag.tdzAccessDefined */)) {
  6572. return null;
  6573. }
  6574. return isFlagSet(this.flags, 8 /* Flag.tdzAccess */);
  6575. }
  6576. set isTDZAccess(value) {
  6577. this.flags = setFlag(this.flags, 4 /* Flag.tdzAccessDefined */, true);
  6578. this.flags = setFlag(this.flags, 8 /* Flag.tdzAccess */, value);
  6579. }
  6580. addExportedVariables(variables, exportNamesByVariable) {
  6581. if (exportNamesByVariable.has(this.variable)) {
  6582. variables.push(this.variable);
  6583. }
  6584. }
  6585. bind() {
  6586. if (!this.variable && is_reference(this, this.parent)) {
  6587. this.variable = this.scope.findVariable(this.name);
  6588. this.variable.addReference(this);
  6589. }
  6590. }
  6591. declare(kind, init) {
  6592. let variable;
  6593. const { treeshake } = this.scope.context.options;
  6594. switch (kind) {
  6595. case 'var': {
  6596. variable = this.scope.addDeclaration(this, this.scope.context, init, kind);
  6597. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  6598. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  6599. variable.markInitializersForDeoptimization();
  6600. }
  6601. break;
  6602. }
  6603. case 'function': {
  6604. // in strict mode, functions are only hoisted within a scope but not across block scopes
  6605. variable = this.scope.addDeclaration(this, this.scope.context, init, kind);
  6606. break;
  6607. }
  6608. case 'let':
  6609. case 'const':
  6610. case 'using':
  6611. case 'await using':
  6612. case 'class': {
  6613. variable = this.scope.addDeclaration(this, this.scope.context, init, kind);
  6614. break;
  6615. }
  6616. case 'parameter': {
  6617. variable = this.scope.addParameterDeclaration(this);
  6618. break;
  6619. }
  6620. /* istanbul ignore next */
  6621. default: {
  6622. /* istanbul ignore next */
  6623. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  6624. }
  6625. }
  6626. return [(this.variable = variable)];
  6627. }
  6628. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6629. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6630. }
  6631. deoptimizePath(path) {
  6632. if (path.length === 0 && !this.scope.contains(this.name)) {
  6633. this.disallowImportReassignment();
  6634. }
  6635. // We keep conditional chaining because an unknown Node could have an
  6636. // Identifier as property that might be deoptimized by default
  6637. this.variable?.deoptimizePath(path);
  6638. }
  6639. getLiteralValueAtPath(path, recursionTracker, origin) {
  6640. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  6641. }
  6642. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6643. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6644. return [expression, isPure || this.isPureFunction(path)];
  6645. }
  6646. hasEffects(context) {
  6647. if (!this.deoptimized)
  6648. this.applyDeoptimizations();
  6649. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  6650. return true;
  6651. }
  6652. return (this.scope.context.options.treeshake
  6653. .unknownGlobalSideEffects &&
  6654. this.variable instanceof GlobalVariable &&
  6655. !this.isPureFunction(EMPTY_PATH) &&
  6656. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  6657. }
  6658. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6659. switch (interaction.type) {
  6660. case INTERACTION_ACCESSED: {
  6661. return (this.variable !== null &&
  6662. !this.isPureFunction(path) &&
  6663. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  6664. }
  6665. case INTERACTION_ASSIGNED: {
  6666. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  6667. }
  6668. case INTERACTION_CALLED: {
  6669. return (!this.isPureFunction(path) &&
  6670. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  6671. }
  6672. }
  6673. }
  6674. include() {
  6675. if (!this.deoptimized)
  6676. this.applyDeoptimizations();
  6677. if (!this.included) {
  6678. this.included = true;
  6679. if (this.variable !== null) {
  6680. this.scope.context.includeVariableInModule(this.variable);
  6681. }
  6682. }
  6683. }
  6684. includeCallArguments(context, parameters) {
  6685. this.variable.includeCallArguments(context, parameters);
  6686. }
  6687. isPossibleTDZ() {
  6688. // return cached value to avoid issues with the next tree-shaking pass
  6689. const cachedTdzAccess = this.isTDZAccess;
  6690. if (cachedTdzAccess !== null)
  6691. return cachedTdzAccess;
  6692. if (!(this.variable instanceof LocalVariable &&
  6693. this.variable.kind &&
  6694. tdzVariableKinds.has(this.variable.kind) &&
  6695. // we ignore possible TDZs due to circular module dependencies as
  6696. // otherwise we get many false positives
  6697. this.variable.module === this.scope.context.module)) {
  6698. return (this.isTDZAccess = false);
  6699. }
  6700. let decl_id;
  6701. if (this.variable.declarations &&
  6702. this.variable.declarations.length === 1 &&
  6703. (decl_id = this.variable.declarations[0]) &&
  6704. this.start < decl_id.start &&
  6705. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  6706. // a variable accessed before its declaration
  6707. // in the same function or at top level of module
  6708. return (this.isTDZAccess = true);
  6709. }
  6710. // We ignore the case where the module is not yet executed because
  6711. // moduleSideEffects are false.
  6712. if (!this.variable.initReached && this.scope.context.module.isExecuted) {
  6713. // Either a const/let TDZ violation or
  6714. // var use before declaration was encountered.
  6715. return (this.isTDZAccess = true);
  6716. }
  6717. return (this.isTDZAccess = false);
  6718. }
  6719. markDeclarationReached() {
  6720. this.variable.initReached = true;
  6721. }
  6722. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  6723. if (this.variable) {
  6724. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  6725. if (name !== this.name) {
  6726. code.overwrite(this.start, this.end, name, {
  6727. contentOnly: true,
  6728. storeName: true
  6729. });
  6730. if (isShorthandProperty) {
  6731. code.prependRight(this.start, `${this.name}: `);
  6732. }
  6733. }
  6734. // In strict mode, any variable named "eval" must be the actual "eval" function
  6735. if (name === 'eval' &&
  6736. renderedParentType === CallExpression$1 &&
  6737. isCalleeOfRenderedParent) {
  6738. code.appendRight(this.start, '0, ');
  6739. }
  6740. }
  6741. }
  6742. disallowImportReassignment() {
  6743. return this.scope.context.error(logIllegalImportReassignment(this.name, this.scope.context.module.id), this.start);
  6744. }
  6745. applyDeoptimizations() {
  6746. this.deoptimized = true;
  6747. if (this.variable instanceof LocalVariable) {
  6748. this.variable.consolidateInitializers();
  6749. this.scope.context.requestTreeshakingPass();
  6750. }
  6751. }
  6752. getVariableRespectingTDZ() {
  6753. if (this.isPossibleTDZ()) {
  6754. return UNKNOWN_EXPRESSION;
  6755. }
  6756. return this.variable;
  6757. }
  6758. isPureFunction(path) {
  6759. let currentPureFunction = this.scope.context.manualPureFunctions[this.name];
  6760. for (const segment of path) {
  6761. if (currentPureFunction) {
  6762. if (currentPureFunction[PureFunctionKey]) {
  6763. return true;
  6764. }
  6765. currentPureFunction = currentPureFunction[segment];
  6766. }
  6767. else {
  6768. return false;
  6769. }
  6770. }
  6771. return currentPureFunction?.[PureFunctionKey];
  6772. }
  6773. }
  6774. function closestParentFunctionOrProgram(node) {
  6775. while (node && !/^Program|Function/.test(node.type)) {
  6776. node = node.parent;
  6777. }
  6778. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  6779. return node;
  6780. }
  6781. function treeshakeNode(node, code, start, end) {
  6782. code.remove(start, end);
  6783. node.removeAnnotations(code);
  6784. }
  6785. const NO_SEMICOLON = { isNoStatement: true };
  6786. // This assumes there are only white-space and comments between start and the string we are looking for
  6787. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  6788. let searchPos, charCodeAfterSlash;
  6789. searchPos = code.indexOf(searchString, start);
  6790. while (true) {
  6791. start = code.indexOf('/', start);
  6792. if (start === -1 || start >= searchPos)
  6793. return searchPos;
  6794. charCodeAfterSlash = code.charCodeAt(++start);
  6795. ++start;
  6796. // With our assumption, '/' always starts a comment. Determine comment type:
  6797. start =
  6798. charCodeAfterSlash === 47 /*"/"*/
  6799. ? code.indexOf('\n', start) + 1
  6800. : code.indexOf('*/', start) + 2;
  6801. if (start > searchPos) {
  6802. searchPos = code.indexOf(searchString, start);
  6803. }
  6804. }
  6805. }
  6806. const NON_WHITESPACE = /\S/g;
  6807. function findNonWhiteSpace(code, index) {
  6808. NON_WHITESPACE.lastIndex = index;
  6809. const result = NON_WHITESPACE.exec(code);
  6810. return result.index;
  6811. }
  6812. // This assumes "code" only contains white-space and comments
  6813. // Returns position of line-comment if applicable
  6814. function findFirstLineBreakOutsideComment(code) {
  6815. let lineBreakPos, charCodeAfterSlash, start = 0;
  6816. lineBreakPos = code.indexOf('\n', start);
  6817. while (true) {
  6818. start = code.indexOf('/', start);
  6819. if (start === -1 || start > lineBreakPos)
  6820. return [lineBreakPos, lineBreakPos + 1];
  6821. // With our assumption, '/' always starts a comment. Determine comment type:
  6822. charCodeAfterSlash = code.charCodeAt(start + 1);
  6823. if (charCodeAfterSlash === 47 /*"/"*/)
  6824. return [start, lineBreakPos + 1];
  6825. start = code.indexOf('*/', start + 2) + 2;
  6826. if (start > lineBreakPos) {
  6827. lineBreakPos = code.indexOf('\n', start);
  6828. }
  6829. }
  6830. }
  6831. function renderStatementList(statements, code, start, end, options) {
  6832. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  6833. let nextNode = statements[0];
  6834. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  6835. if (nextNodeNeedsBoundaries) {
  6836. nextNodeStart =
  6837. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  6838. }
  6839. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  6840. currentNode = nextNode;
  6841. currentNodeStart = nextNodeStart;
  6842. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  6843. nextNode = statements[nextIndex];
  6844. nextNodeNeedsBoundaries =
  6845. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  6846. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  6847. nextNodeStart =
  6848. currentNode.end +
  6849. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  6850. if (currentNode.included) {
  6851. currentNodeNeedsBoundaries
  6852. ? currentNode.render(code, options, {
  6853. end: nextNodeStart,
  6854. start: currentNodeStart
  6855. })
  6856. : currentNode.render(code, options);
  6857. }
  6858. else {
  6859. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  6860. }
  6861. }
  6862. else {
  6863. currentNode.render(code, options);
  6864. }
  6865. }
  6866. }
  6867. // This assumes that the first character is not part of the first node
  6868. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  6869. const splitUpNodes = [];
  6870. let node, nextNodeStart, contentEnd, char;
  6871. let separator = start - 1;
  6872. for (const nextNode of nodes) {
  6873. if (node !== undefined) {
  6874. separator =
  6875. node.end +
  6876. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  6877. }
  6878. nextNodeStart = contentEnd =
  6879. separator +
  6880. 1 +
  6881. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  6882. while (((char = code.original.charCodeAt(nextNodeStart)),
  6883. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  6884. nextNodeStart++;
  6885. if (node !== undefined) {
  6886. splitUpNodes.push({
  6887. contentEnd,
  6888. end: nextNodeStart,
  6889. node,
  6890. separator,
  6891. start
  6892. });
  6893. }
  6894. node = nextNode;
  6895. start = nextNodeStart;
  6896. }
  6897. splitUpNodes.push({
  6898. contentEnd: end,
  6899. end,
  6900. node: node,
  6901. separator: null,
  6902. start
  6903. });
  6904. return splitUpNodes;
  6905. }
  6906. // This assumes there are only white-space and comments between start and end
  6907. function removeLineBreaks(code, start, end) {
  6908. while (true) {
  6909. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  6910. if (removeStart === -1) {
  6911. break;
  6912. }
  6913. code.remove(start + removeStart, (start += removeEnd));
  6914. }
  6915. }
  6916. class BlockScope extends ChildScope {
  6917. constructor(parent) {
  6918. super(parent, parent.context);
  6919. }
  6920. addDeclaration(identifier, context, init, kind) {
  6921. if (kind === 'var') {
  6922. const name = identifier.name;
  6923. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  6924. if (existingVariable) {
  6925. if (existingVariable.kind === 'var' ||
  6926. (kind === 'var' && existingVariable.kind === 'parameter')) {
  6927. existingVariable.addDeclaration(identifier, init);
  6928. return existingVariable;
  6929. }
  6930. return context.error(logRedeclarationError(name), identifier.start);
  6931. }
  6932. const declaredVariable = this.parent.addDeclaration(identifier, context, init, kind);
  6933. // Necessary to make sure the init is deoptimized for conditional declarations.
  6934. // We cannot call deoptimizePath here.
  6935. declaredVariable.markInitializersForDeoptimization();
  6936. // We add the variable to this and all parent scopes to reliably detect conflicts
  6937. this.addHoistedVariable(name, declaredVariable);
  6938. return declaredVariable;
  6939. }
  6940. return super.addDeclaration(identifier, context, init, kind);
  6941. }
  6942. }
  6943. class ExpressionStatement extends NodeBase {
  6944. initialise() {
  6945. super.initialise();
  6946. if (this.directive &&
  6947. this.directive !== 'use strict' &&
  6948. this.parent.type === Program$1) {
  6949. this.scope.context.log(LOGLEVEL_WARN,
  6950. // This is necessary, because either way (deleting or not) can lead to errors.
  6951. logModuleLevelDirective(this.directive, this.scope.context.module.id), this.start);
  6952. }
  6953. }
  6954. removeAnnotations(code) {
  6955. this.expression.removeAnnotations(code);
  6956. }
  6957. render(code, options) {
  6958. super.render(code, options);
  6959. if (code.original[this.end - 1] !== ';') {
  6960. code.appendLeft(this.end, ';');
  6961. }
  6962. }
  6963. shouldBeIncluded(context) {
  6964. if (this.directive && this.directive !== 'use strict')
  6965. return this.parent.type !== Program$1;
  6966. return super.shouldBeIncluded(context);
  6967. }
  6968. applyDeoptimizations() { }
  6969. }
  6970. class BlockStatement extends NodeBase {
  6971. get deoptimizeBody() {
  6972. return isFlagSet(this.flags, 32768 /* Flag.deoptimizeBody */);
  6973. }
  6974. set deoptimizeBody(value) {
  6975. this.flags = setFlag(this.flags, 32768 /* Flag.deoptimizeBody */, value);
  6976. }
  6977. get directlyIncluded() {
  6978. return isFlagSet(this.flags, 16384 /* Flag.directlyIncluded */);
  6979. }
  6980. set directlyIncluded(value) {
  6981. this.flags = setFlag(this.flags, 16384 /* Flag.directlyIncluded */, value);
  6982. }
  6983. addImplicitReturnExpressionToScope() {
  6984. const lastStatement = this.body[this.body.length - 1];
  6985. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  6986. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  6987. }
  6988. }
  6989. createScope(parentScope) {
  6990. this.scope = this.parent.preventChildBlockScope
  6991. ? parentScope
  6992. : new BlockScope(parentScope);
  6993. }
  6994. hasEffects(context) {
  6995. if (this.deoptimizeBody)
  6996. return true;
  6997. for (const node of this.body) {
  6998. if (context.brokenFlow)
  6999. break;
  7000. if (node.hasEffects(context))
  7001. return true;
  7002. }
  7003. return false;
  7004. }
  7005. include(context, includeChildrenRecursively) {
  7006. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  7007. this.included = true;
  7008. this.directlyIncluded = true;
  7009. if (this.deoptimizeBody)
  7010. includeChildrenRecursively = true;
  7011. for (const node of this.body) {
  7012. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  7013. node.include(context, includeChildrenRecursively);
  7014. }
  7015. }
  7016. }
  7017. initialise() {
  7018. super.initialise();
  7019. const firstBodyStatement = this.body[0];
  7020. this.deoptimizeBody =
  7021. firstBodyStatement instanceof ExpressionStatement &&
  7022. firstBodyStatement.directive === 'use asm';
  7023. }
  7024. render(code, options) {
  7025. if (this.body.length > 0) {
  7026. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  7027. }
  7028. else {
  7029. super.render(code, options);
  7030. }
  7031. }
  7032. }
  7033. class RestElement extends NodeBase {
  7034. constructor() {
  7035. super(...arguments);
  7036. this.declarationInit = null;
  7037. }
  7038. addExportedVariables(variables, exportNamesByVariable) {
  7039. this.argument.addExportedVariables(variables, exportNamesByVariable);
  7040. }
  7041. declare(kind, init) {
  7042. this.declarationInit = init;
  7043. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  7044. }
  7045. deoptimizePath(path) {
  7046. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  7047. }
  7048. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7049. return (path.length > 0 ||
  7050. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7051. }
  7052. markDeclarationReached() {
  7053. this.argument.markDeclarationReached();
  7054. }
  7055. applyDeoptimizations() {
  7056. this.deoptimized = true;
  7057. if (this.declarationInit !== null) {
  7058. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  7059. this.scope.context.requestTreeshakingPass();
  7060. }
  7061. }
  7062. }
  7063. class FunctionBase extends NodeBase {
  7064. constructor() {
  7065. super(...arguments);
  7066. this.objectEntity = null;
  7067. }
  7068. get async() {
  7069. return isFlagSet(this.flags, 256 /* Flag.async */);
  7070. }
  7071. set async(value) {
  7072. this.flags = setFlag(this.flags, 256 /* Flag.async */, value);
  7073. }
  7074. get deoptimizedReturn() {
  7075. return isFlagSet(this.flags, 512 /* Flag.deoptimizedReturn */);
  7076. }
  7077. set deoptimizedReturn(value) {
  7078. this.flags = setFlag(this.flags, 512 /* Flag.deoptimizedReturn */, value);
  7079. }
  7080. get generator() {
  7081. return isFlagSet(this.flags, 4194304 /* Flag.generator */);
  7082. }
  7083. set generator(value) {
  7084. this.flags = setFlag(this.flags, 4194304 /* Flag.generator */, value);
  7085. }
  7086. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7087. if (interaction.type === INTERACTION_CALLED) {
  7088. const { parameters } = this.scope;
  7089. const { args } = interaction;
  7090. let hasRest = false;
  7091. for (let position = 0; position < args.length - 1; position++) {
  7092. const parameter = this.params[position];
  7093. // Only the "this" argument arg[0] can be null
  7094. const argument = args[position + 1];
  7095. if (hasRest || parameter instanceof RestElement) {
  7096. hasRest = true;
  7097. argument.deoptimizePath(UNKNOWN_PATH);
  7098. }
  7099. else if (parameter instanceof Identifier) {
  7100. parameters[position][0].addEntityToBeDeoptimized(argument);
  7101. this.addArgumentToBeDeoptimized(argument);
  7102. }
  7103. else if (parameter) {
  7104. argument.deoptimizePath(UNKNOWN_PATH);
  7105. }
  7106. else {
  7107. this.addArgumentToBeDeoptimized(argument);
  7108. }
  7109. }
  7110. }
  7111. else {
  7112. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7113. }
  7114. }
  7115. deoptimizePath(path) {
  7116. this.getObjectEntity().deoptimizePath(path);
  7117. if (path.length === 1 && path[0] === UnknownKey) {
  7118. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  7119. // which means the return expression and parameters need to be reassigned
  7120. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7121. for (const parameterList of this.scope.parameters) {
  7122. for (const parameter of parameterList) {
  7123. parameter.deoptimizePath(UNKNOWN_PATH);
  7124. }
  7125. }
  7126. }
  7127. }
  7128. getLiteralValueAtPath(path, recursionTracker, origin) {
  7129. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  7130. }
  7131. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7132. if (path.length > 0) {
  7133. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7134. }
  7135. if (this.async) {
  7136. if (!this.deoptimizedReturn) {
  7137. this.deoptimizedReturn = true;
  7138. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7139. this.scope.context.requestTreeshakingPass();
  7140. }
  7141. return UNKNOWN_RETURN_EXPRESSION;
  7142. }
  7143. return [this.scope.getReturnExpression(), false];
  7144. }
  7145. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7146. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  7147. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  7148. }
  7149. if (this.annotationNoSideEffects) {
  7150. return false;
  7151. }
  7152. if (this.async) {
  7153. const { propertyReadSideEffects } = this.scope.context.options
  7154. .treeshake;
  7155. const returnExpression = this.scope.getReturnExpression();
  7156. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  7157. (propertyReadSideEffects &&
  7158. (propertyReadSideEffects === 'always' ||
  7159. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  7160. return true;
  7161. }
  7162. }
  7163. for (const parameter of this.params) {
  7164. if (parameter.hasEffects(context))
  7165. return true;
  7166. }
  7167. return false;
  7168. }
  7169. include(context, includeChildrenRecursively) {
  7170. if (!this.deoptimized)
  7171. this.applyDeoptimizations();
  7172. this.included = true;
  7173. const { brokenFlow } = context;
  7174. context.brokenFlow = false;
  7175. this.body.include(context, includeChildrenRecursively);
  7176. context.brokenFlow = brokenFlow;
  7177. }
  7178. includeCallArguments(context, parameters) {
  7179. this.scope.includeCallArguments(context, parameters);
  7180. }
  7181. initialise() {
  7182. super.initialise();
  7183. if (this.body instanceof BlockStatement) {
  7184. this.body.addImplicitReturnExpressionToScope();
  7185. }
  7186. else {
  7187. this.scope.addReturnExpression(this.body);
  7188. }
  7189. if (this.annotations &&
  7190. this.scope.context.options.treeshake.annotations) {
  7191. this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
  7192. }
  7193. }
  7194. parseNode(esTreeNode) {
  7195. const { body, params } = esTreeNode;
  7196. const { scope } = this;
  7197. const { bodyScope, context } = scope;
  7198. // We need to ensure that parameters are declared before the body is parsed
  7199. // so that the scope already knows all parameters and can detect conflicts
  7200. // when parsing the body.
  7201. const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
  7202. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  7203. this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
  7204. return super.parseNode(esTreeNode);
  7205. }
  7206. addArgumentToBeDeoptimized(_argument) { }
  7207. applyDeoptimizations() { }
  7208. }
  7209. FunctionBase.prototype.preventChildBlockScope = true;
  7210. class ArrowFunctionExpression extends FunctionBase {
  7211. constructor() {
  7212. super(...arguments);
  7213. this.objectEntity = null;
  7214. }
  7215. get expression() {
  7216. return isFlagSet(this.flags, 8388608 /* Flag.expression */);
  7217. }
  7218. set expression(value) {
  7219. this.flags = setFlag(this.flags, 8388608 /* Flag.expression */, value);
  7220. }
  7221. createScope(parentScope) {
  7222. this.scope = new ReturnValueScope(parentScope, false);
  7223. }
  7224. hasEffects() {
  7225. if (!this.deoptimized)
  7226. this.applyDeoptimizations();
  7227. return false;
  7228. }
  7229. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7230. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  7231. return true;
  7232. }
  7233. if (this.annotationNoSideEffects) {
  7234. return false;
  7235. }
  7236. if (interaction.type === INTERACTION_CALLED) {
  7237. const { ignore, brokenFlow } = context;
  7238. context.ignore = {
  7239. breaks: false,
  7240. continues: false,
  7241. labels: new Set(),
  7242. returnYield: true,
  7243. this: false
  7244. };
  7245. if (this.body.hasEffects(context))
  7246. return true;
  7247. context.ignore = ignore;
  7248. context.brokenFlow = brokenFlow;
  7249. }
  7250. return false;
  7251. }
  7252. include(context, includeChildrenRecursively) {
  7253. super.include(context, includeChildrenRecursively);
  7254. for (const parameter of this.params) {
  7255. if (!(parameter instanceof Identifier)) {
  7256. parameter.include(context, includeChildrenRecursively);
  7257. }
  7258. }
  7259. }
  7260. getObjectEntity() {
  7261. if (this.objectEntity !== null) {
  7262. return this.objectEntity;
  7263. }
  7264. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  7265. }
  7266. }
  7267. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  7268. if (exportedVariables.length === 1 &&
  7269. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  7270. const variable = exportedVariables[0];
  7271. return `exports(${JSON.stringify(exportNamesByVariable.get(variable)[0])},${_}${variable.getName(getPropertyAccess)}${modifier})`;
  7272. }
  7273. else {
  7274. const fields = [];
  7275. for (const variable of exportedVariables) {
  7276. for (const exportName of exportNamesByVariable.get(variable)) {
  7277. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  7278. }
  7279. }
  7280. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  7281. }
  7282. }
  7283. // This is only invoked if there is exactly one export name
  7284. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  7285. code.prependRight(expressionStart, `exports(${JSON.stringify(exportNamesByVariable.get(exportedVariable)[0])},${_}`);
  7286. code.appendLeft(expressionEnd, ')');
  7287. }
  7288. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  7289. const { _, getDirectReturnIifeLeft } = options.snippets;
  7290. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  7291. code.appendLeft(expressionEnd, ')');
  7292. }
  7293. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  7294. const { _, getPropertyAccess } = options.snippets;
  7295. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  7296. if (needsParens) {
  7297. code.prependRight(expressionStart, '(');
  7298. code.appendLeft(expressionEnd, ')');
  7299. }
  7300. }
  7301. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  7302. const { _ } = options.snippets;
  7303. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  7304. if (needsParens) {
  7305. code.prependRight(expressionStart, '(');
  7306. code.appendLeft(expressionEnd, ')');
  7307. }
  7308. }
  7309. class ObjectPattern extends NodeBase {
  7310. addExportedVariables(variables, exportNamesByVariable) {
  7311. for (const property of this.properties) {
  7312. if (property.type === Property$1) {
  7313. property.value.addExportedVariables(variables, exportNamesByVariable);
  7314. }
  7315. else {
  7316. property.argument.addExportedVariables(variables, exportNamesByVariable);
  7317. }
  7318. }
  7319. }
  7320. declare(kind, init) {
  7321. const variables = [];
  7322. for (const property of this.properties) {
  7323. variables.push(...property.declare(kind, init));
  7324. }
  7325. return variables;
  7326. }
  7327. deoptimizePath(path) {
  7328. if (path.length === 0) {
  7329. for (const property of this.properties) {
  7330. property.deoptimizePath(path);
  7331. }
  7332. }
  7333. }
  7334. hasEffectsOnInteractionAtPath(
  7335. // At the moment, this is only triggered for assignment left-hand sides,
  7336. // where the path is empty
  7337. _path, interaction, context) {
  7338. for (const property of this.properties) {
  7339. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  7340. return true;
  7341. }
  7342. return false;
  7343. }
  7344. markDeclarationReached() {
  7345. for (const property of this.properties) {
  7346. property.markDeclarationReached();
  7347. }
  7348. }
  7349. }
  7350. class AssignmentExpression extends NodeBase {
  7351. hasEffects(context) {
  7352. const { deoptimized, left, operator, right } = this;
  7353. if (!deoptimized)
  7354. this.applyDeoptimizations();
  7355. // MemberExpressions do not access the property before assignments if the
  7356. // operator is '='.
  7357. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, operator !== '='));
  7358. }
  7359. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7360. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  7361. }
  7362. include(context, includeChildrenRecursively) {
  7363. const { deoptimized, left, right, operator } = this;
  7364. if (!deoptimized)
  7365. this.applyDeoptimizations();
  7366. this.included = true;
  7367. if (includeChildrenRecursively ||
  7368. operator !== '=' ||
  7369. left.included ||
  7370. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  7371. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  7372. }
  7373. right.include(context, includeChildrenRecursively);
  7374. }
  7375. initialise() {
  7376. super.initialise();
  7377. if (this.left instanceof Identifier) {
  7378. const variable = this.scope.variables.get(this.left.name);
  7379. if (variable?.kind === 'const') {
  7380. this.scope.context.error(logConstVariableReassignError(), this.left.start);
  7381. }
  7382. }
  7383. this.left.setAssignedValue(this.right);
  7384. }
  7385. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  7386. const { left, right, start, end, parent } = this;
  7387. if (left.included) {
  7388. left.render(code, options);
  7389. right.render(code, options);
  7390. }
  7391. else {
  7392. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  7393. code.remove(start, inclusionStart);
  7394. if (preventASI) {
  7395. removeLineBreaks(code, inclusionStart, right.start);
  7396. }
  7397. right.render(code, options, {
  7398. renderedParentType: renderedParentType || parent.type,
  7399. renderedSurroundingElement: renderedSurroundingElement || parent.type
  7400. });
  7401. }
  7402. if (options.format === 'system') {
  7403. if (left instanceof Identifier) {
  7404. const variable = left.variable;
  7405. const exportNames = options.exportNamesByVariable.get(variable);
  7406. if (exportNames) {
  7407. if (exportNames.length === 1) {
  7408. renderSystemExportExpression(variable, start, end, code, options);
  7409. }
  7410. else {
  7411. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  7412. }
  7413. return;
  7414. }
  7415. }
  7416. else {
  7417. const systemPatternExports = [];
  7418. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  7419. if (systemPatternExports.length > 0) {
  7420. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  7421. return;
  7422. }
  7423. }
  7424. }
  7425. if (left.included &&
  7426. left instanceof ObjectPattern &&
  7427. (renderedSurroundingElement === ExpressionStatement$1 ||
  7428. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  7429. code.appendRight(start, '(');
  7430. code.prependLeft(end, ')');
  7431. }
  7432. }
  7433. applyDeoptimizations() {
  7434. this.deoptimized = true;
  7435. this.left.deoptimizePath(EMPTY_PATH);
  7436. this.right.deoptimizePath(UNKNOWN_PATH);
  7437. this.scope.context.requestTreeshakingPass();
  7438. }
  7439. }
  7440. class AssignmentPattern extends NodeBase {
  7441. addExportedVariables(variables, exportNamesByVariable) {
  7442. this.left.addExportedVariables(variables, exportNamesByVariable);
  7443. }
  7444. declare(kind, init) {
  7445. return this.left.declare(kind, init);
  7446. }
  7447. deoptimizePath(path) {
  7448. path.length === 0 && this.left.deoptimizePath(path);
  7449. }
  7450. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7451. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7452. }
  7453. markDeclarationReached() {
  7454. this.left.markDeclarationReached();
  7455. }
  7456. render(code, options, { isShorthandProperty } = BLANK) {
  7457. this.left.render(code, options, { isShorthandProperty });
  7458. this.right.render(code, options);
  7459. }
  7460. applyDeoptimizations() {
  7461. this.deoptimized = true;
  7462. this.left.deoptimizePath(EMPTY_PATH);
  7463. this.right.deoptimizePath(UNKNOWN_PATH);
  7464. this.scope.context.requestTreeshakingPass();
  7465. }
  7466. }
  7467. class ArgumentsVariable extends LocalVariable {
  7468. constructor(context) {
  7469. super('arguments', null, UNKNOWN_EXPRESSION, context, 'other');
  7470. this.deoptimizedArguments = [];
  7471. }
  7472. addArgumentToBeDeoptimized(argument) {
  7473. if (this.included) {
  7474. argument.deoptimizePath(UNKNOWN_PATH);
  7475. }
  7476. else {
  7477. this.deoptimizedArguments.push(argument);
  7478. }
  7479. }
  7480. hasEffectsOnInteractionAtPath(path, { type }) {
  7481. return type !== INTERACTION_ACCESSED || path.length > 1;
  7482. }
  7483. include() {
  7484. super.include();
  7485. for (const argument of this.deoptimizedArguments) {
  7486. argument.deoptimizePath(UNKNOWN_PATH);
  7487. }
  7488. this.deoptimizedArguments.length = 0;
  7489. }
  7490. }
  7491. class ThisVariable extends ParameterVariable {
  7492. constructor(context) {
  7493. super('this', null, context);
  7494. }
  7495. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7496. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  7497. }
  7498. }
  7499. class FunctionScope extends ReturnValueScope {
  7500. constructor(parent) {
  7501. const { context } = parent;
  7502. super(parent, false);
  7503. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  7504. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  7505. }
  7506. findLexicalBoundary() {
  7507. return this;
  7508. }
  7509. includeCallArguments(context, parameters) {
  7510. super.includeCallArguments(context, parameters);
  7511. if (this.argumentsVariable.included) {
  7512. for (const argument of parameters) {
  7513. if (!argument.included) {
  7514. argument.include(context, false);
  7515. }
  7516. }
  7517. }
  7518. }
  7519. }
  7520. class FunctionNode extends FunctionBase {
  7521. constructor() {
  7522. super(...arguments);
  7523. this.objectEntity = null;
  7524. }
  7525. createScope(parentScope) {
  7526. this.scope = new FunctionScope(parentScope);
  7527. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  7528. // This makes sure that all deoptimizations of "this" are applied to the
  7529. // constructed entity.
  7530. this.scope.thisVariable.addEntityToBeDeoptimized(this.constructedEntity);
  7531. }
  7532. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7533. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7534. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  7535. // args[0] is the "this" argument
  7536. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.args[0]);
  7537. }
  7538. }
  7539. hasEffects(context) {
  7540. if (!this.deoptimized)
  7541. this.applyDeoptimizations();
  7542. if (this.annotationNoSideEffects) {
  7543. return false;
  7544. }
  7545. return !!this.id?.hasEffects(context);
  7546. }
  7547. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7548. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7549. return true;
  7550. if (this.annotationNoSideEffects) {
  7551. return false;
  7552. }
  7553. if (interaction.type === INTERACTION_CALLED) {
  7554. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  7555. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  7556. const { brokenFlow, ignore, replacedVariableInits } = context;
  7557. context.ignore = {
  7558. breaks: false,
  7559. continues: false,
  7560. labels: new Set(),
  7561. returnYield: true,
  7562. this: interaction.withNew
  7563. };
  7564. if (this.body.hasEffects(context))
  7565. return true;
  7566. context.brokenFlow = brokenFlow;
  7567. if (thisInit) {
  7568. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  7569. }
  7570. else {
  7571. replacedVariableInits.delete(this.scope.thisVariable);
  7572. }
  7573. context.ignore = ignore;
  7574. }
  7575. return false;
  7576. }
  7577. include(context, includeChildrenRecursively) {
  7578. super.include(context, includeChildrenRecursively);
  7579. this.id?.include();
  7580. const hasArguments = this.scope.argumentsVariable.included;
  7581. for (const parameter of this.params) {
  7582. if (!(parameter instanceof Identifier) || hasArguments) {
  7583. parameter.include(context, includeChildrenRecursively);
  7584. }
  7585. }
  7586. }
  7587. initialise() {
  7588. super.initialise();
  7589. this.id?.declare('function', this);
  7590. }
  7591. addArgumentToBeDeoptimized(argument) {
  7592. this.scope.argumentsVariable.addArgumentToBeDeoptimized(argument);
  7593. }
  7594. getObjectEntity() {
  7595. if (this.objectEntity !== null) {
  7596. return this.objectEntity;
  7597. }
  7598. return (this.objectEntity = new ObjectEntity([
  7599. {
  7600. key: 'prototype',
  7601. kind: 'init',
  7602. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  7603. }
  7604. ], OBJECT_PROTOTYPE));
  7605. }
  7606. }
  7607. class AwaitExpression extends NodeBase {
  7608. hasEffects() {
  7609. if (!this.deoptimized)
  7610. this.applyDeoptimizations();
  7611. return true;
  7612. }
  7613. include(context, includeChildrenRecursively) {
  7614. if (!this.deoptimized)
  7615. this.applyDeoptimizations();
  7616. if (!this.included) {
  7617. this.included = true;
  7618. checkTopLevelAwait: if (!this.scope.context.usesTopLevelAwait) {
  7619. let parent = this.parent;
  7620. do {
  7621. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  7622. break checkTopLevelAwait;
  7623. } while ((parent = parent.parent));
  7624. this.scope.context.usesTopLevelAwait = true;
  7625. }
  7626. }
  7627. this.argument.include(context, includeChildrenRecursively);
  7628. }
  7629. }
  7630. const binaryOperators = {
  7631. '!=': (left, right) => left != right,
  7632. '!==': (left, right) => left !== right,
  7633. '%': (left, right) => left % right,
  7634. '&': (left, right) => left & right,
  7635. '*': (left, right) => left * right,
  7636. // At the moment, "**" will be transpiled to Math.pow
  7637. '**': (left, right) => left ** right,
  7638. '+': (left, right) => left + right,
  7639. '-': (left, right) => left - right,
  7640. '/': (left, right) => left / right,
  7641. '<': (left, right) => left < right,
  7642. '<<': (left, right) => left << right,
  7643. '<=': (left, right) => left <= right,
  7644. '==': (left, right) => left == right,
  7645. '===': (left, right) => left === right,
  7646. '>': (left, right) => left > right,
  7647. '>=': (left, right) => left >= right,
  7648. '>>': (left, right) => left >> right,
  7649. '>>>': (left, right) => left >>> right,
  7650. '^': (left, right) => left ^ right,
  7651. '|': (left, right) => left | right
  7652. // We use the fallback for cases where we return something unknown
  7653. // in: () => UnknownValue,
  7654. // instanceof: () => UnknownValue,
  7655. };
  7656. class BinaryExpression extends NodeBase {
  7657. deoptimizeCache() { }
  7658. getLiteralValueAtPath(path, recursionTracker, origin) {
  7659. if (path.length > 0)
  7660. return UnknownValue;
  7661. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7662. if (typeof leftValue === 'symbol')
  7663. return UnknownValue;
  7664. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7665. if (typeof rightValue === 'symbol')
  7666. return UnknownValue;
  7667. const operatorFunction = binaryOperators[this.operator];
  7668. if (!operatorFunction)
  7669. return UnknownValue;
  7670. return operatorFunction(leftValue, rightValue);
  7671. }
  7672. hasEffects(context) {
  7673. // support some implicit type coercion runtime errors
  7674. if (this.operator === '+' &&
  7675. this.parent instanceof ExpressionStatement &&
  7676. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  7677. return true;
  7678. }
  7679. return super.hasEffects(context);
  7680. }
  7681. hasEffectsOnInteractionAtPath(path, { type }) {
  7682. return type !== INTERACTION_ACCESSED || path.length > 1;
  7683. }
  7684. removeAnnotations(code) {
  7685. this.left.removeAnnotations(code);
  7686. }
  7687. render(code, options, { renderedSurroundingElement } = BLANK) {
  7688. this.left.render(code, options, { renderedSurroundingElement });
  7689. this.right.render(code, options);
  7690. }
  7691. }
  7692. class BreakStatement extends NodeBase {
  7693. hasEffects(context) {
  7694. if (this.label) {
  7695. if (!context.ignore.labels.has(this.label.name))
  7696. return true;
  7697. context.includedLabels.add(this.label.name);
  7698. }
  7699. else {
  7700. if (!context.ignore.breaks)
  7701. return true;
  7702. context.hasBreak = true;
  7703. }
  7704. context.brokenFlow = true;
  7705. return false;
  7706. }
  7707. include(context) {
  7708. this.included = true;
  7709. if (this.label) {
  7710. this.label.include();
  7711. context.includedLabels.add(this.label.name);
  7712. }
  7713. else {
  7714. context.hasBreak = true;
  7715. }
  7716. context.brokenFlow = true;
  7717. }
  7718. }
  7719. function renderCallArguments(code, options, node) {
  7720. if (node.arguments.length > 0) {
  7721. if (node.arguments[node.arguments.length - 1].included) {
  7722. for (const argument of node.arguments) {
  7723. argument.render(code, options);
  7724. }
  7725. }
  7726. else {
  7727. let lastIncludedIndex = node.arguments.length - 2;
  7728. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  7729. lastIncludedIndex--;
  7730. }
  7731. if (lastIncludedIndex >= 0) {
  7732. for (let index = 0; index <= lastIncludedIndex; index++) {
  7733. node.arguments[index].render(code, options);
  7734. }
  7735. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  7736. }
  7737. else {
  7738. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  7739. }
  7740. }
  7741. }
  7742. }
  7743. class Literal extends NodeBase {
  7744. deoptimizeArgumentsOnInteractionAtPath() { }
  7745. getLiteralValueAtPath(path) {
  7746. if (path.length > 0 ||
  7747. // unknown literals can also be null but do not start with an "n"
  7748. (this.value === null && this.scope.context.code.charCodeAt(this.start) !== 110) ||
  7749. typeof this.value === 'bigint' ||
  7750. // to support shims for regular expressions
  7751. this.scope.context.code.charCodeAt(this.start) === 47) {
  7752. return UnknownValue;
  7753. }
  7754. return this.value;
  7755. }
  7756. getReturnExpressionWhenCalledAtPath(path) {
  7757. if (path.length !== 1)
  7758. return UNKNOWN_RETURN_EXPRESSION;
  7759. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  7760. }
  7761. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7762. switch (interaction.type) {
  7763. case INTERACTION_ACCESSED: {
  7764. return path.length > (this.value === null ? 0 : 1);
  7765. }
  7766. case INTERACTION_ASSIGNED: {
  7767. return true;
  7768. }
  7769. case INTERACTION_CALLED: {
  7770. if (this.included &&
  7771. this.value instanceof RegExp &&
  7772. (this.value.global || this.value.sticky)) {
  7773. return true;
  7774. }
  7775. return (path.length !== 1 ||
  7776. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  7777. }
  7778. }
  7779. }
  7780. initialise() {
  7781. super.initialise();
  7782. this.members = getLiteralMembersForValue(this.value);
  7783. }
  7784. parseNode(esTreeNode) {
  7785. this.value = esTreeNode.value;
  7786. this.regex = esTreeNode.regex;
  7787. return super.parseNode(esTreeNode);
  7788. }
  7789. render(code) {
  7790. if (typeof this.value === 'string') {
  7791. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  7792. }
  7793. }
  7794. }
  7795. // To avoid infinite recursions
  7796. const MAX_PATH_DEPTH = 7;
  7797. function getResolvablePropertyKey(memberExpression) {
  7798. return memberExpression.computed
  7799. ? getResolvableComputedPropertyKey(memberExpression.property)
  7800. : memberExpression.property.name;
  7801. }
  7802. function getResolvableComputedPropertyKey(propertyKey) {
  7803. if (propertyKey instanceof Literal) {
  7804. return String(propertyKey.value);
  7805. }
  7806. return null;
  7807. }
  7808. function getPathIfNotComputed(memberExpression) {
  7809. const nextPathKey = memberExpression.propertyKey;
  7810. const object = memberExpression.object;
  7811. if (typeof nextPathKey === 'string') {
  7812. if (object instanceof Identifier) {
  7813. return [
  7814. { key: object.name, pos: object.start },
  7815. { key: nextPathKey, pos: memberExpression.property.start }
  7816. ];
  7817. }
  7818. if (object instanceof MemberExpression) {
  7819. const parentPath = getPathIfNotComputed(object);
  7820. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  7821. }
  7822. }
  7823. return null;
  7824. }
  7825. function getStringFromPath(path) {
  7826. let pathString = path[0].key;
  7827. for (let index = 1; index < path.length; index++) {
  7828. pathString += '.' + path[index].key;
  7829. }
  7830. return pathString;
  7831. }
  7832. class MemberExpression extends NodeBase {
  7833. constructor() {
  7834. super(...arguments);
  7835. this.variable = null;
  7836. this.expressionsToBeDeoptimized = [];
  7837. }
  7838. get computed() {
  7839. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  7840. }
  7841. set computed(value) {
  7842. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  7843. }
  7844. get optional() {
  7845. return isFlagSet(this.flags, 128 /* Flag.optional */);
  7846. }
  7847. set optional(value) {
  7848. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  7849. }
  7850. get assignmentDeoptimized() {
  7851. return isFlagSet(this.flags, 16 /* Flag.assignmentDeoptimized */);
  7852. }
  7853. set assignmentDeoptimized(value) {
  7854. this.flags = setFlag(this.flags, 16 /* Flag.assignmentDeoptimized */, value);
  7855. }
  7856. get bound() {
  7857. return isFlagSet(this.flags, 32 /* Flag.bound */);
  7858. }
  7859. set bound(value) {
  7860. this.flags = setFlag(this.flags, 32 /* Flag.bound */, value);
  7861. }
  7862. get isUndefined() {
  7863. return isFlagSet(this.flags, 64 /* Flag.isUndefined */);
  7864. }
  7865. set isUndefined(value) {
  7866. this.flags = setFlag(this.flags, 64 /* Flag.isUndefined */, value);
  7867. }
  7868. bind() {
  7869. this.bound = true;
  7870. const path = getPathIfNotComputed(this);
  7871. const baseVariable = path && this.scope.findVariable(path[0].key);
  7872. if (baseVariable?.isNamespace) {
  7873. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.scope.context);
  7874. if (!resolvedVariable) {
  7875. super.bind();
  7876. }
  7877. else if (resolvedVariable === 'undefined') {
  7878. this.isUndefined = true;
  7879. }
  7880. else {
  7881. this.variable = resolvedVariable;
  7882. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  7883. }
  7884. }
  7885. else {
  7886. super.bind();
  7887. }
  7888. }
  7889. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7890. if (this.variable) {
  7891. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7892. }
  7893. else if (!this.isUndefined) {
  7894. if (path.length < MAX_PATH_DEPTH) {
  7895. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  7896. }
  7897. else {
  7898. deoptimizeInteraction(interaction);
  7899. }
  7900. }
  7901. }
  7902. deoptimizeCache() {
  7903. const { expressionsToBeDeoptimized, object } = this;
  7904. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  7905. this.propertyKey = UnknownKey;
  7906. object.deoptimizePath(UNKNOWN_PATH);
  7907. for (const expression of expressionsToBeDeoptimized) {
  7908. expression.deoptimizeCache();
  7909. }
  7910. }
  7911. deoptimizePath(path) {
  7912. if (path.length === 0)
  7913. this.disallowNamespaceReassignment();
  7914. if (this.variable) {
  7915. this.variable.deoptimizePath(path);
  7916. }
  7917. else if (!this.isUndefined && path.length < MAX_PATH_DEPTH) {
  7918. const propertyKey = this.getPropertyKey();
  7919. this.object.deoptimizePath([
  7920. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  7921. ...path
  7922. ]);
  7923. }
  7924. }
  7925. getLiteralValueAtPath(path, recursionTracker, origin) {
  7926. if (this.variable) {
  7927. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  7928. }
  7929. if (this.isUndefined) {
  7930. return undefined;
  7931. }
  7932. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  7933. this.expressionsToBeDeoptimized.push(origin);
  7934. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  7935. }
  7936. return UnknownValue;
  7937. }
  7938. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7939. if (this.variable) {
  7940. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7941. }
  7942. if (this.isUndefined) {
  7943. return [UNDEFINED_EXPRESSION, false];
  7944. }
  7945. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  7946. this.expressionsToBeDeoptimized.push(origin);
  7947. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  7948. }
  7949. return UNKNOWN_RETURN_EXPRESSION;
  7950. }
  7951. hasEffects(context) {
  7952. if (!this.deoptimized)
  7953. this.applyDeoptimizations();
  7954. return (this.property.hasEffects(context) ||
  7955. this.object.hasEffects(context) ||
  7956. this.hasAccessEffect(context));
  7957. }
  7958. hasEffectsAsAssignmentTarget(context, checkAccess) {
  7959. if (checkAccess && !this.deoptimized)
  7960. this.applyDeoptimizations();
  7961. if (!this.assignmentDeoptimized)
  7962. this.applyAssignmentDeoptimization();
  7963. return (this.property.hasEffects(context) ||
  7964. this.object.hasEffects(context) ||
  7965. (checkAccess && this.hasAccessEffect(context)) ||
  7966. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  7967. }
  7968. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7969. if (this.variable) {
  7970. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  7971. }
  7972. if (this.isUndefined) {
  7973. return true;
  7974. }
  7975. if (path.length < MAX_PATH_DEPTH) {
  7976. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  7977. }
  7978. return true;
  7979. }
  7980. include(context, includeChildrenRecursively) {
  7981. if (!this.deoptimized)
  7982. this.applyDeoptimizations();
  7983. this.includeProperties(context, includeChildrenRecursively);
  7984. }
  7985. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  7986. if (!this.assignmentDeoptimized)
  7987. this.applyAssignmentDeoptimization();
  7988. if (deoptimizeAccess) {
  7989. this.include(context, includeChildrenRecursively);
  7990. }
  7991. else {
  7992. this.includeProperties(context, includeChildrenRecursively);
  7993. }
  7994. }
  7995. includeCallArguments(context, parameters) {
  7996. if (this.variable) {
  7997. this.variable.includeCallArguments(context, parameters);
  7998. }
  7999. else {
  8000. super.includeCallArguments(context, parameters);
  8001. }
  8002. }
  8003. initialise() {
  8004. super.initialise();
  8005. this.propertyKey = getResolvablePropertyKey(this);
  8006. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  8007. }
  8008. isSkippedAsOptional(origin) {
  8009. return (!this.variable &&
  8010. !this.isUndefined &&
  8011. (this.object.isSkippedAsOptional?.(origin) ||
  8012. (this.optional &&
  8013. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null)));
  8014. }
  8015. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  8016. if (this.variable || this.isUndefined) {
  8017. const { snippets: { getPropertyAccess } } = options;
  8018. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  8019. if (renderedParentType && isCalleeOfRenderedParent)
  8020. replacement = '0, ' + replacement;
  8021. code.overwrite(this.start, this.end, replacement, {
  8022. contentOnly: true,
  8023. storeName: true
  8024. });
  8025. }
  8026. else {
  8027. if (renderedParentType && isCalleeOfRenderedParent) {
  8028. code.appendRight(this.start, '0, ');
  8029. }
  8030. this.object.render(code, options, { renderedSurroundingElement });
  8031. this.property.render(code, options);
  8032. }
  8033. }
  8034. setAssignedValue(value) {
  8035. this.assignmentInteraction = {
  8036. args: [this.object, value],
  8037. type: INTERACTION_ASSIGNED
  8038. };
  8039. }
  8040. applyDeoptimizations() {
  8041. this.deoptimized = true;
  8042. const { propertyReadSideEffects } = this.scope.context.options
  8043. .treeshake;
  8044. if (
  8045. // Namespaces are not bound and should not be deoptimized
  8046. this.bound &&
  8047. propertyReadSideEffects &&
  8048. !(this.variable || this.isUndefined)) {
  8049. const propertyKey = this.getPropertyKey();
  8050. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  8051. this.scope.context.requestTreeshakingPass();
  8052. }
  8053. }
  8054. applyAssignmentDeoptimization() {
  8055. this.assignmentDeoptimized = true;
  8056. const { propertyReadSideEffects } = this.scope.context.options
  8057. .treeshake;
  8058. if (
  8059. // Namespaces are not bound and should not be deoptimized
  8060. this.bound &&
  8061. propertyReadSideEffects &&
  8062. !(this.variable || this.isUndefined)) {
  8063. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  8064. this.scope.context.requestTreeshakingPass();
  8065. }
  8066. }
  8067. disallowNamespaceReassignment() {
  8068. if (this.object instanceof Identifier) {
  8069. const variable = this.scope.findVariable(this.object.name);
  8070. if (variable.isNamespace) {
  8071. if (this.variable) {
  8072. this.scope.context.includeVariableInModule(this.variable);
  8073. }
  8074. this.scope.context.log(LOGLEVEL_WARN, logIllegalImportReassignment(this.object.name, this.scope.context.module.id), this.start);
  8075. }
  8076. }
  8077. }
  8078. getPropertyKey() {
  8079. if (this.propertyKey === null) {
  8080. this.propertyKey = UnknownKey;
  8081. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8082. return (this.propertyKey =
  8083. value === SymbolToStringTag
  8084. ? value
  8085. : typeof value === 'symbol'
  8086. ? UnknownKey
  8087. : String(value));
  8088. }
  8089. return this.propertyKey;
  8090. }
  8091. hasAccessEffect(context) {
  8092. const { propertyReadSideEffects } = this.scope.context.options
  8093. .treeshake;
  8094. return (!(this.variable || this.isUndefined) &&
  8095. propertyReadSideEffects &&
  8096. (propertyReadSideEffects === 'always' ||
  8097. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  8098. }
  8099. includeProperties(context, includeChildrenRecursively) {
  8100. if (!this.included) {
  8101. this.included = true;
  8102. if (this.variable) {
  8103. this.scope.context.includeVariableInModule(this.variable);
  8104. }
  8105. }
  8106. this.object.include(context, includeChildrenRecursively);
  8107. this.property.include(context, includeChildrenRecursively);
  8108. }
  8109. }
  8110. function resolveNamespaceVariables(baseVariable, path, astContext) {
  8111. if (path.length === 0)
  8112. return baseVariable;
  8113. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  8114. return null;
  8115. const exportName = path[0].key;
  8116. const variable = baseVariable.context.traceExport(exportName);
  8117. if (!variable) {
  8118. if (path.length === 1) {
  8119. const fileName = baseVariable.context.fileName;
  8120. astContext.log(LOGLEVEL_WARN, logMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  8121. return 'undefined';
  8122. }
  8123. return null;
  8124. }
  8125. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  8126. }
  8127. class CallExpressionBase extends NodeBase {
  8128. constructor() {
  8129. super(...arguments);
  8130. this.returnExpression = null;
  8131. this.deoptimizableDependentExpressions = [];
  8132. this.expressionsToBeDeoptimized = new Set();
  8133. }
  8134. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8135. const { args } = interaction;
  8136. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  8137. if (isPure)
  8138. return;
  8139. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  8140. if (deoptimizedExpressions.length === 0)
  8141. return;
  8142. if (returnExpression === UNKNOWN_EXPRESSION) {
  8143. for (const expression of deoptimizedExpressions) {
  8144. expression.deoptimizePath(UNKNOWN_PATH);
  8145. }
  8146. }
  8147. else {
  8148. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8149. for (const expression of deoptimizedExpressions) {
  8150. this.expressionsToBeDeoptimized.add(expression);
  8151. }
  8152. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8153. }, null);
  8154. }
  8155. }
  8156. deoptimizeCache() {
  8157. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  8158. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  8159. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  8160. this.expressionsToBeDeoptimized = EMPTY_SET;
  8161. this.deoptimizableDependentExpressions = EMPTY_ARRAY;
  8162. for (const expression of deoptimizableDependentExpressions) {
  8163. expression.deoptimizeCache();
  8164. }
  8165. for (const expression of expressionsToBeDeoptimized) {
  8166. expression.deoptimizePath(UNKNOWN_PATH);
  8167. }
  8168. }
  8169. }
  8170. deoptimizePath(path) {
  8171. if (path.length === 0 ||
  8172. this.scope.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  8173. return;
  8174. }
  8175. const [returnExpression] = this.getReturnExpression();
  8176. if (returnExpression !== UNKNOWN_EXPRESSION) {
  8177. returnExpression.deoptimizePath(path);
  8178. }
  8179. }
  8180. getLiteralValueAtPath(path, recursionTracker, origin) {
  8181. const [returnExpression] = this.getReturnExpression(recursionTracker);
  8182. if (returnExpression === UNKNOWN_EXPRESSION) {
  8183. return UnknownValue;
  8184. }
  8185. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8186. this.deoptimizableDependentExpressions.push(origin);
  8187. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  8188. }, UnknownValue);
  8189. }
  8190. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8191. const returnExpression = this.getReturnExpression(recursionTracker);
  8192. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  8193. return returnExpression;
  8194. }
  8195. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8196. this.deoptimizableDependentExpressions.push(origin);
  8197. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8198. return [expression, isPure || returnExpression[1]];
  8199. }, UNKNOWN_RETURN_EXPRESSION);
  8200. }
  8201. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8202. const { type } = interaction;
  8203. if (type === INTERACTION_CALLED) {
  8204. const { args, withNew } = interaction;
  8205. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  8206. return false;
  8207. }
  8208. }
  8209. else if ((type === INTERACTION_ASSIGNED
  8210. ? context.assigned
  8211. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  8212. return false;
  8213. }
  8214. const [returnExpression, isPure] = this.getReturnExpression();
  8215. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  8216. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  8217. }
  8218. }
  8219. class CallExpression extends CallExpressionBase {
  8220. get optional() {
  8221. return isFlagSet(this.flags, 128 /* Flag.optional */);
  8222. }
  8223. set optional(value) {
  8224. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  8225. }
  8226. bind() {
  8227. super.bind();
  8228. if (this.callee instanceof Identifier) {
  8229. const variable = this.scope.findVariable(this.callee.name);
  8230. if (variable.isNamespace) {
  8231. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(this.callee.name), this.start);
  8232. }
  8233. if (this.callee.name === 'eval') {
  8234. this.scope.context.log(LOGLEVEL_WARN, logEval(this.scope.context.module.id), this.start);
  8235. }
  8236. }
  8237. this.interaction = {
  8238. args: [
  8239. this.callee instanceof MemberExpression && !this.callee.variable
  8240. ? this.callee.object
  8241. : null,
  8242. ...this.arguments
  8243. ],
  8244. type: INTERACTION_CALLED,
  8245. withNew: false
  8246. };
  8247. }
  8248. hasEffects(context) {
  8249. try {
  8250. for (const argument of this.arguments) {
  8251. if (argument.hasEffects(context))
  8252. return true;
  8253. }
  8254. if (this.annotationPure) {
  8255. return false;
  8256. }
  8257. return (this.callee.hasEffects(context) ||
  8258. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  8259. }
  8260. finally {
  8261. if (!this.deoptimized)
  8262. this.applyDeoptimizations();
  8263. }
  8264. }
  8265. include(context, includeChildrenRecursively) {
  8266. if (!this.deoptimized)
  8267. this.applyDeoptimizations();
  8268. if (includeChildrenRecursively) {
  8269. super.include(context, includeChildrenRecursively);
  8270. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  8271. this.callee instanceof Identifier &&
  8272. this.callee.variable) {
  8273. this.callee.variable.markCalledFromTryStatement();
  8274. }
  8275. }
  8276. else {
  8277. this.included = true;
  8278. this.callee.include(context, false);
  8279. }
  8280. this.callee.includeCallArguments(context, this.arguments);
  8281. }
  8282. initialise() {
  8283. super.initialise();
  8284. if (this.annotations &&
  8285. this.scope.context.options.treeshake.annotations) {
  8286. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  8287. }
  8288. }
  8289. isSkippedAsOptional(origin) {
  8290. return (this.callee.isSkippedAsOptional?.(origin) ||
  8291. (this.optional &&
  8292. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null));
  8293. }
  8294. render(code, options, { renderedSurroundingElement } = BLANK) {
  8295. this.callee.render(code, options, {
  8296. isCalleeOfRenderedParent: true,
  8297. renderedSurroundingElement
  8298. });
  8299. renderCallArguments(code, options, this);
  8300. }
  8301. applyDeoptimizations() {
  8302. this.deoptimized = true;
  8303. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  8304. this.scope.context.requestTreeshakingPass();
  8305. }
  8306. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  8307. if (this.returnExpression === null) {
  8308. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  8309. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  8310. }
  8311. return this.returnExpression;
  8312. }
  8313. }
  8314. class CatchClause extends NodeBase {
  8315. createScope(parentScope) {
  8316. this.scope = new ParameterScope(parentScope, true);
  8317. }
  8318. parseNode(esTreeNode) {
  8319. const { body, param, type } = esTreeNode;
  8320. this.type = type;
  8321. if (param) {
  8322. this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
  8323. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  8324. }
  8325. this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
  8326. return super.parseNode(esTreeNode);
  8327. }
  8328. }
  8329. CatchClause.prototype.preventChildBlockScope = true;
  8330. class ChainExpression extends NodeBase {
  8331. // deoptimizations are not relevant as we are not caching values
  8332. deoptimizeCache() { }
  8333. getLiteralValueAtPath(path, recursionTracker, origin) {
  8334. if (this.expression.isSkippedAsOptional(origin))
  8335. return undefined;
  8336. return this.expression.getLiteralValueAtPath(path, recursionTracker, origin);
  8337. }
  8338. hasEffects(context) {
  8339. if (this.expression.isSkippedAsOptional(this))
  8340. return false;
  8341. return this.expression.hasEffects(context);
  8342. }
  8343. removeAnnotations(code) {
  8344. this.expression.removeAnnotations(code);
  8345. }
  8346. }
  8347. class ClassBodyScope extends ChildScope {
  8348. constructor(parent, classNode) {
  8349. const { context } = parent;
  8350. super(parent, context);
  8351. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context, 'other')));
  8352. this.instanceScope = new ChildScope(this, context);
  8353. this.instanceScope.variables.set('this', new ThisVariable(context));
  8354. }
  8355. findLexicalBoundary() {
  8356. return this;
  8357. }
  8358. }
  8359. class ClassBody extends NodeBase {
  8360. createScope(parentScope) {
  8361. this.scope = new ClassBodyScope(parentScope, this.parent);
  8362. }
  8363. include(context, includeChildrenRecursively) {
  8364. this.included = true;
  8365. this.scope.context.includeVariableInModule(this.scope.thisVariable);
  8366. for (const definition of this.body) {
  8367. definition.include(context, includeChildrenRecursively);
  8368. }
  8369. }
  8370. parseNode(esTreeNode) {
  8371. const body = (this.body = []);
  8372. for (const definition of esTreeNode.body) {
  8373. body.push(new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition));
  8374. }
  8375. return super.parseNode(esTreeNode);
  8376. }
  8377. applyDeoptimizations() { }
  8378. }
  8379. class MethodBase extends NodeBase {
  8380. constructor() {
  8381. super(...arguments);
  8382. this.accessedValue = null;
  8383. }
  8384. get computed() {
  8385. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  8386. }
  8387. set computed(value) {
  8388. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  8389. }
  8390. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8391. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  8392. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  8393. args: interaction.args,
  8394. type: INTERACTION_CALLED,
  8395. withNew: false
  8396. }, EMPTY_PATH, recursionTracker);
  8397. }
  8398. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  8399. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  8400. args: interaction.args,
  8401. type: INTERACTION_CALLED,
  8402. withNew: false
  8403. }, EMPTY_PATH, recursionTracker);
  8404. }
  8405. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8406. }
  8407. // As getter properties directly receive their values from fixed function
  8408. // expressions, there is no known situation where a getter is deoptimized.
  8409. deoptimizeCache() { }
  8410. deoptimizePath(path) {
  8411. this.getAccessedValue()[0].deoptimizePath(path);
  8412. }
  8413. getLiteralValueAtPath(path, recursionTracker, origin) {
  8414. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  8415. }
  8416. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8417. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8418. }
  8419. hasEffects(context) {
  8420. return this.key.hasEffects(context);
  8421. }
  8422. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8423. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  8424. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8425. args: interaction.args,
  8426. type: INTERACTION_CALLED,
  8427. withNew: false
  8428. }, context);
  8429. }
  8430. // setters are only called for empty paths
  8431. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  8432. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8433. args: interaction.args,
  8434. type: INTERACTION_CALLED,
  8435. withNew: false
  8436. }, context);
  8437. }
  8438. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  8439. }
  8440. applyDeoptimizations() { }
  8441. getAccessedValue() {
  8442. if (this.accessedValue === null) {
  8443. if (this.kind === 'get') {
  8444. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  8445. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  8446. }
  8447. else {
  8448. return (this.accessedValue = [this.value, false]);
  8449. }
  8450. }
  8451. return this.accessedValue;
  8452. }
  8453. }
  8454. class MethodDefinition extends MethodBase {
  8455. applyDeoptimizations() { }
  8456. }
  8457. class ObjectMember extends ExpressionEntity {
  8458. constructor(object, key) {
  8459. super();
  8460. this.object = object;
  8461. this.key = key;
  8462. }
  8463. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8464. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  8465. }
  8466. deoptimizePath(path) {
  8467. this.object.deoptimizePath([this.key, ...path]);
  8468. }
  8469. getLiteralValueAtPath(path, recursionTracker, origin) {
  8470. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  8471. }
  8472. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8473. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  8474. }
  8475. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8476. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  8477. }
  8478. }
  8479. class ClassNode extends NodeBase {
  8480. constructor() {
  8481. super(...arguments);
  8482. this.objectEntity = null;
  8483. }
  8484. createScope(parentScope) {
  8485. this.scope = new ChildScope(parentScope, parentScope.context);
  8486. }
  8487. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8488. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8489. }
  8490. deoptimizeCache() {
  8491. this.getObjectEntity().deoptimizeAllProperties();
  8492. }
  8493. deoptimizePath(path) {
  8494. this.getObjectEntity().deoptimizePath(path);
  8495. }
  8496. getLiteralValueAtPath(path, recursionTracker, origin) {
  8497. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8498. }
  8499. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8500. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8501. }
  8502. hasEffects(context) {
  8503. if (!this.deoptimized)
  8504. this.applyDeoptimizations();
  8505. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  8506. this.id?.markDeclarationReached();
  8507. return initEffect || super.hasEffects(context);
  8508. }
  8509. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8510. return interaction.type === INTERACTION_CALLED && path.length === 0
  8511. ? !interaction.withNew ||
  8512. (this.classConstructor === null
  8513. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  8514. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  8515. false
  8516. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  8517. }
  8518. include(context, includeChildrenRecursively) {
  8519. if (!this.deoptimized)
  8520. this.applyDeoptimizations();
  8521. this.included = true;
  8522. this.superClass?.include(context, includeChildrenRecursively);
  8523. this.body.include(context, includeChildrenRecursively);
  8524. if (this.id) {
  8525. this.id.markDeclarationReached();
  8526. this.id.include();
  8527. }
  8528. }
  8529. initialise() {
  8530. super.initialise();
  8531. this.id?.declare('class', this);
  8532. for (const method of this.body.body) {
  8533. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  8534. this.classConstructor = method;
  8535. return;
  8536. }
  8537. }
  8538. this.classConstructor = null;
  8539. }
  8540. applyDeoptimizations() {
  8541. this.deoptimized = true;
  8542. for (const definition of this.body.body) {
  8543. if (!(definition.static ||
  8544. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  8545. // Calls to methods are not tracked, ensure that the return value is deoptimized
  8546. definition.deoptimizePath(UNKNOWN_PATH);
  8547. }
  8548. }
  8549. this.scope.context.requestTreeshakingPass();
  8550. }
  8551. getObjectEntity() {
  8552. if (this.objectEntity !== null) {
  8553. return this.objectEntity;
  8554. }
  8555. const staticProperties = [];
  8556. const dynamicMethods = [];
  8557. for (const definition of this.body.body) {
  8558. const properties = definition.static ? staticProperties : dynamicMethods;
  8559. const definitionKind = definition.kind;
  8560. // Note that class fields do not end up on the prototype
  8561. if (properties === dynamicMethods && !definitionKind)
  8562. continue;
  8563. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  8564. let key;
  8565. if (definition.computed) {
  8566. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8567. if (typeof keyValue === 'symbol') {
  8568. properties.push({ key: UnknownKey, kind, property: definition });
  8569. continue;
  8570. }
  8571. else {
  8572. key = String(keyValue);
  8573. }
  8574. }
  8575. else {
  8576. key =
  8577. definition.key instanceof Identifier
  8578. ? definition.key.name
  8579. : String(definition.key.value);
  8580. }
  8581. properties.push({ key, kind, property: definition });
  8582. }
  8583. staticProperties.unshift({
  8584. key: 'prototype',
  8585. kind: 'init',
  8586. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  8587. });
  8588. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  8589. }
  8590. }
  8591. class ClassDeclaration extends ClassNode {
  8592. initialise() {
  8593. super.initialise();
  8594. if (this.id !== null) {
  8595. this.id.variable.isId = true;
  8596. }
  8597. }
  8598. parseNode(esTreeNode) {
  8599. if (esTreeNode.id !== null) {
  8600. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  8601. }
  8602. return super.parseNode(esTreeNode);
  8603. }
  8604. render(code, options) {
  8605. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  8606. if (this.id) {
  8607. const { variable, name } = this.id;
  8608. if (format === 'system' && exportNamesByVariable.has(variable)) {
  8609. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  8610. }
  8611. const renderedVariable = variable.getName(getPropertyAccess);
  8612. if (renderedVariable !== name) {
  8613. this.superClass?.render(code, options);
  8614. this.body.render(code, {
  8615. ...options,
  8616. useOriginalName: (_variable) => _variable === variable
  8617. });
  8618. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  8619. code.prependLeft(this.end, ';');
  8620. return;
  8621. }
  8622. }
  8623. super.render(code, options);
  8624. }
  8625. applyDeoptimizations() {
  8626. super.applyDeoptimizations();
  8627. const { id, scope } = this;
  8628. if (id) {
  8629. const { name, variable } = id;
  8630. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  8631. if (accessedVariable !== variable) {
  8632. accessedVariable.forbidName(name);
  8633. }
  8634. }
  8635. }
  8636. }
  8637. }
  8638. class ClassExpression extends ClassNode {
  8639. render(code, options, { renderedSurroundingElement } = BLANK) {
  8640. super.render(code, options);
  8641. if (renderedSurroundingElement === ExpressionStatement$1) {
  8642. code.appendRight(this.start, '(');
  8643. code.prependLeft(this.end, ')');
  8644. }
  8645. }
  8646. }
  8647. class MultiExpression extends ExpressionEntity {
  8648. constructor(expressions) {
  8649. super();
  8650. this.expressions = expressions;
  8651. }
  8652. deoptimizePath(path) {
  8653. for (const expression of this.expressions) {
  8654. expression.deoptimizePath(path);
  8655. }
  8656. }
  8657. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8658. return [
  8659. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  8660. false
  8661. ];
  8662. }
  8663. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8664. for (const expression of this.expressions) {
  8665. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  8666. return true;
  8667. }
  8668. return false;
  8669. }
  8670. }
  8671. class ConditionalExpression extends NodeBase {
  8672. constructor() {
  8673. super(...arguments);
  8674. this.expressionsToBeDeoptimized = [];
  8675. this.usedBranch = null;
  8676. }
  8677. get isBranchResolutionAnalysed() {
  8678. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  8679. }
  8680. set isBranchResolutionAnalysed(value) {
  8681. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  8682. }
  8683. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8684. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8685. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8686. }
  8687. deoptimizeCache() {
  8688. if (this.usedBranch !== null) {
  8689. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  8690. this.usedBranch = null;
  8691. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  8692. const { expressionsToBeDeoptimized } = this;
  8693. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  8694. for (const expression of expressionsToBeDeoptimized) {
  8695. expression.deoptimizeCache();
  8696. }
  8697. }
  8698. }
  8699. deoptimizePath(path) {
  8700. const usedBranch = this.getUsedBranch();
  8701. if (usedBranch) {
  8702. usedBranch.deoptimizePath(path);
  8703. }
  8704. else {
  8705. this.consequent.deoptimizePath(path);
  8706. this.alternate.deoptimizePath(path);
  8707. }
  8708. }
  8709. getLiteralValueAtPath(path, recursionTracker, origin) {
  8710. const usedBranch = this.getUsedBranch();
  8711. if (!usedBranch)
  8712. return UnknownValue;
  8713. this.expressionsToBeDeoptimized.push(origin);
  8714. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  8715. }
  8716. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8717. const usedBranch = this.getUsedBranch();
  8718. if (!usedBranch)
  8719. return [
  8720. new MultiExpression([
  8721. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  8722. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  8723. ]),
  8724. false
  8725. ];
  8726. this.expressionsToBeDeoptimized.push(origin);
  8727. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8728. }
  8729. hasEffects(context) {
  8730. if (this.test.hasEffects(context))
  8731. return true;
  8732. const usedBranch = this.getUsedBranch();
  8733. if (!usedBranch) {
  8734. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  8735. }
  8736. return usedBranch.hasEffects(context);
  8737. }
  8738. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8739. const usedBranch = this.getUsedBranch();
  8740. if (!usedBranch) {
  8741. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  8742. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  8743. }
  8744. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  8745. }
  8746. include(context, includeChildrenRecursively) {
  8747. this.included = true;
  8748. const usedBranch = this.getUsedBranch();
  8749. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  8750. this.test.include(context, includeChildrenRecursively);
  8751. this.consequent.include(context, includeChildrenRecursively);
  8752. this.alternate.include(context, includeChildrenRecursively);
  8753. }
  8754. else {
  8755. usedBranch.include(context, includeChildrenRecursively);
  8756. }
  8757. }
  8758. includeCallArguments(context, parameters) {
  8759. const usedBranch = this.getUsedBranch();
  8760. if (usedBranch) {
  8761. usedBranch.includeCallArguments(context, parameters);
  8762. }
  8763. else {
  8764. this.consequent.includeCallArguments(context, parameters);
  8765. this.alternate.includeCallArguments(context, parameters);
  8766. }
  8767. }
  8768. removeAnnotations(code) {
  8769. this.test.removeAnnotations(code);
  8770. }
  8771. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  8772. const usedBranch = this.getUsedBranch();
  8773. if (this.test.included) {
  8774. this.test.render(code, options, { renderedSurroundingElement });
  8775. this.consequent.render(code, options);
  8776. this.alternate.render(code, options);
  8777. }
  8778. else {
  8779. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  8780. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  8781. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  8782. : colonPos) + 1);
  8783. if (preventASI) {
  8784. removeLineBreaks(code, inclusionStart, usedBranch.start);
  8785. }
  8786. code.remove(this.start, inclusionStart);
  8787. if (this.consequent.included) {
  8788. code.remove(colonPos, this.end);
  8789. }
  8790. this.test.removeAnnotations(code);
  8791. usedBranch.render(code, options, {
  8792. isCalleeOfRenderedParent,
  8793. preventASI: true,
  8794. renderedParentType: renderedParentType || this.parent.type,
  8795. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  8796. });
  8797. }
  8798. }
  8799. getUsedBranch() {
  8800. if (this.isBranchResolutionAnalysed) {
  8801. return this.usedBranch;
  8802. }
  8803. this.isBranchResolutionAnalysed = true;
  8804. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8805. return typeof testValue === 'symbol'
  8806. ? null
  8807. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  8808. }
  8809. }
  8810. class ContinueStatement extends NodeBase {
  8811. hasEffects(context) {
  8812. if (this.label) {
  8813. if (!context.ignore.labels.has(this.label.name))
  8814. return true;
  8815. context.includedLabels.add(this.label.name);
  8816. }
  8817. else {
  8818. if (!context.ignore.continues)
  8819. return true;
  8820. context.hasContinue = true;
  8821. }
  8822. context.brokenFlow = true;
  8823. return false;
  8824. }
  8825. include(context) {
  8826. this.included = true;
  8827. if (this.label) {
  8828. this.label.include();
  8829. context.includedLabels.add(this.label.name);
  8830. }
  8831. else {
  8832. context.hasContinue = true;
  8833. }
  8834. context.brokenFlow = true;
  8835. }
  8836. }
  8837. class DebuggerStatement extends NodeBase {
  8838. hasEffects() {
  8839. return true;
  8840. }
  8841. }
  8842. function hasLoopBodyEffects(context, body) {
  8843. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  8844. const { breaks, continues } = ignore;
  8845. ignore.breaks = true;
  8846. ignore.continues = true;
  8847. context.hasBreak = false;
  8848. context.hasContinue = false;
  8849. if (body.hasEffects(context))
  8850. return true;
  8851. ignore.breaks = breaks;
  8852. ignore.continues = continues;
  8853. context.hasBreak = hasBreak;
  8854. context.hasContinue = hasContinue;
  8855. context.brokenFlow = brokenFlow;
  8856. return false;
  8857. }
  8858. function includeLoopBody(context, body, includeChildrenRecursively) {
  8859. const { brokenFlow, hasBreak, hasContinue } = context;
  8860. context.hasBreak = false;
  8861. context.hasContinue = false;
  8862. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8863. context.hasBreak = hasBreak;
  8864. context.hasContinue = hasContinue;
  8865. context.brokenFlow = brokenFlow;
  8866. }
  8867. class DoWhileStatement extends NodeBase {
  8868. hasEffects(context) {
  8869. if (this.test.hasEffects(context))
  8870. return true;
  8871. return hasLoopBodyEffects(context, this.body);
  8872. }
  8873. include(context, includeChildrenRecursively) {
  8874. this.included = true;
  8875. this.test.include(context, includeChildrenRecursively);
  8876. includeLoopBody(context, this.body, includeChildrenRecursively);
  8877. }
  8878. }
  8879. class EmptyStatement extends NodeBase {
  8880. hasEffects() {
  8881. return false;
  8882. }
  8883. }
  8884. class ExportAllDeclaration extends NodeBase {
  8885. hasEffects() {
  8886. return false;
  8887. }
  8888. initialise() {
  8889. super.initialise();
  8890. this.scope.context.addExport(this);
  8891. }
  8892. render(code, _options, nodeRenderOptions) {
  8893. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  8894. }
  8895. applyDeoptimizations() { }
  8896. }
  8897. ExportAllDeclaration.prototype.needsBoundaries = true;
  8898. class FunctionDeclaration extends FunctionNode {
  8899. initialise() {
  8900. super.initialise();
  8901. if (this.id !== null) {
  8902. this.id.variable.isId = true;
  8903. }
  8904. }
  8905. parseNode(esTreeNode) {
  8906. if (esTreeNode.id !== null) {
  8907. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  8908. }
  8909. return super.parseNode(esTreeNode);
  8910. }
  8911. }
  8912. // The header ends at the first non-white-space after "default"
  8913. function getDeclarationStart(code, start) {
  8914. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  8915. }
  8916. function getFunctionIdInsertPosition(code, start) {
  8917. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  8918. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  8919. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  8920. if (generatorStarPos === -1) {
  8921. return declarationEnd;
  8922. }
  8923. return declarationEnd + generatorStarPos + 1;
  8924. }
  8925. class ExportDefaultDeclaration extends NodeBase {
  8926. include(context, includeChildrenRecursively) {
  8927. super.include(context, includeChildrenRecursively);
  8928. if (includeChildrenRecursively) {
  8929. this.scope.context.includeVariableInModule(this.variable);
  8930. }
  8931. }
  8932. initialise() {
  8933. super.initialise();
  8934. const declaration = this.declaration;
  8935. this.declarationName =
  8936. (declaration.id && declaration.id.name) || this.declaration.name;
  8937. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.scope.context.getModuleName(), this, this.scope.context);
  8938. this.scope.context.addExport(this);
  8939. }
  8940. removeAnnotations(code) {
  8941. this.declaration.removeAnnotations(code);
  8942. }
  8943. render(code, options, nodeRenderOptions) {
  8944. const { start, end } = nodeRenderOptions;
  8945. const declarationStart = getDeclarationStart(code.original, this.start);
  8946. if (this.declaration instanceof FunctionDeclaration) {
  8947. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  8948. ? getFunctionIdInsertPosition(code.original, declarationStart)
  8949. : null, options);
  8950. }
  8951. else if (this.declaration instanceof ClassDeclaration) {
  8952. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  8953. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  8954. : null, options);
  8955. }
  8956. else if (this.variable.getOriginalVariable() !== this.variable) {
  8957. // Remove altogether to prevent re-declaring the same variable
  8958. treeshakeNode(this, code, start, end);
  8959. return;
  8960. }
  8961. else if (this.variable.included) {
  8962. this.renderVariableDeclaration(code, declarationStart, options);
  8963. }
  8964. else {
  8965. code.remove(this.start, declarationStart);
  8966. this.declaration.render(code, options, {
  8967. renderedSurroundingElement: ExpressionStatement$1
  8968. });
  8969. if (code.original[this.end - 1] !== ';') {
  8970. code.appendLeft(this.end, ';');
  8971. }
  8972. return;
  8973. }
  8974. this.declaration.render(code, options);
  8975. }
  8976. applyDeoptimizations() { }
  8977. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  8978. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  8979. const name = this.variable.getName(getPropertyAccess);
  8980. // Remove `export default`
  8981. code.remove(this.start, declarationStart);
  8982. if (idInsertPosition !== null) {
  8983. code.appendLeft(idInsertPosition, ` ${name}`);
  8984. }
  8985. if (format === 'system' &&
  8986. this.declaration instanceof ClassDeclaration &&
  8987. exportNamesByVariable.has(this.variable)) {
  8988. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  8989. }
  8990. }
  8991. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  8992. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  8993. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  8994. if (systemExportNames) {
  8995. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports(${JSON.stringify(systemExportNames[0])}, `);
  8996. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  8997. }
  8998. else {
  8999. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  9000. if (!hasTrailingSemicolon) {
  9001. code.appendLeft(this.end, ';');
  9002. }
  9003. }
  9004. }
  9005. }
  9006. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  9007. class ExportNamedDeclaration extends NodeBase {
  9008. bind() {
  9009. // Do not bind specifiers
  9010. this.declaration?.bind();
  9011. }
  9012. hasEffects(context) {
  9013. return !!this.declaration?.hasEffects(context);
  9014. }
  9015. initialise() {
  9016. super.initialise();
  9017. this.scope.context.addExport(this);
  9018. }
  9019. removeAnnotations(code) {
  9020. this.declaration?.removeAnnotations(code);
  9021. }
  9022. render(code, options, nodeRenderOptions) {
  9023. const { start, end } = nodeRenderOptions;
  9024. if (this.declaration === null) {
  9025. code.remove(start, end);
  9026. }
  9027. else {
  9028. code.remove(this.start, this.declaration.start);
  9029. this.declaration.render(code, options, { end, start });
  9030. }
  9031. }
  9032. applyDeoptimizations() { }
  9033. }
  9034. ExportNamedDeclaration.prototype.needsBoundaries = true;
  9035. class ExportSpecifier extends NodeBase {
  9036. applyDeoptimizations() { }
  9037. }
  9038. class ForInStatement extends NodeBase {
  9039. createScope(parentScope) {
  9040. this.scope = new BlockScope(parentScope);
  9041. }
  9042. hasEffects(context) {
  9043. const { body, deoptimized, left, right } = this;
  9044. if (!deoptimized)
  9045. this.applyDeoptimizations();
  9046. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  9047. return true;
  9048. return hasLoopBodyEffects(context, body);
  9049. }
  9050. include(context, includeChildrenRecursively) {
  9051. const { body, deoptimized, left, right } = this;
  9052. if (!deoptimized)
  9053. this.applyDeoptimizations();
  9054. this.included = true;
  9055. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  9056. right.include(context, includeChildrenRecursively);
  9057. includeLoopBody(context, body, includeChildrenRecursively);
  9058. }
  9059. initialise() {
  9060. super.initialise();
  9061. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  9062. }
  9063. render(code, options) {
  9064. this.left.render(code, options, NO_SEMICOLON);
  9065. this.right.render(code, options, NO_SEMICOLON);
  9066. // handle no space between "in" and the right side
  9067. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  9068. code.prependLeft(this.right.start, ' ');
  9069. }
  9070. this.body.render(code, options);
  9071. }
  9072. applyDeoptimizations() {
  9073. this.deoptimized = true;
  9074. this.left.deoptimizePath(EMPTY_PATH);
  9075. this.scope.context.requestTreeshakingPass();
  9076. }
  9077. }
  9078. class ForOfStatement extends NodeBase {
  9079. get await() {
  9080. return isFlagSet(this.flags, 131072 /* Flag.await */);
  9081. }
  9082. set await(value) {
  9083. this.flags = setFlag(this.flags, 131072 /* Flag.await */, value);
  9084. }
  9085. createScope(parentScope) {
  9086. this.scope = new BlockScope(parentScope);
  9087. }
  9088. hasEffects() {
  9089. if (!this.deoptimized)
  9090. this.applyDeoptimizations();
  9091. // Placeholder until proper Symbol.Iterator support
  9092. return true;
  9093. }
  9094. include(context, includeChildrenRecursively) {
  9095. const { body, deoptimized, left, right } = this;
  9096. if (!deoptimized)
  9097. this.applyDeoptimizations();
  9098. this.included = true;
  9099. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  9100. right.include(context, includeChildrenRecursively);
  9101. includeLoopBody(context, body, includeChildrenRecursively);
  9102. }
  9103. initialise() {
  9104. super.initialise();
  9105. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  9106. }
  9107. render(code, options) {
  9108. this.left.render(code, options, NO_SEMICOLON);
  9109. this.right.render(code, options, NO_SEMICOLON);
  9110. // handle no space between "of" and the right side
  9111. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  9112. code.prependLeft(this.right.start, ' ');
  9113. }
  9114. this.body.render(code, options);
  9115. }
  9116. applyDeoptimizations() {
  9117. this.deoptimized = true;
  9118. this.left.deoptimizePath(EMPTY_PATH);
  9119. this.right.deoptimizePath(UNKNOWN_PATH);
  9120. this.scope.context.requestTreeshakingPass();
  9121. }
  9122. }
  9123. class ForStatement extends NodeBase {
  9124. createScope(parentScope) {
  9125. this.scope = new BlockScope(parentScope);
  9126. }
  9127. hasEffects(context) {
  9128. if (this.init?.hasEffects(context) ||
  9129. this.test?.hasEffects(context) ||
  9130. this.update?.hasEffects(context)) {
  9131. return true;
  9132. }
  9133. return hasLoopBodyEffects(context, this.body);
  9134. }
  9135. include(context, includeChildrenRecursively) {
  9136. this.included = true;
  9137. this.init?.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9138. this.test?.include(context, includeChildrenRecursively);
  9139. this.update?.include(context, includeChildrenRecursively);
  9140. includeLoopBody(context, this.body, includeChildrenRecursively);
  9141. }
  9142. render(code, options) {
  9143. this.init?.render(code, options, NO_SEMICOLON);
  9144. this.test?.render(code, options, NO_SEMICOLON);
  9145. this.update?.render(code, options, NO_SEMICOLON);
  9146. this.body.render(code, options);
  9147. }
  9148. }
  9149. class FunctionExpression extends FunctionNode {
  9150. createScope(parentScope) {
  9151. super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
  9152. }
  9153. parseNode(esTreeNode) {
  9154. if (esTreeNode.id !== null) {
  9155. this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
  9156. }
  9157. return super.parseNode(esTreeNode);
  9158. }
  9159. render(code, options, { renderedSurroundingElement } = BLANK) {
  9160. super.render(code, options);
  9161. if (renderedSurroundingElement === ExpressionStatement$1) {
  9162. code.appendRight(this.start, '(');
  9163. code.prependLeft(this.end, ')');
  9164. }
  9165. }
  9166. }
  9167. class TrackingScope extends BlockScope {
  9168. constructor() {
  9169. super(...arguments);
  9170. this.hoistedDeclarations = [];
  9171. }
  9172. addDeclaration(identifier, context, init, kind) {
  9173. this.hoistedDeclarations.push(identifier);
  9174. return super.addDeclaration(identifier, context, init, kind);
  9175. }
  9176. }
  9177. const unset = Symbol('unset');
  9178. class IfStatement extends NodeBase {
  9179. constructor() {
  9180. super(...arguments);
  9181. this.testValue = unset;
  9182. }
  9183. deoptimizeCache() {
  9184. this.testValue = UnknownValue;
  9185. }
  9186. hasEffects(context) {
  9187. if (this.test.hasEffects(context)) {
  9188. return true;
  9189. }
  9190. const testValue = this.getTestValue();
  9191. if (typeof testValue === 'symbol') {
  9192. const { brokenFlow } = context;
  9193. if (this.consequent.hasEffects(context))
  9194. return true;
  9195. const consequentBrokenFlow = context.brokenFlow;
  9196. context.brokenFlow = brokenFlow;
  9197. if (this.alternate === null)
  9198. return false;
  9199. if (this.alternate.hasEffects(context))
  9200. return true;
  9201. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  9202. return false;
  9203. }
  9204. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  9205. }
  9206. include(context, includeChildrenRecursively) {
  9207. this.included = true;
  9208. if (includeChildrenRecursively) {
  9209. this.includeRecursively(includeChildrenRecursively, context);
  9210. }
  9211. else {
  9212. const testValue = this.getTestValue();
  9213. if (typeof testValue === 'symbol') {
  9214. this.includeUnknownTest(context);
  9215. }
  9216. else {
  9217. this.includeKnownTest(context, testValue);
  9218. }
  9219. }
  9220. }
  9221. parseNode(esTreeNode) {
  9222. this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
  9223. if (esTreeNode.alternate) {
  9224. this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
  9225. }
  9226. return super.parseNode(esTreeNode);
  9227. }
  9228. render(code, options) {
  9229. const { snippets: { getPropertyAccess } } = options;
  9230. // Note that unknown test values are always included
  9231. const testValue = this.getTestValue();
  9232. const hoistedDeclarations = [];
  9233. const includesIfElse = this.test.included;
  9234. const noTreeshake = !this.scope.context.options.treeshake;
  9235. if (includesIfElse) {
  9236. this.test.render(code, options);
  9237. }
  9238. else {
  9239. code.remove(this.start, this.consequent.start);
  9240. }
  9241. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  9242. this.consequent.render(code, options);
  9243. }
  9244. else {
  9245. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  9246. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  9247. }
  9248. if (this.alternate) {
  9249. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  9250. if (includesIfElse) {
  9251. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  9252. code.prependLeft(this.alternate.start, ' ');
  9253. }
  9254. }
  9255. else {
  9256. code.remove(this.consequent.end, this.alternate.start);
  9257. }
  9258. this.alternate.render(code, options);
  9259. }
  9260. else {
  9261. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  9262. code.overwrite(this.alternate.start, this.end, ';');
  9263. }
  9264. else {
  9265. code.remove(this.consequent.end, this.end);
  9266. }
  9267. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  9268. }
  9269. }
  9270. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  9271. }
  9272. applyDeoptimizations() { }
  9273. getTestValue() {
  9274. if (this.testValue === unset) {
  9275. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  9276. }
  9277. return this.testValue;
  9278. }
  9279. includeKnownTest(context, testValue) {
  9280. if (this.test.shouldBeIncluded(context)) {
  9281. this.test.include(context, false);
  9282. }
  9283. if (testValue && this.consequent.shouldBeIncluded(context)) {
  9284. this.consequent.include(context, false, { asSingleStatement: true });
  9285. }
  9286. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  9287. this.alternate.include(context, false, { asSingleStatement: true });
  9288. }
  9289. }
  9290. includeRecursively(includeChildrenRecursively, context) {
  9291. this.test.include(context, includeChildrenRecursively);
  9292. this.consequent.include(context, includeChildrenRecursively);
  9293. this.alternate?.include(context, includeChildrenRecursively);
  9294. }
  9295. includeUnknownTest(context) {
  9296. this.test.include(context, false);
  9297. const { brokenFlow } = context;
  9298. let consequentBrokenFlow = false;
  9299. if (this.consequent.shouldBeIncluded(context)) {
  9300. this.consequent.include(context, false, { asSingleStatement: true });
  9301. consequentBrokenFlow = context.brokenFlow;
  9302. context.brokenFlow = brokenFlow;
  9303. }
  9304. if (this.alternate?.shouldBeIncluded(context)) {
  9305. this.alternate.include(context, false, { asSingleStatement: true });
  9306. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  9307. }
  9308. }
  9309. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  9310. const hoistedVariables = [
  9311. ...new Set(hoistedDeclarations.map(identifier => {
  9312. const variable = identifier.variable;
  9313. return variable.included ? variable.getName(getPropertyAccess) : '';
  9314. }))
  9315. ]
  9316. .filter(Boolean)
  9317. .join(', ');
  9318. if (hoistedVariables) {
  9319. const parentType = this.parent.type;
  9320. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  9321. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  9322. if (needsBraces) {
  9323. code.appendLeft(this.end, ` }`);
  9324. }
  9325. }
  9326. }
  9327. shouldKeepAlternateBranch() {
  9328. let currentParent = this.parent;
  9329. do {
  9330. if (currentParent instanceof IfStatement && currentParent.alternate) {
  9331. return true;
  9332. }
  9333. if (currentParent instanceof BlockStatement) {
  9334. return false;
  9335. }
  9336. currentParent = currentParent.parent;
  9337. } while (currentParent);
  9338. return false;
  9339. }
  9340. }
  9341. class ImportAttribute extends NodeBase {
  9342. }
  9343. class ImportDeclaration extends NodeBase {
  9344. // Do not bind specifiers or attributes
  9345. bind() { }
  9346. hasEffects() {
  9347. return false;
  9348. }
  9349. initialise() {
  9350. super.initialise();
  9351. this.scope.context.addImport(this);
  9352. }
  9353. render(code, _options, nodeRenderOptions) {
  9354. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  9355. }
  9356. applyDeoptimizations() { }
  9357. }
  9358. ImportDeclaration.prototype.needsBoundaries = true;
  9359. class ImportDefaultSpecifier extends NodeBase {
  9360. applyDeoptimizations() { }
  9361. }
  9362. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  9363. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  9364. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  9365. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  9366. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  9367. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  9368. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  9369. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  9370. const defaultInteropHelpersByInteropType = {
  9371. auto: INTEROP_DEFAULT_VARIABLE,
  9372. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  9373. default: null,
  9374. defaultOnly: null,
  9375. esModule: null
  9376. };
  9377. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  9378. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  9379. const namespaceInteropHelpersByInteropType = {
  9380. auto: INTEROP_NAMESPACE_VARIABLE,
  9381. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  9382. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  9383. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  9384. esModule: null
  9385. };
  9386. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  9387. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, symbols) => {
  9388. const usedHelpers = new Set(additionalHelpers);
  9389. for (const variable of HELPER_NAMES) {
  9390. if (accessedGlobals.has(variable)) {
  9391. usedHelpers.add(variable);
  9392. }
  9393. }
  9394. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  9395. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, symbols, usedHelpers)
  9396. : '').join('');
  9397. };
  9398. const HELPER_GENERATORS = {
  9399. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  9400. return `var${_}${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof${_}document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  9401. },
  9402. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  9403. const { _, getDirectReturnFunction, n } = snippets;
  9404. const [left, right] = getDirectReturnFunction(['e'], {
  9405. functionReturn: true,
  9406. lineBreakIndent: null,
  9407. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  9408. });
  9409. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  9410. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9411. },
  9412. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  9413. const { _, getDirectReturnFunction, n } = snippets;
  9414. const [left, right] = getDirectReturnFunction(['e'], {
  9415. functionReturn: true,
  9416. lineBreakIndent: null,
  9417. name: INTEROP_DEFAULT_VARIABLE
  9418. });
  9419. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  9420. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9421. },
  9422. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  9423. const { _, getDirectReturnFunction, n } = snippets;
  9424. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  9425. const [left, right] = getDirectReturnFunction(['e'], {
  9426. functionReturn: true,
  9427. lineBreakIndent: null,
  9428. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  9429. });
  9430. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  9431. }
  9432. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  9433. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  9434. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  9435. `}${n}${n}`);
  9436. },
  9437. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, symbols) {
  9438. const { getDirectReturnFunction, getObject, n, _ } = snippets;
  9439. const [left, right] = getDirectReturnFunction(['e'], {
  9440. functionReturn: true,
  9441. lineBreakIndent: null,
  9442. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9443. });
  9444. return `${left}${getFrozen(freeze, getWithToStringTag(symbols, getObject([
  9445. [null, `__proto__:${_}null`],
  9446. ['default', 'e']
  9447. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  9448. },
  9449. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  9450. const { _, n } = snippets;
  9451. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  9452. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  9453. `}${n}${n}`);
  9454. },
  9455. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  9456. const { _, getDirectReturnFunction, n } = snippets;
  9457. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  9458. const [left, right] = getDirectReturnFunction(['e'], {
  9459. functionReturn: true,
  9460. lineBreakIndent: null,
  9461. name: INTEROP_NAMESPACE_VARIABLE
  9462. });
  9463. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  9464. }
  9465. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  9466. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  9467. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  9468. `}${n}${n}`);
  9469. },
  9470. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  9471. const { _, cnst, n } = snippets;
  9472. const useForEach = cnst === 'var' && liveBindings;
  9473. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  9474. `${t}${loopOverNamespaces(`{${n}` +
  9475. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  9476. (liveBindings
  9477. ? useForEach
  9478. ? copyOwnPropertyLiveBinding
  9479. : copyPropertyLiveBinding
  9480. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  9481. `${t}${t}${t}}${n}` +
  9482. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  9483. `${t}return ${getFrozen(freeze, getWithToStringTag(symbols, 'n', snippets))};${n}` +
  9484. `}${n}${n}`);
  9485. }
  9486. };
  9487. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  9488. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  9489. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  9490. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, symbols) => {
  9491. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  9492. const copyProperty = `{${n}` +
  9493. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  9494. `${index}${t}}`;
  9495. return (`${index}${cnst} n${_}=${_}Object.create(null${symbols ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` +
  9496. `${index}if${_}(e)${_}{${n}` +
  9497. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  9498. `${index}}${n}` +
  9499. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  9500. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  9501. };
  9502. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  9503. ? `for${_}(${cnst} k in e)${_}${body}`
  9504. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9505. isAsync: false,
  9506. name: null
  9507. })}${body})${s}`;
  9508. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  9509. if (useForEach) {
  9510. const [left, right] = getDirectReturnFunction(['e'], {
  9511. functionReturn: false,
  9512. lineBreakIndent: { base: t, t },
  9513. name: null
  9514. });
  9515. return (`m.forEach(${left}` +
  9516. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9517. isAsync: false,
  9518. name: null
  9519. })}${body})${right});`);
  9520. }
  9521. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  9522. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  9523. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  9524. };
  9525. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  9526. const { _, n } = snippets;
  9527. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  9528. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  9529. `${index}}${n}`);
  9530. };
  9531. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  9532. const [left, right] = getDirectReturnFunction([], {
  9533. functionReturn: true,
  9534. lineBreakIndent: null,
  9535. name: null
  9536. });
  9537. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9538. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9539. `${index}${t}enumerable:${_}true,${n}` +
  9540. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  9541. `${index}});${n}`);
  9542. };
  9543. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  9544. const [left, right] = getDirectReturnFunction([], {
  9545. functionReturn: true,
  9546. lineBreakIndent: null,
  9547. name: null
  9548. });
  9549. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9550. `${index}if${_}(d)${_}{${n}` +
  9551. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9552. `${index}${t}${t}enumerable:${_}true,${n}` +
  9553. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  9554. `${index}${t}});${n}` +
  9555. `${index}}${n}`);
  9556. };
  9557. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  9558. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  9559. const getWithToStringTag = (symbols, fragment, { _, getObject }) => symbols
  9560. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  9561. : fragment;
  9562. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  9563. function getToStringTagValue(getObject) {
  9564. return getObject([['value', "'Module'"]], {
  9565. lineBreakIndent: null
  9566. });
  9567. }
  9568. function isReassignedExportsMember(variable, exportNamesByVariable) {
  9569. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  9570. }
  9571. class VariableDeclarator extends NodeBase {
  9572. declareDeclarator(kind, isUsingDeclaration) {
  9573. this.isUsingDeclaration = isUsingDeclaration;
  9574. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  9575. }
  9576. deoptimizePath(path) {
  9577. this.id.deoptimizePath(path);
  9578. }
  9579. hasEffects(context) {
  9580. if (!this.deoptimized)
  9581. this.applyDeoptimizations();
  9582. const initEffect = this.init?.hasEffects(context);
  9583. this.id.markDeclarationReached();
  9584. return initEffect || this.id.hasEffects(context) || this.isUsingDeclaration;
  9585. }
  9586. include(context, includeChildrenRecursively) {
  9587. const { deoptimized, id, init } = this;
  9588. if (!deoptimized)
  9589. this.applyDeoptimizations();
  9590. this.included = true;
  9591. init?.include(context, includeChildrenRecursively);
  9592. id.markDeclarationReached();
  9593. if (includeChildrenRecursively || id.shouldBeIncluded(context)) {
  9594. id.include(context, includeChildrenRecursively);
  9595. }
  9596. }
  9597. removeAnnotations(code) {
  9598. this.init?.removeAnnotations(code);
  9599. }
  9600. render(code, options) {
  9601. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  9602. const { end, id, init, start } = this;
  9603. const renderId = id.included || this.isUsingDeclaration;
  9604. if (renderId) {
  9605. id.render(code, options);
  9606. }
  9607. else {
  9608. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  9609. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  9610. }
  9611. if (init) {
  9612. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  9613. const renderedVariable = id.variable.getName(getPropertyAccess);
  9614. if (renderedVariable !== id.name) {
  9615. code.appendLeft(init.start + 5, ` ${id.name}`);
  9616. }
  9617. }
  9618. init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  9619. }
  9620. else if (id instanceof Identifier &&
  9621. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  9622. code.appendLeft(end, `${_}=${_}void 0`);
  9623. }
  9624. }
  9625. applyDeoptimizations() {
  9626. this.deoptimized = true;
  9627. const { id, init } = this;
  9628. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  9629. const { name, variable } = id;
  9630. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  9631. if (accessedVariable !== variable) {
  9632. accessedVariable.forbidName(name);
  9633. }
  9634. }
  9635. }
  9636. }
  9637. }
  9638. class ImportExpression extends NodeBase {
  9639. constructor() {
  9640. super(...arguments);
  9641. this.inlineNamespace = null;
  9642. this.attributes = null;
  9643. this.mechanism = null;
  9644. this.namespaceExportName = undefined;
  9645. this.resolution = null;
  9646. this.resolutionString = null;
  9647. }
  9648. // Do not bind attributes
  9649. bind() {
  9650. this.source.bind();
  9651. }
  9652. /**
  9653. * Get imported variables for deterministic usage, valid cases are:
  9654. *
  9655. * - `const { foo } = await import('bar')`.
  9656. * - `(await import('bar')).foo`
  9657. * - `import('bar').then(({ foo }) => {})`
  9658. *
  9659. * Returns empty array if it's side-effect only import.
  9660. * Returns undefined if it's not fully deterministic.
  9661. */
  9662. getDeterministicImportedNames() {
  9663. const parent1 = this.parent;
  9664. // Side-effect only: import('bar')
  9665. if (parent1 instanceof ExpressionStatement) {
  9666. return EMPTY_ARRAY;
  9667. }
  9668. if (parent1 instanceof AwaitExpression) {
  9669. const parent2 = parent1.parent;
  9670. // Side-effect only: await import('bar')
  9671. if (parent2 instanceof ExpressionStatement) {
  9672. return EMPTY_ARRAY;
  9673. }
  9674. // Case 1: const { foo } = await import('bar')
  9675. if (parent2 instanceof VariableDeclarator) {
  9676. const declaration = parent2.id;
  9677. return declaration instanceof ObjectPattern
  9678. ? getDeterministicObjectDestructure(declaration)
  9679. : undefined;
  9680. }
  9681. // Case 2: (await import('bar')).foo
  9682. if (parent2 instanceof MemberExpression) {
  9683. const id = parent2.property;
  9684. if (!parent2.computed && id instanceof Identifier) {
  9685. return [id.name];
  9686. }
  9687. }
  9688. return;
  9689. }
  9690. // Case 3: import('bar').then(({ foo }) => {})
  9691. if (parent1 instanceof MemberExpression) {
  9692. const callExpression = parent1.parent;
  9693. const property = parent1.property;
  9694. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  9695. return;
  9696. }
  9697. const memberName = property.name;
  9698. // side-effect only, when only chaining .catch or .finally
  9699. if (callExpression.parent instanceof ExpressionStatement &&
  9700. ['catch', 'finally'].includes(memberName)) {
  9701. return EMPTY_ARRAY;
  9702. }
  9703. if (memberName !== 'then')
  9704. return;
  9705. // Side-effect only: import('bar').then()
  9706. if (callExpression.arguments.length === 0) {
  9707. return EMPTY_ARRAY;
  9708. }
  9709. const argument = callExpression.arguments[0];
  9710. if (callExpression.arguments.length !== 1 ||
  9711. !(argument instanceof ArrowFunctionExpression || argument instanceof FunctionExpression)) {
  9712. return;
  9713. }
  9714. // Side-effect only: import('bar').then(() => {})
  9715. if (argument.params.length === 0) {
  9716. return EMPTY_ARRAY;
  9717. }
  9718. const declaration = argument.params[0];
  9719. if (argument.params.length === 1 && declaration instanceof ObjectPattern) {
  9720. return getDeterministicObjectDestructure(declaration);
  9721. }
  9722. return;
  9723. }
  9724. }
  9725. hasEffects() {
  9726. return true;
  9727. }
  9728. include(context, includeChildrenRecursively) {
  9729. if (!this.included) {
  9730. this.included = true;
  9731. this.scope.context.includeDynamicImport(this);
  9732. this.scope.addAccessedDynamicImport(this);
  9733. }
  9734. this.source.include(context, includeChildrenRecursively);
  9735. }
  9736. initialise() {
  9737. super.initialise();
  9738. this.scope.context.addDynamicImport(this);
  9739. }
  9740. parseNode(esTreeNode) {
  9741. this.sourceAstNode = esTreeNode.source;
  9742. return super.parseNode(esTreeNode);
  9743. }
  9744. render(code, options) {
  9745. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess } } = options;
  9746. if (this.inlineNamespace) {
  9747. const [left, right] = getDirectReturnFunction([], {
  9748. functionReturn: true,
  9749. lineBreakIndent: null,
  9750. name: null
  9751. });
  9752. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  9753. return;
  9754. }
  9755. if (this.mechanism) {
  9756. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  9757. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  9758. }
  9759. if (this.resolutionString) {
  9760. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  9761. if (this.namespaceExportName) {
  9762. const [left, right] = getDirectReturnFunction(['n'], {
  9763. functionReturn: true,
  9764. lineBreakIndent: null,
  9765. name: null
  9766. });
  9767. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  9768. }
  9769. }
  9770. else {
  9771. this.source.render(code, options);
  9772. }
  9773. if (this.attributes !== true) {
  9774. if (this.options) {
  9775. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  9776. }
  9777. if (this.attributes) {
  9778. code.appendLeft(this.end - 1, `,${_}${getObject([['assert', this.attributes]], {
  9779. lineBreakIndent: null
  9780. })}`);
  9781. }
  9782. }
  9783. }
  9784. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, attributes) {
  9785. const { format } = options;
  9786. this.inlineNamespace = null;
  9787. this.resolution = resolution;
  9788. this.resolutionString = resolutionString;
  9789. this.namespaceExportName = namespaceExportName;
  9790. this.attributes = attributes;
  9791. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  9792. let helper;
  9793. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  9794. if (helper) {
  9795. accessedGlobals.push(helper);
  9796. }
  9797. if (accessedGlobals.length > 0) {
  9798. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  9799. }
  9800. }
  9801. setInternalResolution(inlineNamespace) {
  9802. this.inlineNamespace = inlineNamespace;
  9803. }
  9804. applyDeoptimizations() { }
  9805. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  9806. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  9807. {
  9808. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  9809. format,
  9810. moduleId: this.scope.context.module.id,
  9811. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  9812. }
  9813. ]);
  9814. if (mechanism) {
  9815. return { helper: null, mechanism };
  9816. }
  9817. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  9818. switch (format) {
  9819. case 'cjs': {
  9820. if (dynamicImportInCjs &&
  9821. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  9822. return { helper: null, mechanism: null };
  9823. }
  9824. const helper = getInteropHelper(resolution, exportMode, interop);
  9825. let left = `require(`;
  9826. let right = `)`;
  9827. if (helper) {
  9828. left = `/*#__PURE__*/${helper}(${left}`;
  9829. right += ')';
  9830. }
  9831. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  9832. functionReturn: true,
  9833. lineBreakIndent: null,
  9834. name: null
  9835. });
  9836. left = `Promise.resolve().then(${functionLeft}${left}`;
  9837. right += `${functionRight})`;
  9838. if (!arrowFunctions && hasDynamicTarget) {
  9839. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9840. needsArrowReturnParens: false,
  9841. needsWrappedFunction: true
  9842. });
  9843. right = ')';
  9844. }
  9845. return {
  9846. helper,
  9847. mechanism: { left, right }
  9848. };
  9849. }
  9850. case 'amd': {
  9851. const resolve = compact ? 'c' : 'resolve';
  9852. const reject = compact ? 'e' : 'reject';
  9853. const helper = getInteropHelper(resolution, exportMode, interop);
  9854. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  9855. functionReturn: false,
  9856. lineBreakIndent: null,
  9857. name: null
  9858. });
  9859. const resolveNamespace = helper
  9860. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  9861. : resolve;
  9862. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  9863. functionReturn: false,
  9864. lineBreakIndent: null,
  9865. name: null
  9866. });
  9867. let left = `new Promise(${handlerLeft}require([`;
  9868. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  9869. if (!arrowFunctions && hasDynamicTarget) {
  9870. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9871. needsArrowReturnParens: false,
  9872. needsWrappedFunction: true
  9873. });
  9874. right = ')';
  9875. }
  9876. return {
  9877. helper,
  9878. mechanism: { left, right }
  9879. };
  9880. }
  9881. case 'system': {
  9882. return {
  9883. helper: null,
  9884. mechanism: {
  9885. left: 'module.import(',
  9886. right: ')'
  9887. }
  9888. };
  9889. }
  9890. }
  9891. return { helper: null, mechanism: null };
  9892. }
  9893. }
  9894. function getInteropHelper(resolution, exportMode, interop) {
  9895. return exportMode === 'external'
  9896. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  9897. : exportMode === 'default'
  9898. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9899. : null;
  9900. }
  9901. const accessedImportGlobals = {
  9902. amd: ['require'],
  9903. cjs: ['require'],
  9904. system: ['module']
  9905. };
  9906. function getDeterministicObjectDestructure(objectPattern) {
  9907. const variables = [];
  9908. for (const property of objectPattern.properties) {
  9909. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  9910. return;
  9911. variables.push(property.key.name);
  9912. }
  9913. return variables;
  9914. }
  9915. class ImportNamespaceSpecifier extends NodeBase {
  9916. applyDeoptimizations() { }
  9917. }
  9918. class ImportSpecifier extends NodeBase {
  9919. applyDeoptimizations() { }
  9920. }
  9921. class LabeledStatement extends NodeBase {
  9922. hasEffects(context) {
  9923. const { brokenFlow, includedLabels } = context;
  9924. context.ignore.labels.add(this.label.name);
  9925. context.includedLabels = new Set();
  9926. let bodyHasEffects = false;
  9927. if (this.body.hasEffects(context)) {
  9928. bodyHasEffects = true;
  9929. }
  9930. else {
  9931. context.ignore.labels.delete(this.label.name);
  9932. if (context.includedLabels.has(this.label.name)) {
  9933. context.includedLabels.delete(this.label.name);
  9934. context.brokenFlow = brokenFlow;
  9935. }
  9936. }
  9937. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  9938. return bodyHasEffects;
  9939. }
  9940. include(context, includeChildrenRecursively) {
  9941. this.included = true;
  9942. const { brokenFlow, includedLabels } = context;
  9943. context.includedLabels = new Set();
  9944. this.body.include(context, includeChildrenRecursively);
  9945. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  9946. this.label.include();
  9947. context.includedLabels.delete(this.label.name);
  9948. context.brokenFlow = brokenFlow;
  9949. }
  9950. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  9951. }
  9952. render(code, options) {
  9953. if (this.label.included) {
  9954. this.label.render(code, options);
  9955. }
  9956. else {
  9957. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  9958. }
  9959. this.body.render(code, options);
  9960. }
  9961. }
  9962. class LogicalExpression extends NodeBase {
  9963. constructor() {
  9964. super(...arguments);
  9965. // We collect deoptimization information if usedBranch !== null
  9966. this.expressionsToBeDeoptimized = [];
  9967. this.usedBranch = null;
  9968. }
  9969. //private isBranchResolutionAnalysed = false;
  9970. get isBranchResolutionAnalysed() {
  9971. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  9972. }
  9973. set isBranchResolutionAnalysed(value) {
  9974. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  9975. }
  9976. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9977. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9978. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9979. }
  9980. deoptimizeCache() {
  9981. if (this.usedBranch) {
  9982. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  9983. this.usedBranch = null;
  9984. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  9985. const { scope: { context }, expressionsToBeDeoptimized } = this;
  9986. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  9987. for (const expression of expressionsToBeDeoptimized) {
  9988. expression.deoptimizeCache();
  9989. }
  9990. // Request another pass because we need to ensure "include" runs again if
  9991. // it is rendered
  9992. context.requestTreeshakingPass();
  9993. }
  9994. }
  9995. deoptimizePath(path) {
  9996. const usedBranch = this.getUsedBranch();
  9997. if (usedBranch) {
  9998. usedBranch.deoptimizePath(path);
  9999. }
  10000. else {
  10001. this.left.deoptimizePath(path);
  10002. this.right.deoptimizePath(path);
  10003. }
  10004. }
  10005. getLiteralValueAtPath(path, recursionTracker, origin) {
  10006. const usedBranch = this.getUsedBranch();
  10007. if (!usedBranch)
  10008. return UnknownValue;
  10009. this.expressionsToBeDeoptimized.push(origin);
  10010. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  10011. }
  10012. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10013. const usedBranch = this.getUsedBranch();
  10014. if (!usedBranch)
  10015. return [
  10016. new MultiExpression([
  10017. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  10018. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  10019. ]),
  10020. false
  10021. ];
  10022. this.expressionsToBeDeoptimized.push(origin);
  10023. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10024. }
  10025. hasEffects(context) {
  10026. if (this.left.hasEffects(context)) {
  10027. return true;
  10028. }
  10029. if (this.getUsedBranch() !== this.left) {
  10030. return this.right.hasEffects(context);
  10031. }
  10032. return false;
  10033. }
  10034. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10035. const usedBranch = this.getUsedBranch();
  10036. if (!usedBranch) {
  10037. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  10038. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  10039. }
  10040. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  10041. }
  10042. include(context, includeChildrenRecursively) {
  10043. this.included = true;
  10044. const usedBranch = this.getUsedBranch();
  10045. if (includeChildrenRecursively ||
  10046. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  10047. !usedBranch) {
  10048. this.left.include(context, includeChildrenRecursively);
  10049. this.right.include(context, includeChildrenRecursively);
  10050. }
  10051. else {
  10052. usedBranch.include(context, includeChildrenRecursively);
  10053. }
  10054. }
  10055. removeAnnotations(code) {
  10056. this.left.removeAnnotations(code);
  10057. }
  10058. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  10059. if (!this.left.included || !this.right.included) {
  10060. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  10061. if (this.right.included) {
  10062. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  10063. code.remove(this.start, removePos);
  10064. if (preventASI) {
  10065. removeLineBreaks(code, removePos, this.right.start);
  10066. }
  10067. this.left.removeAnnotations(code);
  10068. }
  10069. else {
  10070. code.remove(operatorPos, this.end);
  10071. }
  10072. this.getUsedBranch().render(code, options, {
  10073. isCalleeOfRenderedParent,
  10074. preventASI,
  10075. renderedParentType: renderedParentType || this.parent.type,
  10076. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  10077. });
  10078. }
  10079. else {
  10080. this.left.render(code, options, {
  10081. preventASI,
  10082. renderedSurroundingElement
  10083. });
  10084. this.right.render(code, options);
  10085. }
  10086. }
  10087. getUsedBranch() {
  10088. if (!this.isBranchResolutionAnalysed) {
  10089. this.isBranchResolutionAnalysed = true;
  10090. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10091. if (typeof leftValue === 'symbol') {
  10092. return null;
  10093. }
  10094. else {
  10095. this.usedBranch =
  10096. (this.operator === '||' && leftValue) ||
  10097. (this.operator === '&&' && !leftValue) ||
  10098. (this.operator === '??' && leftValue != null)
  10099. ? this.left
  10100. : this.right;
  10101. }
  10102. }
  10103. return this.usedBranch;
  10104. }
  10105. }
  10106. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  10107. const IMPORT = 'import';
  10108. class MetaProperty extends NodeBase {
  10109. constructor() {
  10110. super(...arguments);
  10111. this.metaProperty = null;
  10112. this.preliminaryChunkId = null;
  10113. this.referenceId = null;
  10114. }
  10115. getReferencedFileName(outputPluginDriver) {
  10116. const { meta: { name }, metaProperty } = this;
  10117. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  10118. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  10119. }
  10120. return null;
  10121. }
  10122. hasEffects() {
  10123. return false;
  10124. }
  10125. hasEffectsOnInteractionAtPath(path, { type }) {
  10126. return path.length > 1 || type !== INTERACTION_ACCESSED;
  10127. }
  10128. include() {
  10129. if (!this.included) {
  10130. this.included = true;
  10131. if (this.meta.name === IMPORT) {
  10132. this.scope.context.addImportMeta(this);
  10133. const parent = this.parent;
  10134. const metaProperty = (this.metaProperty =
  10135. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  10136. ? parent.propertyKey
  10137. : null);
  10138. if (metaProperty?.startsWith(FILE_PREFIX)) {
  10139. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  10140. }
  10141. }
  10142. }
  10143. }
  10144. render(code, renderOptions) {
  10145. const { format, pluginDriver, snippets } = renderOptions;
  10146. const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  10147. const { id: moduleId } = module;
  10148. if (name !== IMPORT)
  10149. return;
  10150. const chunkId = preliminaryChunkId;
  10151. if (referenceId) {
  10152. const fileName = pluginDriver.getFileName(referenceId);
  10153. const relativePath = normalize(relative(dirname(chunkId), fileName));
  10154. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  10155. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  10156. ]) || relativeUrlMechanisms[format](relativePath);
  10157. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10158. return;
  10159. }
  10160. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  10161. metaProperty,
  10162. { chunkId, format, moduleId }
  10163. ]);
  10164. if (!replacement) {
  10165. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  10166. renderOptions.accessedDocumentCurrentScript ||=
  10167. formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
  10168. }
  10169. if (typeof replacement === 'string') {
  10170. if (parent instanceof MemberExpression) {
  10171. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10172. }
  10173. else {
  10174. code.overwrite(start, end, replacement, { contentOnly: true });
  10175. }
  10176. }
  10177. }
  10178. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  10179. this.preliminaryChunkId = preliminaryChunkId;
  10180. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  10181. if (accessedGlobals.length > 0) {
  10182. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  10183. }
  10184. }
  10185. }
  10186. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  10187. const accessedMetaUrlGlobals = {
  10188. amd: ['document', 'module', 'URL'],
  10189. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  10190. es: [],
  10191. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  10192. system: ['module'],
  10193. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  10194. };
  10195. const accessedFileUrlGlobals = {
  10196. amd: ['document', 'require', 'URL'],
  10197. cjs: ['document', 'require', 'URL'],
  10198. es: [],
  10199. iife: ['document', 'URL'],
  10200. system: ['module', 'URL'],
  10201. umd: ['document', 'require', 'URL']
  10202. };
  10203. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  10204. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
  10205. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  10206. const urlMechanism = getUrl(chunkId);
  10207. return property === null
  10208. ? `({ url: ${urlMechanism} })`
  10209. : property === 'url'
  10210. ? urlMechanism
  10211. : 'undefined';
  10212. };
  10213. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  10214. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
  10215. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(${DOCUMENT_CURRENT_SCRIPT} && ${DOCUMENT_CURRENT_SCRIPT}.src || new URL('${escapeId(chunkId)}', document.baseURI).href)`;
  10216. const relativeUrlMechanisms = {
  10217. amd: relativePath => {
  10218. if (relativePath[0] !== '.')
  10219. relativePath = './' + relativePath;
  10220. return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
  10221. },
  10222. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  10223. es: relativePath => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`),
  10224. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  10225. system: relativePath => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`),
  10226. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  10227. };
  10228. const importMetaMechanisms = {
  10229. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  10230. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  10231. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  10232. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  10233. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  10234. };
  10235. class NewExpression extends NodeBase {
  10236. hasEffects(context) {
  10237. try {
  10238. for (const argument of this.arguments) {
  10239. if (argument.hasEffects(context))
  10240. return true;
  10241. }
  10242. if (this.annotationPure) {
  10243. return false;
  10244. }
  10245. return (this.callee.hasEffects(context) ||
  10246. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10247. }
  10248. finally {
  10249. if (!this.deoptimized)
  10250. this.applyDeoptimizations();
  10251. }
  10252. }
  10253. hasEffectsOnInteractionAtPath(path, { type }) {
  10254. return path.length > 0 || type !== INTERACTION_ACCESSED;
  10255. }
  10256. include(context, includeChildrenRecursively) {
  10257. if (!this.deoptimized)
  10258. this.applyDeoptimizations();
  10259. if (includeChildrenRecursively) {
  10260. super.include(context, includeChildrenRecursively);
  10261. }
  10262. else {
  10263. this.included = true;
  10264. this.callee.include(context, false);
  10265. }
  10266. this.callee.includeCallArguments(context, this.arguments);
  10267. }
  10268. initialise() {
  10269. super.initialise();
  10270. this.interaction = {
  10271. args: [null, ...this.arguments],
  10272. type: INTERACTION_CALLED,
  10273. withNew: true
  10274. };
  10275. if (this.annotations &&
  10276. this.scope.context.options.treeshake.annotations) {
  10277. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  10278. }
  10279. }
  10280. render(code, options) {
  10281. this.callee.render(code, options);
  10282. renderCallArguments(code, options, this);
  10283. }
  10284. applyDeoptimizations() {
  10285. this.deoptimized = true;
  10286. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  10287. this.scope.context.requestTreeshakingPass();
  10288. }
  10289. }
  10290. class ObjectExpression extends NodeBase {
  10291. constructor() {
  10292. super(...arguments);
  10293. this.objectEntity = null;
  10294. }
  10295. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10296. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10297. }
  10298. deoptimizeCache() {
  10299. this.getObjectEntity().deoptimizeAllProperties();
  10300. }
  10301. deoptimizePath(path) {
  10302. this.getObjectEntity().deoptimizePath(path);
  10303. }
  10304. getLiteralValueAtPath(path, recursionTracker, origin) {
  10305. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  10306. }
  10307. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10308. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10309. }
  10310. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10311. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  10312. }
  10313. render(code, options, { renderedSurroundingElement } = BLANK) {
  10314. super.render(code, options);
  10315. if (renderedSurroundingElement === ExpressionStatement$1 ||
  10316. renderedSurroundingElement === ArrowFunctionExpression$1) {
  10317. code.appendRight(this.start, '(');
  10318. code.prependLeft(this.end, ')');
  10319. }
  10320. }
  10321. applyDeoptimizations() { }
  10322. getObjectEntity() {
  10323. if (this.objectEntity !== null) {
  10324. return this.objectEntity;
  10325. }
  10326. let prototype = OBJECT_PROTOTYPE;
  10327. const properties = [];
  10328. for (const property of this.properties) {
  10329. if (property instanceof SpreadElement) {
  10330. properties.push({ key: UnknownKey, kind: 'init', property });
  10331. continue;
  10332. }
  10333. let key;
  10334. if (property.computed) {
  10335. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10336. if (typeof keyValue === 'symbol') {
  10337. properties.push({ key: UnknownKey, kind: property.kind, property });
  10338. continue;
  10339. }
  10340. else {
  10341. key = String(keyValue);
  10342. }
  10343. }
  10344. else {
  10345. key =
  10346. property.key instanceof Identifier
  10347. ? property.key.name
  10348. : String(property.key.value);
  10349. if (key === '__proto__' && property.kind === 'init') {
  10350. prototype =
  10351. property.value instanceof Literal && property.value.value === null
  10352. ? null
  10353. : property.value;
  10354. continue;
  10355. }
  10356. }
  10357. properties.push({ key, kind: property.kind, property });
  10358. }
  10359. return (this.objectEntity = new ObjectEntity(properties, prototype));
  10360. }
  10361. }
  10362. class PanicError extends NodeBase {
  10363. initialise() {
  10364. const id = this.scope.context.module.id;
  10365. // This simulates the current nested error structure. We could also just
  10366. // replace it with a flat error.
  10367. const parseError = getRollupError(logParseError(this.message));
  10368. const moduleParseError = logModuleParseError(parseError, id);
  10369. return error(moduleParseError);
  10370. }
  10371. }
  10372. class ParseError extends NodeBase {
  10373. initialise() {
  10374. const pos = this.start;
  10375. const id = this.scope.context.module.id;
  10376. // This simulates the current nested error structure. We could also just
  10377. // replace it with a flat error.
  10378. const parseError = getRollupError(logParseError(this.message, pos));
  10379. const moduleParseError = logModuleParseError(parseError, id);
  10380. this.scope.context.error(moduleParseError, pos);
  10381. }
  10382. }
  10383. class PrivateIdentifier extends NodeBase {
  10384. }
  10385. class Program extends NodeBase {
  10386. constructor() {
  10387. super(...arguments);
  10388. this.hasCachedEffect = null;
  10389. this.hasLoggedEffect = false;
  10390. }
  10391. hasCachedEffects() {
  10392. if (!this.included) {
  10393. return false;
  10394. }
  10395. return this.hasCachedEffect === null
  10396. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  10397. : this.hasCachedEffect;
  10398. }
  10399. hasEffects(context) {
  10400. for (const node of this.body) {
  10401. if (node.hasEffects(context)) {
  10402. if (this.scope.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  10403. this.hasLoggedEffect = true;
  10404. const { code, log, module } = this.scope.context;
  10405. log(LOGLEVEL_INFO, logFirstSideEffect(code, module.id, locate(code, node.start, { offsetLine: 1 })), node.start);
  10406. }
  10407. return (this.hasCachedEffect = true);
  10408. }
  10409. }
  10410. return false;
  10411. }
  10412. include(context, includeChildrenRecursively) {
  10413. this.included = true;
  10414. for (const node of this.body) {
  10415. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  10416. node.include(context, includeChildrenRecursively);
  10417. }
  10418. }
  10419. }
  10420. initialise() {
  10421. super.initialise();
  10422. if (this.invalidAnnotations)
  10423. for (const { start, end, type } of this.invalidAnnotations) {
  10424. this.scope.context.magicString.remove(start, end);
  10425. if (type === 'pure' || type === 'noSideEffects') {
  10426. this.scope.context.log(LOGLEVEL_WARN, logInvalidAnnotation(this.scope.context.code.slice(start, end), this.scope.context.module.id, type), start);
  10427. }
  10428. }
  10429. }
  10430. render(code, options) {
  10431. let start = this.start;
  10432. if (code.original.startsWith('#!')) {
  10433. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  10434. code.remove(0, start);
  10435. }
  10436. if (this.body.length > 0) {
  10437. // Keep all consecutive lines that start with a comment
  10438. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  10439. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  10440. if (firstLineBreak[0] === -1) {
  10441. break;
  10442. }
  10443. start += firstLineBreak[1];
  10444. }
  10445. renderStatementList(this.body, code, start, this.end, options);
  10446. }
  10447. else {
  10448. super.render(code, options);
  10449. }
  10450. }
  10451. applyDeoptimizations() { }
  10452. }
  10453. class Property extends MethodBase {
  10454. constructor() {
  10455. super(...arguments);
  10456. this.declarationInit = null;
  10457. }
  10458. //declare method: boolean;
  10459. get method() {
  10460. return isFlagSet(this.flags, 262144 /* Flag.method */);
  10461. }
  10462. set method(value) {
  10463. this.flags = setFlag(this.flags, 262144 /* Flag.method */, value);
  10464. }
  10465. //declare shorthand: boolean;
  10466. get shorthand() {
  10467. return isFlagSet(this.flags, 524288 /* Flag.shorthand */);
  10468. }
  10469. set shorthand(value) {
  10470. this.flags = setFlag(this.flags, 524288 /* Flag.shorthand */, value);
  10471. }
  10472. declare(kind, init) {
  10473. this.declarationInit = init;
  10474. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  10475. }
  10476. hasEffects(context) {
  10477. if (!this.deoptimized)
  10478. this.applyDeoptimizations();
  10479. const propertyReadSideEffects = this.scope.context.options.treeshake.propertyReadSideEffects;
  10480. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  10481. this.key.hasEffects(context) ||
  10482. this.value.hasEffects(context));
  10483. }
  10484. markDeclarationReached() {
  10485. this.value.markDeclarationReached();
  10486. }
  10487. render(code, options) {
  10488. if (!this.shorthand) {
  10489. this.key.render(code, options);
  10490. }
  10491. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  10492. }
  10493. applyDeoptimizations() {
  10494. this.deoptimized = true;
  10495. if (this.declarationInit !== null) {
  10496. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  10497. this.scope.context.requestTreeshakingPass();
  10498. }
  10499. }
  10500. }
  10501. class PropertyDefinition extends NodeBase {
  10502. get computed() {
  10503. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  10504. }
  10505. set computed(value) {
  10506. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  10507. }
  10508. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10509. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10510. }
  10511. deoptimizePath(path) {
  10512. this.value?.deoptimizePath(path);
  10513. }
  10514. getLiteralValueAtPath(path, recursionTracker, origin) {
  10515. return this.value
  10516. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  10517. : UnknownValue;
  10518. }
  10519. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10520. return this.value
  10521. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  10522. : UNKNOWN_RETURN_EXPRESSION;
  10523. }
  10524. hasEffects(context) {
  10525. return this.key.hasEffects(context) || (this.static && !!this.value?.hasEffects(context));
  10526. }
  10527. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10528. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  10529. }
  10530. applyDeoptimizations() { }
  10531. }
  10532. class ReturnStatement extends NodeBase {
  10533. hasEffects(context) {
  10534. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  10535. return true;
  10536. context.brokenFlow = true;
  10537. return false;
  10538. }
  10539. include(context, includeChildrenRecursively) {
  10540. this.included = true;
  10541. this.argument?.include(context, includeChildrenRecursively);
  10542. context.brokenFlow = true;
  10543. }
  10544. initialise() {
  10545. super.initialise();
  10546. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  10547. }
  10548. render(code, options) {
  10549. if (this.argument) {
  10550. this.argument.render(code, options, { preventASI: true });
  10551. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  10552. code.prependLeft(this.start + 6, ' ');
  10553. }
  10554. }
  10555. }
  10556. }
  10557. class SequenceExpression extends NodeBase {
  10558. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10559. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10560. }
  10561. deoptimizePath(path) {
  10562. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  10563. }
  10564. getLiteralValueAtPath(path, recursionTracker, origin) {
  10565. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  10566. }
  10567. hasEffects(context) {
  10568. for (const expression of this.expressions) {
  10569. if (expression.hasEffects(context))
  10570. return true;
  10571. }
  10572. return false;
  10573. }
  10574. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10575. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  10576. }
  10577. include(context, includeChildrenRecursively) {
  10578. this.included = true;
  10579. const lastExpression = this.expressions[this.expressions.length - 1];
  10580. for (const expression of this.expressions) {
  10581. if (includeChildrenRecursively ||
  10582. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  10583. expression.shouldBeIncluded(context))
  10584. expression.include(context, includeChildrenRecursively);
  10585. }
  10586. }
  10587. removeAnnotations(code) {
  10588. this.expressions[0].removeAnnotations(code);
  10589. }
  10590. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  10591. let includedNodes = 0;
  10592. let lastSeparatorPos = null;
  10593. const lastNode = this.expressions[this.expressions.length - 1];
  10594. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  10595. if (!node.included) {
  10596. treeshakeNode(node, code, start, end);
  10597. continue;
  10598. }
  10599. includedNodes++;
  10600. lastSeparatorPos = separator;
  10601. if (includedNodes === 1 && preventASI) {
  10602. removeLineBreaks(code, start, node.start);
  10603. }
  10604. if (includedNodes === 1) {
  10605. const parentType = renderedParentType || this.parent.type;
  10606. node.render(code, options, {
  10607. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  10608. renderedParentType: parentType,
  10609. renderedSurroundingElement: parentType
  10610. });
  10611. }
  10612. else {
  10613. node.render(code, options);
  10614. }
  10615. }
  10616. if (lastSeparatorPos) {
  10617. code.remove(lastSeparatorPos, this.end);
  10618. }
  10619. }
  10620. }
  10621. class StaticBlock extends NodeBase {
  10622. createScope(parentScope) {
  10623. this.scope = new BlockScope(parentScope);
  10624. }
  10625. hasEffects(context) {
  10626. for (const node of this.body) {
  10627. if (node.hasEffects(context))
  10628. return true;
  10629. }
  10630. return false;
  10631. }
  10632. include(context, includeChildrenRecursively) {
  10633. this.included = true;
  10634. for (const node of this.body) {
  10635. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10636. node.include(context, includeChildrenRecursively);
  10637. }
  10638. }
  10639. render(code, options) {
  10640. if (this.body.length > 0) {
  10641. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  10642. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  10643. }
  10644. else {
  10645. super.render(code, options);
  10646. }
  10647. }
  10648. }
  10649. class Super extends NodeBase {
  10650. bind() {
  10651. this.variable = this.scope.findVariable('this');
  10652. }
  10653. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10654. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10655. }
  10656. deoptimizePath(path) {
  10657. this.variable.deoptimizePath(path);
  10658. }
  10659. include() {
  10660. if (!this.included) {
  10661. this.included = true;
  10662. this.scope.context.includeVariableInModule(this.variable);
  10663. }
  10664. }
  10665. }
  10666. class SwitchCase extends NodeBase {
  10667. hasEffects(context) {
  10668. if (this.test?.hasEffects(context))
  10669. return true;
  10670. for (const node of this.consequent) {
  10671. if (context.brokenFlow)
  10672. break;
  10673. if (node.hasEffects(context))
  10674. return true;
  10675. }
  10676. return false;
  10677. }
  10678. include(context, includeChildrenRecursively) {
  10679. this.included = true;
  10680. this.test?.include(context, includeChildrenRecursively);
  10681. for (const node of this.consequent) {
  10682. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10683. node.include(context, includeChildrenRecursively);
  10684. }
  10685. }
  10686. render(code, options, nodeRenderOptions) {
  10687. if (this.consequent.length > 0) {
  10688. this.test && this.test.render(code, options);
  10689. const testEnd = this.test
  10690. ? this.test.end
  10691. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  10692. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  10693. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  10694. }
  10695. else {
  10696. super.render(code, options);
  10697. }
  10698. }
  10699. }
  10700. SwitchCase.prototype.needsBoundaries = true;
  10701. class SwitchStatement extends NodeBase {
  10702. createScope(parentScope) {
  10703. this.parentScope = parentScope;
  10704. this.scope = new BlockScope(parentScope);
  10705. }
  10706. hasEffects(context) {
  10707. if (this.discriminant.hasEffects(context))
  10708. return true;
  10709. const { brokenFlow, hasBreak, ignore } = context;
  10710. const { breaks } = ignore;
  10711. ignore.breaks = true;
  10712. context.hasBreak = false;
  10713. let onlyHasBrokenFlow = true;
  10714. for (const switchCase of this.cases) {
  10715. if (switchCase.hasEffects(context))
  10716. return true;
  10717. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  10718. context.hasBreak = false;
  10719. context.brokenFlow = brokenFlow;
  10720. }
  10721. if (this.defaultCase !== null) {
  10722. context.brokenFlow = onlyHasBrokenFlow;
  10723. }
  10724. ignore.breaks = breaks;
  10725. context.hasBreak = hasBreak;
  10726. return false;
  10727. }
  10728. include(context, includeChildrenRecursively) {
  10729. this.included = true;
  10730. this.discriminant.include(context, includeChildrenRecursively);
  10731. const { brokenFlow, hasBreak } = context;
  10732. context.hasBreak = false;
  10733. let onlyHasBrokenFlow = true;
  10734. let isCaseIncluded = includeChildrenRecursively ||
  10735. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  10736. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  10737. const switchCase = this.cases[caseIndex];
  10738. if (switchCase.included) {
  10739. isCaseIncluded = true;
  10740. }
  10741. if (!isCaseIncluded) {
  10742. const hasEffectsContext = createHasEffectsContext();
  10743. hasEffectsContext.ignore.breaks = true;
  10744. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  10745. }
  10746. if (isCaseIncluded) {
  10747. switchCase.include(context, includeChildrenRecursively);
  10748. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  10749. context.hasBreak = false;
  10750. context.brokenFlow = brokenFlow;
  10751. }
  10752. else {
  10753. onlyHasBrokenFlow = brokenFlow;
  10754. }
  10755. }
  10756. if (isCaseIncluded && this.defaultCase !== null) {
  10757. context.brokenFlow = onlyHasBrokenFlow;
  10758. }
  10759. context.hasBreak = hasBreak;
  10760. }
  10761. initialise() {
  10762. super.initialise();
  10763. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  10764. if (this.cases[caseIndex].test === null) {
  10765. this.defaultCase = caseIndex;
  10766. return;
  10767. }
  10768. }
  10769. this.defaultCase = null;
  10770. }
  10771. parseNode(esTreeNode) {
  10772. this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
  10773. return super.parseNode(esTreeNode);
  10774. }
  10775. render(code, options) {
  10776. this.discriminant.render(code, options);
  10777. if (this.cases.length > 0) {
  10778. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  10779. }
  10780. }
  10781. }
  10782. class TaggedTemplateExpression extends CallExpressionBase {
  10783. bind() {
  10784. super.bind();
  10785. if (this.tag.type === Identifier$1) {
  10786. const name = this.tag.name;
  10787. const variable = this.scope.findVariable(name);
  10788. if (variable.isNamespace) {
  10789. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(name), this.start);
  10790. }
  10791. }
  10792. }
  10793. hasEffects(context) {
  10794. try {
  10795. for (const argument of this.quasi.expressions) {
  10796. if (argument.hasEffects(context))
  10797. return true;
  10798. }
  10799. return (this.tag.hasEffects(context) ||
  10800. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10801. }
  10802. finally {
  10803. if (!this.deoptimized)
  10804. this.applyDeoptimizations();
  10805. }
  10806. }
  10807. include(context, includeChildrenRecursively) {
  10808. if (!this.deoptimized)
  10809. this.applyDeoptimizations();
  10810. if (includeChildrenRecursively) {
  10811. super.include(context, includeChildrenRecursively);
  10812. }
  10813. else {
  10814. this.included = true;
  10815. this.tag.include(context, includeChildrenRecursively);
  10816. this.quasi.include(context, includeChildrenRecursively);
  10817. }
  10818. this.tag.includeCallArguments(context, this.args);
  10819. const [returnExpression] = this.getReturnExpression();
  10820. if (!returnExpression.included) {
  10821. returnExpression.include(context, false);
  10822. }
  10823. }
  10824. initialise() {
  10825. super.initialise();
  10826. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  10827. this.interaction = {
  10828. args: [
  10829. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  10830. ...this.args
  10831. ],
  10832. type: INTERACTION_CALLED,
  10833. withNew: false
  10834. };
  10835. }
  10836. render(code, options) {
  10837. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  10838. this.quasi.render(code, options);
  10839. }
  10840. applyDeoptimizations() {
  10841. this.deoptimized = true;
  10842. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  10843. this.scope.context.requestTreeshakingPass();
  10844. }
  10845. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  10846. if (this.returnExpression === null) {
  10847. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  10848. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  10849. }
  10850. return this.returnExpression;
  10851. }
  10852. }
  10853. class TemplateElement extends NodeBase {
  10854. get tail() {
  10855. return isFlagSet(this.flags, 1048576 /* Flag.tail */);
  10856. }
  10857. set tail(value) {
  10858. this.flags = setFlag(this.flags, 1048576 /* Flag.tail */, value);
  10859. }
  10860. // Do not try to bind value
  10861. bind() { }
  10862. hasEffects() {
  10863. return false;
  10864. }
  10865. include() {
  10866. this.included = true;
  10867. }
  10868. parseNode(esTreeNode) {
  10869. this.value = esTreeNode.value;
  10870. return super.parseNode(esTreeNode);
  10871. }
  10872. render() { }
  10873. }
  10874. class TemplateLiteral extends NodeBase {
  10875. deoptimizeArgumentsOnInteractionAtPath() { }
  10876. getLiteralValueAtPath(path) {
  10877. if (path.length > 0 || this.quasis.length !== 1) {
  10878. return UnknownValue;
  10879. }
  10880. return this.quasis[0].value.cooked;
  10881. }
  10882. getReturnExpressionWhenCalledAtPath(path) {
  10883. if (path.length !== 1) {
  10884. return UNKNOWN_RETURN_EXPRESSION;
  10885. }
  10886. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  10887. }
  10888. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10889. if (interaction.type === INTERACTION_ACCESSED) {
  10890. return path.length > 1;
  10891. }
  10892. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  10893. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  10894. }
  10895. return true;
  10896. }
  10897. render(code, options) {
  10898. code.indentExclusionRanges.push([this.start, this.end]);
  10899. super.render(code, options);
  10900. }
  10901. }
  10902. class UndefinedVariable extends Variable {
  10903. constructor() {
  10904. super('undefined');
  10905. }
  10906. getLiteralValueAtPath() {
  10907. return undefined;
  10908. }
  10909. }
  10910. class ExportDefaultVariable extends LocalVariable {
  10911. constructor(name, exportDefaultDeclaration, context) {
  10912. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context, 'other');
  10913. this.hasId = false;
  10914. this.originalId = null;
  10915. this.originalVariable = null;
  10916. const declaration = exportDefaultDeclaration.declaration;
  10917. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  10918. declaration.id) {
  10919. this.hasId = true;
  10920. this.originalId = declaration.id;
  10921. }
  10922. else if (declaration instanceof Identifier) {
  10923. this.originalId = declaration;
  10924. }
  10925. }
  10926. addReference(identifier) {
  10927. if (!this.hasId) {
  10928. this.name = identifier.name;
  10929. }
  10930. }
  10931. forbidName(name) {
  10932. const original = this.getOriginalVariable();
  10933. if (original === this) {
  10934. super.forbidName(name);
  10935. }
  10936. else {
  10937. original.forbidName(name);
  10938. }
  10939. }
  10940. getAssignedVariableName() {
  10941. return (this.originalId && this.originalId.name) || null;
  10942. }
  10943. getBaseVariableName() {
  10944. const original = this.getOriginalVariable();
  10945. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  10946. }
  10947. getDirectOriginalVariable() {
  10948. return this.originalId &&
  10949. (this.hasId ||
  10950. !(this.originalId.isPossibleTDZ() ||
  10951. this.originalId.variable.isReassigned ||
  10952. this.originalId.variable instanceof UndefinedVariable ||
  10953. // this avoids a circular dependency
  10954. 'syntheticNamespace' in this.originalId.variable))
  10955. ? this.originalId.variable
  10956. : null;
  10957. }
  10958. getName(getPropertyAccess) {
  10959. const original = this.getOriginalVariable();
  10960. return original === this
  10961. ? super.getName(getPropertyAccess)
  10962. : original.getName(getPropertyAccess);
  10963. }
  10964. getOriginalVariable() {
  10965. if (this.originalVariable)
  10966. return this.originalVariable;
  10967. // eslint-disable-next-line @typescript-eslint/no-this-alias
  10968. let original = this;
  10969. let currentVariable;
  10970. const checkedVariables = new Set();
  10971. do {
  10972. checkedVariables.add(original);
  10973. currentVariable = original;
  10974. original = currentVariable.getDirectOriginalVariable();
  10975. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  10976. return (this.originalVariable = original || currentVariable);
  10977. }
  10978. }
  10979. class ModuleScope extends ChildScope {
  10980. constructor(parent, context) {
  10981. super(parent, context);
  10982. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context, 'other'));
  10983. }
  10984. addDeclaration(identifier, context, init, kind) {
  10985. if (this.context.module.importDescriptions.has(identifier.name)) {
  10986. context.error(logRedeclarationError(identifier.name), identifier.start);
  10987. }
  10988. return super.addDeclaration(identifier, context, init, kind);
  10989. }
  10990. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  10991. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  10992. this.variables.set('default', variable);
  10993. return variable;
  10994. }
  10995. addNamespaceMemberAccess() { }
  10996. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  10997. // all module level variables are already deconflicted when deconflicting the chunk
  10998. for (const scope of this.children)
  10999. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  11000. }
  11001. findLexicalBoundary() {
  11002. return this;
  11003. }
  11004. findVariable(name) {
  11005. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  11006. if (knownVariable) {
  11007. return knownVariable;
  11008. }
  11009. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  11010. if (variable instanceof GlobalVariable) {
  11011. this.accessedOutsideVariables.set(name, variable);
  11012. }
  11013. return variable;
  11014. }
  11015. }
  11016. class ThisExpression extends NodeBase {
  11017. bind() {
  11018. this.variable = this.scope.findVariable('this');
  11019. }
  11020. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11021. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11022. }
  11023. deoptimizePath(path) {
  11024. this.variable.deoptimizePath(path);
  11025. }
  11026. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11027. if (path.length === 0) {
  11028. return interaction.type !== INTERACTION_ACCESSED;
  11029. }
  11030. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  11031. }
  11032. include() {
  11033. if (!this.included) {
  11034. this.included = true;
  11035. this.scope.context.includeVariableInModule(this.variable);
  11036. }
  11037. }
  11038. initialise() {
  11039. super.initialise();
  11040. this.alias =
  11041. this.scope.findLexicalBoundary() instanceof ModuleScope
  11042. ? this.scope.context.moduleContext
  11043. : null;
  11044. if (this.alias === 'undefined') {
  11045. this.scope.context.log(LOGLEVEL_WARN, logThisIsUndefined(), this.start);
  11046. }
  11047. }
  11048. render(code) {
  11049. if (this.alias !== null) {
  11050. code.overwrite(this.start, this.end, this.alias, {
  11051. contentOnly: false,
  11052. storeName: true
  11053. });
  11054. }
  11055. }
  11056. }
  11057. class ThrowStatement extends NodeBase {
  11058. hasEffects() {
  11059. return true;
  11060. }
  11061. include(context, includeChildrenRecursively) {
  11062. this.included = true;
  11063. this.argument.include(context, includeChildrenRecursively);
  11064. context.brokenFlow = true;
  11065. }
  11066. render(code, options) {
  11067. this.argument.render(code, options, { preventASI: true });
  11068. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  11069. code.prependLeft(this.start + 5, ' ');
  11070. }
  11071. }
  11072. }
  11073. class TryStatement extends NodeBase {
  11074. constructor() {
  11075. super(...arguments);
  11076. this.directlyIncluded = false;
  11077. this.includedLabelsAfterBlock = null;
  11078. }
  11079. hasEffects(context) {
  11080. return ((this.scope.context.options.treeshake.tryCatchDeoptimization
  11081. ? this.block.body.length > 0
  11082. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  11083. }
  11084. include(context, includeChildrenRecursively) {
  11085. const tryCatchDeoptimization = this.scope.context.options.treeshake?.tryCatchDeoptimization;
  11086. const { brokenFlow, includedLabels } = context;
  11087. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  11088. this.included = true;
  11089. this.directlyIncluded = true;
  11090. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  11091. if (includedLabels.size > 0) {
  11092. this.includedLabelsAfterBlock = [...includedLabels];
  11093. }
  11094. context.brokenFlow = brokenFlow;
  11095. }
  11096. else if (this.includedLabelsAfterBlock) {
  11097. for (const label of this.includedLabelsAfterBlock) {
  11098. includedLabels.add(label);
  11099. }
  11100. }
  11101. if (this.handler !== null) {
  11102. this.handler.include(context, includeChildrenRecursively);
  11103. context.brokenFlow = brokenFlow;
  11104. }
  11105. this.finalizer?.include(context, includeChildrenRecursively);
  11106. }
  11107. }
  11108. const unaryOperators = {
  11109. '!': value => !value,
  11110. '+': value => +value,
  11111. '-': value => -value,
  11112. delete: () => UnknownValue,
  11113. typeof: value => typeof value,
  11114. void: () => undefined,
  11115. '~': value => ~value
  11116. };
  11117. class UnaryExpression extends NodeBase {
  11118. get prefix() {
  11119. return isFlagSet(this.flags, 2097152 /* Flag.prefix */);
  11120. }
  11121. set prefix(value) {
  11122. this.flags = setFlag(this.flags, 2097152 /* Flag.prefix */, value);
  11123. }
  11124. getLiteralValueAtPath(path, recursionTracker, origin) {
  11125. if (path.length > 0)
  11126. return UnknownValue;
  11127. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  11128. if (typeof argumentValue === 'symbol')
  11129. return UnknownValue;
  11130. return unaryOperators[this.operator](argumentValue);
  11131. }
  11132. hasEffects(context) {
  11133. if (!this.deoptimized)
  11134. this.applyDeoptimizations();
  11135. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  11136. return false;
  11137. return (this.argument.hasEffects(context) ||
  11138. (this.operator === 'delete' &&
  11139. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  11140. }
  11141. hasEffectsOnInteractionAtPath(path, { type }) {
  11142. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  11143. }
  11144. applyDeoptimizations() {
  11145. this.deoptimized = true;
  11146. if (this.operator === 'delete') {
  11147. this.argument.deoptimizePath(EMPTY_PATH);
  11148. this.scope.context.requestTreeshakingPass();
  11149. }
  11150. }
  11151. }
  11152. class UpdateExpression extends NodeBase {
  11153. hasEffects(context) {
  11154. if (!this.deoptimized)
  11155. this.applyDeoptimizations();
  11156. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  11157. }
  11158. hasEffectsOnInteractionAtPath(path, { type }) {
  11159. return path.length > 1 || type !== INTERACTION_ACCESSED;
  11160. }
  11161. include(context, includeChildrenRecursively) {
  11162. if (!this.deoptimized)
  11163. this.applyDeoptimizations();
  11164. this.included = true;
  11165. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  11166. }
  11167. initialise() {
  11168. super.initialise();
  11169. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  11170. }
  11171. render(code, options) {
  11172. const { exportNamesByVariable, format, snippets: { _ } } = options;
  11173. this.argument.render(code, options);
  11174. if (format === 'system') {
  11175. const variable = this.argument.variable;
  11176. const exportNames = exportNamesByVariable.get(variable);
  11177. if (exportNames) {
  11178. if (this.prefix) {
  11179. if (exportNames.length === 1) {
  11180. renderSystemExportExpression(variable, this.start, this.end, code, options);
  11181. }
  11182. else {
  11183. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  11184. }
  11185. }
  11186. else {
  11187. const operator = this.operator[0];
  11188. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  11189. }
  11190. }
  11191. }
  11192. }
  11193. applyDeoptimizations() {
  11194. this.deoptimized = true;
  11195. this.argument.deoptimizePath(EMPTY_PATH);
  11196. if (this.argument instanceof Identifier) {
  11197. const variable = this.scope.findVariable(this.argument.name);
  11198. variable.isReassigned = true;
  11199. }
  11200. this.scope.context.requestTreeshakingPass();
  11201. }
  11202. }
  11203. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  11204. for (const declarator of declarations) {
  11205. if (!declarator.id.included)
  11206. return false;
  11207. if (declarator.id.type === Identifier$1) {
  11208. if (exportNamesByVariable.has(declarator.id.variable))
  11209. return false;
  11210. }
  11211. else {
  11212. const exportedVariables = [];
  11213. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  11214. if (exportedVariables.length > 0)
  11215. return false;
  11216. }
  11217. }
  11218. return true;
  11219. }
  11220. class VariableDeclaration extends NodeBase {
  11221. deoptimizePath() {
  11222. for (const declarator of this.declarations) {
  11223. declarator.deoptimizePath(EMPTY_PATH);
  11224. }
  11225. }
  11226. hasEffectsOnInteractionAtPath() {
  11227. return false;
  11228. }
  11229. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  11230. this.included = true;
  11231. for (const declarator of this.declarations) {
  11232. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  11233. declarator.include(context, includeChildrenRecursively);
  11234. const { id, init } = declarator;
  11235. if (asSingleStatement) {
  11236. id.include(context, includeChildrenRecursively);
  11237. }
  11238. if (init &&
  11239. id.included &&
  11240. !init.included &&
  11241. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  11242. init.include(context, includeChildrenRecursively);
  11243. }
  11244. }
  11245. }
  11246. initialise() {
  11247. super.initialise();
  11248. this.isUsingDeclaration = this.kind === 'await using' || this.kind === 'using';
  11249. for (const declarator of this.declarations) {
  11250. declarator.declareDeclarator(this.kind, this.isUsingDeclaration);
  11251. }
  11252. }
  11253. removeAnnotations(code) {
  11254. this.declarations[0].removeAnnotations(code);
  11255. }
  11256. render(code, options, nodeRenderOptions = BLANK) {
  11257. if (this.isUsingDeclaration ||
  11258. areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  11259. for (const declarator of this.declarations) {
  11260. declarator.render(code, options);
  11261. }
  11262. if (!nodeRenderOptions.isNoStatement &&
  11263. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  11264. code.appendLeft(this.end, ';');
  11265. }
  11266. }
  11267. else {
  11268. this.renderReplacedDeclarations(code, options);
  11269. }
  11270. }
  11271. applyDeoptimizations() { }
  11272. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  11273. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  11274. code.remove(this.end - 1, this.end);
  11275. }
  11276. separatorString += ';';
  11277. if (lastSeparatorPos === null) {
  11278. code.appendLeft(renderedContentEnd, separatorString);
  11279. }
  11280. else {
  11281. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  11282. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  11283. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  11284. actualContentEnd--;
  11285. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  11286. actualContentEnd--;
  11287. }
  11288. }
  11289. if (actualContentEnd === lastSeparatorPos + 1) {
  11290. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  11291. }
  11292. else {
  11293. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  11294. code.remove(actualContentEnd, renderedContentEnd);
  11295. }
  11296. }
  11297. if (systemPatternExports.length > 0) {
  11298. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  11299. }
  11300. }
  11301. renderReplacedDeclarations(code, options) {
  11302. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  11303. let actualContentEnd, renderedContentEnd;
  11304. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  11305. let lastSeparatorPos = renderedContentEnd - 1;
  11306. code.remove(this.start, lastSeparatorPos);
  11307. let isInDeclaration = false;
  11308. let hasRenderedContent = false;
  11309. let separatorString = '', leadingString, nextSeparatorString;
  11310. const aggregatedSystemExports = [];
  11311. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  11312. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  11313. if (!node.included) {
  11314. code.remove(start, end);
  11315. node.removeAnnotations(code);
  11316. continue;
  11317. }
  11318. node.render(code, options);
  11319. leadingString = '';
  11320. nextSeparatorString = '';
  11321. if (!node.id.included ||
  11322. (node.id instanceof Identifier &&
  11323. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  11324. if (hasRenderedContent) {
  11325. separatorString += ';';
  11326. }
  11327. isInDeclaration = false;
  11328. }
  11329. else {
  11330. if (singleSystemExport && singleSystemExport === node.id.variable) {
  11331. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  11332. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  11333. }
  11334. if (isInDeclaration) {
  11335. separatorString += ',';
  11336. }
  11337. else {
  11338. if (hasRenderedContent) {
  11339. separatorString += ';';
  11340. }
  11341. leadingString += `${this.kind} `;
  11342. isInDeclaration = true;
  11343. }
  11344. }
  11345. if (renderedContentEnd === lastSeparatorPos + 1) {
  11346. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  11347. }
  11348. else {
  11349. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  11350. code.appendLeft(renderedContentEnd, leadingString);
  11351. }
  11352. actualContentEnd = contentEnd;
  11353. renderedContentEnd = end;
  11354. hasRenderedContent = true;
  11355. lastSeparatorPos = separator;
  11356. separatorString = nextSeparatorString;
  11357. }
  11358. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  11359. }
  11360. }
  11361. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  11362. let singleSystemExport = null;
  11363. if (options.format === 'system') {
  11364. for (const { node } of separatedNodes) {
  11365. if (node.id instanceof Identifier &&
  11366. node.init &&
  11367. aggregatedSystemExports.length === 0 &&
  11368. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  11369. singleSystemExport = node.id.variable;
  11370. aggregatedSystemExports.push(singleSystemExport);
  11371. }
  11372. else {
  11373. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  11374. }
  11375. }
  11376. if (aggregatedSystemExports.length > 1) {
  11377. singleSystemExport = null;
  11378. }
  11379. else if (singleSystemExport) {
  11380. aggregatedSystemExports.length = 0;
  11381. }
  11382. }
  11383. return singleSystemExport;
  11384. }
  11385. class WhileStatement extends NodeBase {
  11386. hasEffects(context) {
  11387. if (this.test.hasEffects(context))
  11388. return true;
  11389. return hasLoopBodyEffects(context, this.body);
  11390. }
  11391. include(context, includeChildrenRecursively) {
  11392. this.included = true;
  11393. this.test.include(context, includeChildrenRecursively);
  11394. includeLoopBody(context, this.body, includeChildrenRecursively);
  11395. }
  11396. }
  11397. class YieldExpression extends NodeBase {
  11398. hasEffects(context) {
  11399. if (!this.deoptimized)
  11400. this.applyDeoptimizations();
  11401. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  11402. }
  11403. render(code, options) {
  11404. if (this.argument) {
  11405. this.argument.render(code, options, { preventASI: true });
  11406. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  11407. code.prependLeft(this.start + 5, ' ');
  11408. }
  11409. }
  11410. }
  11411. }
  11412. // This file is generated by scripts/generate-buffer-parsers.js.
  11413. // Do not edit this file directly.
  11414. function convertProgram(buffer, parent, parentScope) {
  11415. return convertNode(parent, parentScope, 0, new Uint32Array(buffer.buffer), getReadStringFunction(buffer));
  11416. }
  11417. const nodeTypeStrings = [
  11418. 'PanicError',
  11419. 'ParseError',
  11420. 'ArrayExpression',
  11421. 'ArrayPattern',
  11422. 'ArrowFunctionExpression',
  11423. 'AssignmentExpression',
  11424. 'AssignmentPattern',
  11425. 'AwaitExpression',
  11426. 'BinaryExpression',
  11427. 'BlockStatement',
  11428. 'BreakStatement',
  11429. 'CallExpression',
  11430. 'CatchClause',
  11431. 'ChainExpression',
  11432. 'ClassBody',
  11433. 'ClassDeclaration',
  11434. 'ClassExpression',
  11435. 'ConditionalExpression',
  11436. 'ContinueStatement',
  11437. 'DebuggerStatement',
  11438. 'ExpressionStatement',
  11439. 'DoWhileStatement',
  11440. 'EmptyStatement',
  11441. 'ExportAllDeclaration',
  11442. 'ExportDefaultDeclaration',
  11443. 'ExportNamedDeclaration',
  11444. 'ExportSpecifier',
  11445. 'ExpressionStatement',
  11446. 'ForInStatement',
  11447. 'ForOfStatement',
  11448. 'ForStatement',
  11449. 'FunctionDeclaration',
  11450. 'FunctionExpression',
  11451. 'Identifier',
  11452. 'IfStatement',
  11453. 'ImportAttribute',
  11454. 'ImportDeclaration',
  11455. 'ImportDefaultSpecifier',
  11456. 'ImportExpression',
  11457. 'ImportNamespaceSpecifier',
  11458. 'ImportSpecifier',
  11459. 'LabeledStatement',
  11460. 'Literal',
  11461. 'Literal',
  11462. 'Literal',
  11463. 'Literal',
  11464. 'Literal',
  11465. 'Literal',
  11466. 'LogicalExpression',
  11467. 'MemberExpression',
  11468. 'MetaProperty',
  11469. 'MethodDefinition',
  11470. 'NewExpression',
  11471. 'ObjectExpression',
  11472. 'ObjectPattern',
  11473. 'PrivateIdentifier',
  11474. 'Program',
  11475. 'Property',
  11476. 'PropertyDefinition',
  11477. 'RestElement',
  11478. 'ReturnStatement',
  11479. 'SequenceExpression',
  11480. 'SpreadElement',
  11481. 'StaticBlock',
  11482. 'Super',
  11483. 'SwitchCase',
  11484. 'SwitchStatement',
  11485. 'TaggedTemplateExpression',
  11486. 'TemplateElement',
  11487. 'TemplateLiteral',
  11488. 'ThisExpression',
  11489. 'ThrowStatement',
  11490. 'TryStatement',
  11491. 'UnaryExpression',
  11492. 'UpdateExpression',
  11493. 'VariableDeclaration',
  11494. 'VariableDeclarator',
  11495. 'WhileStatement',
  11496. 'YieldExpression'
  11497. ];
  11498. const nodeConstructors$1 = [
  11499. PanicError,
  11500. ParseError,
  11501. ArrayExpression,
  11502. ArrayPattern,
  11503. ArrowFunctionExpression,
  11504. AssignmentExpression,
  11505. AssignmentPattern,
  11506. AwaitExpression,
  11507. BinaryExpression,
  11508. BlockStatement,
  11509. BreakStatement,
  11510. CallExpression,
  11511. CatchClause,
  11512. ChainExpression,
  11513. ClassBody,
  11514. ClassDeclaration,
  11515. ClassExpression,
  11516. ConditionalExpression,
  11517. ContinueStatement,
  11518. DebuggerStatement,
  11519. ExpressionStatement,
  11520. DoWhileStatement,
  11521. EmptyStatement,
  11522. ExportAllDeclaration,
  11523. ExportDefaultDeclaration,
  11524. ExportNamedDeclaration,
  11525. ExportSpecifier,
  11526. ExpressionStatement,
  11527. ForInStatement,
  11528. ForOfStatement,
  11529. ForStatement,
  11530. FunctionDeclaration,
  11531. FunctionExpression,
  11532. Identifier,
  11533. IfStatement,
  11534. ImportAttribute,
  11535. ImportDeclaration,
  11536. ImportDefaultSpecifier,
  11537. ImportExpression,
  11538. ImportNamespaceSpecifier,
  11539. ImportSpecifier,
  11540. LabeledStatement,
  11541. Literal,
  11542. Literal,
  11543. Literal,
  11544. Literal,
  11545. Literal,
  11546. Literal,
  11547. LogicalExpression,
  11548. MemberExpression,
  11549. MetaProperty,
  11550. MethodDefinition,
  11551. NewExpression,
  11552. ObjectExpression,
  11553. ObjectPattern,
  11554. PrivateIdentifier,
  11555. Program,
  11556. Property,
  11557. PropertyDefinition,
  11558. RestElement,
  11559. ReturnStatement,
  11560. SequenceExpression,
  11561. SpreadElement,
  11562. StaticBlock,
  11563. Super,
  11564. SwitchCase,
  11565. SwitchStatement,
  11566. TaggedTemplateExpression,
  11567. TemplateElement,
  11568. TemplateLiteral,
  11569. ThisExpression,
  11570. ThrowStatement,
  11571. TryStatement,
  11572. UnaryExpression,
  11573. UpdateExpression,
  11574. VariableDeclaration,
  11575. VariableDeclarator,
  11576. WhileStatement,
  11577. YieldExpression
  11578. ];
  11579. const bufferParsers = [
  11580. function panicError(node, position, buffer, readString) {
  11581. node.message = convertString(buffer[position], buffer, readString);
  11582. },
  11583. function parseError(node, position, buffer, readString) {
  11584. node.message = convertString(buffer[position], buffer, readString);
  11585. },
  11586. function arrayExpression(node, position, buffer, readString) {
  11587. const { scope } = node;
  11588. node.elements = convertNodeList(node, scope, buffer[position], buffer, readString);
  11589. },
  11590. function arrayPattern(node, position, buffer, readString) {
  11591. const { scope } = node;
  11592. node.elements = convertNodeList(node, scope, buffer[position], buffer, readString);
  11593. },
  11594. function arrowFunctionExpression(node, position, buffer, readString) {
  11595. const { scope } = node;
  11596. const flags = buffer[position];
  11597. node.async = (flags & 1) === 1;
  11598. node.expression = (flags & 2) === 2;
  11599. node.generator = (flags & 4) === 4;
  11600. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  11601. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  11602. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 2], buffer, readString));
  11603. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  11604. node.body = convertNode(node, scope.bodyScope, buffer[position + 3], buffer, readString);
  11605. },
  11606. function assignmentExpression(node, position, buffer, readString) {
  11607. const { scope } = node;
  11608. node.operator = FIXED_STRINGS[buffer[position]];
  11609. node.left = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11610. node.right = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11611. },
  11612. function assignmentPattern(node, position, buffer, readString) {
  11613. const { scope } = node;
  11614. node.left = convertNode(node, scope, buffer[position], buffer, readString);
  11615. node.right = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11616. },
  11617. function awaitExpression(node, position, buffer, readString) {
  11618. const { scope } = node;
  11619. node.argument = convertNode(node, scope, buffer[position], buffer, readString);
  11620. },
  11621. function binaryExpression(node, position, buffer, readString) {
  11622. const { scope } = node;
  11623. node.operator = FIXED_STRINGS[buffer[position]];
  11624. node.left = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11625. node.right = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11626. },
  11627. function blockStatement(node, position, buffer, readString) {
  11628. const { scope } = node;
  11629. node.body = convertNodeList(node, scope, buffer[position], buffer, readString);
  11630. },
  11631. function breakStatement(node, position, buffer, readString) {
  11632. const { scope } = node;
  11633. const labelPosition = buffer[position];
  11634. node.label =
  11635. labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer, readString);
  11636. },
  11637. function callExpression(node, position, buffer, readString) {
  11638. const { scope } = node;
  11639. const flags = buffer[position];
  11640. node.optional = (flags & 1) === 1;
  11641. node.annotations = convertAnnotations(buffer[position + 1], buffer);
  11642. node.callee = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11643. node.arguments = convertNodeList(node, scope, buffer[position + 3], buffer, readString);
  11644. },
  11645. function catchClause(node, position, buffer, readString) {
  11646. const { scope } = node;
  11647. const parameterPosition = buffer[position];
  11648. const parameter = (node.param =
  11649. parameterPosition === 0
  11650. ? null
  11651. : convertNode(node, scope, parameterPosition, buffer, readString));
  11652. parameter?.declare('parameter', UNKNOWN_EXPRESSION);
  11653. node.body = convertNode(node, scope.bodyScope, buffer[position + 1], buffer, readString);
  11654. },
  11655. function chainExpression(node, position, buffer, readString) {
  11656. const { scope } = node;
  11657. node.expression = convertNode(node, scope, buffer[position], buffer, readString);
  11658. },
  11659. function classBody(node, position, buffer, readString) {
  11660. const { scope } = node;
  11661. const bodyPosition = buffer[position];
  11662. const body = (node.body = []);
  11663. if (bodyPosition) {
  11664. const length = buffer[bodyPosition];
  11665. for (let index = 0; index < length; index++) {
  11666. const nodePosition = buffer[bodyPosition + 1 + index];
  11667. body.push(convertNode(node, (buffer[nodePosition + 3] & 1) === 0 ? scope.instanceScope : scope, nodePosition, buffer, readString));
  11668. }
  11669. }
  11670. },
  11671. function classDeclaration(node, position, buffer, readString) {
  11672. const { scope } = node;
  11673. const idPosition = buffer[position];
  11674. node.id =
  11675. idPosition === 0
  11676. ? null
  11677. : convertNode(node, scope.parent, idPosition, buffer, readString);
  11678. const superClassPosition = buffer[position + 1];
  11679. node.superClass =
  11680. superClassPosition === 0
  11681. ? null
  11682. : convertNode(node, scope, superClassPosition, buffer, readString);
  11683. node.body = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11684. },
  11685. function classExpression(node, position, buffer, readString) {
  11686. const { scope } = node;
  11687. const idPosition = buffer[position];
  11688. node.id = idPosition === 0 ? null : convertNode(node, scope, idPosition, buffer, readString);
  11689. const superClassPosition = buffer[position + 1];
  11690. node.superClass =
  11691. superClassPosition === 0
  11692. ? null
  11693. : convertNode(node, scope, superClassPosition, buffer, readString);
  11694. node.body = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11695. },
  11696. function conditionalExpression(node, position, buffer, readString) {
  11697. const { scope } = node;
  11698. node.test = convertNode(node, scope, buffer[position], buffer, readString);
  11699. node.consequent = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11700. node.alternate = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11701. },
  11702. function continueStatement(node, position, buffer, readString) {
  11703. const { scope } = node;
  11704. const labelPosition = buffer[position];
  11705. node.label =
  11706. labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer, readString);
  11707. },
  11708. function debuggerStatement() { },
  11709. function directive(node, position, buffer, readString) {
  11710. const { scope } = node;
  11711. node.directive = convertString(buffer[position], buffer, readString);
  11712. node.expression = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11713. },
  11714. function doWhileStatement(node, position, buffer, readString) {
  11715. const { scope } = node;
  11716. node.body = convertNode(node, scope, buffer[position], buffer, readString);
  11717. node.test = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11718. },
  11719. function emptyStatement() { },
  11720. function exportAllDeclaration(node, position, buffer, readString) {
  11721. const { scope } = node;
  11722. const exportedPosition = buffer[position];
  11723. node.exported =
  11724. exportedPosition === 0
  11725. ? null
  11726. : convertNode(node, scope, exportedPosition, buffer, readString);
  11727. node.source = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11728. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer, readString);
  11729. },
  11730. function exportDefaultDeclaration(node, position, buffer, readString) {
  11731. const { scope } = node;
  11732. node.declaration = convertNode(node, scope, buffer[position], buffer, readString);
  11733. },
  11734. function exportNamedDeclaration(node, position, buffer, readString) {
  11735. const { scope } = node;
  11736. node.specifiers = convertNodeList(node, scope, buffer[position], buffer, readString);
  11737. const sourcePosition = buffer[position + 1];
  11738. node.source =
  11739. sourcePosition === 0 ? null : convertNode(node, scope, sourcePosition, buffer, readString);
  11740. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer, readString);
  11741. const declarationPosition = buffer[position + 3];
  11742. node.declaration =
  11743. declarationPosition === 0
  11744. ? null
  11745. : convertNode(node, scope, declarationPosition, buffer, readString);
  11746. },
  11747. function exportSpecifier(node, position, buffer, readString) {
  11748. const { scope } = node;
  11749. node.local = convertNode(node, scope, buffer[position], buffer, readString);
  11750. const exportedPosition = buffer[position + 1];
  11751. node.exported =
  11752. exportedPosition === 0
  11753. ? node.local
  11754. : convertNode(node, scope, exportedPosition, buffer, readString);
  11755. },
  11756. function expressionStatement(node, position, buffer, readString) {
  11757. const { scope } = node;
  11758. node.expression = convertNode(node, scope, buffer[position], buffer, readString);
  11759. },
  11760. function forInStatement(node, position, buffer, readString) {
  11761. const { scope } = node;
  11762. node.left = convertNode(node, scope, buffer[position], buffer, readString);
  11763. node.right = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11764. node.body = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11765. },
  11766. function forOfStatement(node, position, buffer, readString) {
  11767. const { scope } = node;
  11768. const flags = buffer[position];
  11769. node.await = (flags & 1) === 1;
  11770. node.left = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11771. node.right = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11772. node.body = convertNode(node, scope, buffer[position + 3], buffer, readString);
  11773. },
  11774. function forStatement(node, position, buffer, readString) {
  11775. const { scope } = node;
  11776. const initPosition = buffer[position];
  11777. node.init =
  11778. initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer, readString);
  11779. const testPosition = buffer[position + 1];
  11780. node.test =
  11781. testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer, readString);
  11782. const updatePosition = buffer[position + 2];
  11783. node.update =
  11784. updatePosition === 0 ? null : convertNode(node, scope, updatePosition, buffer, readString);
  11785. node.body = convertNode(node, scope, buffer[position + 3], buffer, readString);
  11786. },
  11787. function functionDeclaration(node, position, buffer, readString) {
  11788. const { scope } = node;
  11789. const flags = buffer[position];
  11790. node.async = (flags & 1) === 1;
  11791. node.generator = (flags & 2) === 2;
  11792. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  11793. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  11794. const idPosition = buffer[position + 2];
  11795. node.id =
  11796. idPosition === 0
  11797. ? null
  11798. : convertNode(node, scope.parent, idPosition, buffer, readString);
  11799. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer, readString));
  11800. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  11801. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer, readString);
  11802. },
  11803. function functionExpression(node, position, buffer, readString) {
  11804. const { scope } = node;
  11805. const flags = buffer[position];
  11806. node.async = (flags & 1) === 1;
  11807. node.generator = (flags & 2) === 2;
  11808. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  11809. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  11810. const idPosition = buffer[position + 2];
  11811. node.id =
  11812. idPosition === 0 ? null : convertNode(node, node.idScope, idPosition, buffer, readString);
  11813. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer, readString));
  11814. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  11815. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer, readString);
  11816. },
  11817. function identifier(node, position, buffer, readString) {
  11818. node.name = convertString(buffer[position], buffer, readString);
  11819. },
  11820. function ifStatement(node, position, buffer, readString) {
  11821. const { scope } = node;
  11822. node.test = convertNode(node, scope, buffer[position], buffer, readString);
  11823. node.consequent = convertNode(node, (node.consequentScope = new TrackingScope(scope)), buffer[position + 1], buffer, readString);
  11824. const alternatePosition = buffer[position + 2];
  11825. node.alternate =
  11826. alternatePosition === 0
  11827. ? null
  11828. : convertNode(node, (node.alternateScope = new TrackingScope(scope)), alternatePosition, buffer, readString);
  11829. },
  11830. function importAttribute(node, position, buffer, readString) {
  11831. const { scope } = node;
  11832. node.key = convertNode(node, scope, buffer[position], buffer, readString);
  11833. node.value = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11834. },
  11835. function importDeclaration(node, position, buffer, readString) {
  11836. const { scope } = node;
  11837. node.specifiers = convertNodeList(node, scope, buffer[position], buffer, readString);
  11838. node.source = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11839. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer, readString);
  11840. },
  11841. function importDefaultSpecifier(node, position, buffer, readString) {
  11842. const { scope } = node;
  11843. node.local = convertNode(node, scope, buffer[position], buffer, readString);
  11844. },
  11845. function importExpression(node, position, buffer, readString) {
  11846. const { scope } = node;
  11847. node.source = convertNode(node, scope, buffer[position], buffer, readString);
  11848. node.sourceAstNode = convertNode$1(buffer[position], buffer, readString);
  11849. const optionsPosition = buffer[position + 1];
  11850. node.options =
  11851. optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer, readString);
  11852. },
  11853. function importNamespaceSpecifier(node, position, buffer, readString) {
  11854. const { scope } = node;
  11855. node.local = convertNode(node, scope, buffer[position], buffer, readString);
  11856. },
  11857. function importSpecifier(node, position, buffer, readString) {
  11858. const { scope } = node;
  11859. const importedPosition = buffer[position];
  11860. node.local = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11861. node.imported =
  11862. importedPosition === 0
  11863. ? node.local
  11864. : convertNode(node, scope, importedPosition, buffer, readString);
  11865. },
  11866. function labeledStatement(node, position, buffer, readString) {
  11867. const { scope } = node;
  11868. node.label = convertNode(node, scope, buffer[position], buffer, readString);
  11869. node.body = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11870. },
  11871. function literalBigInt(node, position, buffer, readString) {
  11872. const bigint = (node.bigint = convertString(buffer[position], buffer, readString));
  11873. node.raw = convertString(buffer[position + 1], buffer, readString);
  11874. node.value = BigInt(bigint);
  11875. },
  11876. function literalBoolean(node, position, buffer) {
  11877. const flags = buffer[position];
  11878. const value = (node.value = (flags & 1) === 1);
  11879. node.raw = value ? 'true' : 'false';
  11880. },
  11881. function literalNull(node) {
  11882. node.value = null;
  11883. },
  11884. function literalNumber(node, position, buffer, readString) {
  11885. const rawPosition = buffer[position];
  11886. node.raw = rawPosition === 0 ? undefined : convertString(rawPosition, buffer, readString);
  11887. node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
  11888. },
  11889. function literalRegExp(node, position, buffer, readString) {
  11890. const flags = convertString(buffer[position], buffer, readString);
  11891. const pattern = convertString(buffer[position + 1], buffer, readString);
  11892. node.raw = `/${pattern}/${flags}`;
  11893. node.regex = { flags, pattern };
  11894. node.value = new RegExp(pattern, flags);
  11895. },
  11896. function literalString(node, position, buffer, readString) {
  11897. node.value = convertString(buffer[position], buffer, readString);
  11898. const rawPosition = buffer[position + 1];
  11899. node.raw = rawPosition === 0 ? undefined : convertString(rawPosition, buffer, readString);
  11900. },
  11901. function logicalExpression(node, position, buffer, readString) {
  11902. const { scope } = node;
  11903. node.operator = FIXED_STRINGS[buffer[position]];
  11904. node.left = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11905. node.right = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11906. },
  11907. function memberExpression(node, position, buffer, readString) {
  11908. const { scope } = node;
  11909. const flags = buffer[position];
  11910. node.computed = (flags & 1) === 1;
  11911. node.optional = (flags & 2) === 2;
  11912. node.object = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11913. node.property = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11914. },
  11915. function metaProperty(node, position, buffer, readString) {
  11916. const { scope } = node;
  11917. node.meta = convertNode(node, scope, buffer[position], buffer, readString);
  11918. node.property = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11919. },
  11920. function methodDefinition(node, position, buffer, readString) {
  11921. const { scope } = node;
  11922. const flags = buffer[position];
  11923. node.static = (flags & 1) === 1;
  11924. node.computed = (flags & 2) === 2;
  11925. node.key = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11926. node.value = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11927. node.kind = FIXED_STRINGS[buffer[position + 3]];
  11928. },
  11929. function newExpression(node, position, buffer, readString) {
  11930. const { scope } = node;
  11931. node.annotations = convertAnnotations(buffer[position], buffer);
  11932. node.callee = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11933. node.arguments = convertNodeList(node, scope, buffer[position + 2], buffer, readString);
  11934. },
  11935. function objectExpression(node, position, buffer, readString) {
  11936. const { scope } = node;
  11937. node.properties = convertNodeList(node, scope, buffer[position], buffer, readString);
  11938. },
  11939. function objectPattern(node, position, buffer, readString) {
  11940. const { scope } = node;
  11941. node.properties = convertNodeList(node, scope, buffer[position], buffer, readString);
  11942. },
  11943. function privateIdentifier(node, position, buffer, readString) {
  11944. node.name = convertString(buffer[position], buffer, readString);
  11945. },
  11946. function program(node, position, buffer, readString) {
  11947. const { scope } = node;
  11948. node.body = convertNodeList(node, scope, buffer[position], buffer, readString);
  11949. node.invalidAnnotations = convertAnnotations(buffer[position + 1], buffer);
  11950. },
  11951. function property(node, position, buffer, readString) {
  11952. const { scope } = node;
  11953. const flags = buffer[position];
  11954. node.method = (flags & 1) === 1;
  11955. node.shorthand = (flags & 2) === 2;
  11956. node.computed = (flags & 4) === 4;
  11957. const keyPosition = buffer[position + 1];
  11958. node.value = convertNode(node, scope, buffer[position + 2], buffer, readString);
  11959. node.kind = FIXED_STRINGS[buffer[position + 3]];
  11960. node.key =
  11961. keyPosition === 0 ? node.value : convertNode(node, scope, keyPosition, buffer, readString);
  11962. },
  11963. function propertyDefinition(node, position, buffer, readString) {
  11964. const { scope } = node;
  11965. const flags = buffer[position];
  11966. node.static = (flags & 1) === 1;
  11967. node.computed = (flags & 2) === 2;
  11968. node.key = convertNode(node, scope, buffer[position + 1], buffer, readString);
  11969. const valuePosition = buffer[position + 2];
  11970. node.value =
  11971. valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer, readString);
  11972. },
  11973. function restElement(node, position, buffer, readString) {
  11974. const { scope } = node;
  11975. node.argument = convertNode(node, scope, buffer[position], buffer, readString);
  11976. },
  11977. function returnStatement(node, position, buffer, readString) {
  11978. const { scope } = node;
  11979. const argumentPosition = buffer[position];
  11980. node.argument =
  11981. argumentPosition === 0
  11982. ? null
  11983. : convertNode(node, scope, argumentPosition, buffer, readString);
  11984. },
  11985. function sequenceExpression(node, position, buffer, readString) {
  11986. const { scope } = node;
  11987. node.expressions = convertNodeList(node, scope, buffer[position], buffer, readString);
  11988. },
  11989. function spreadElement(node, position, buffer, readString) {
  11990. const { scope } = node;
  11991. node.argument = convertNode(node, scope, buffer[position], buffer, readString);
  11992. },
  11993. function staticBlock(node, position, buffer, readString) {
  11994. const { scope } = node;
  11995. node.body = convertNodeList(node, scope, buffer[position], buffer, readString);
  11996. },
  11997. function superElement() { },
  11998. function switchCase(node, position, buffer, readString) {
  11999. const { scope } = node;
  12000. const testPosition = buffer[position];
  12001. node.test =
  12002. testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer, readString);
  12003. node.consequent = convertNodeList(node, scope, buffer[position + 1], buffer, readString);
  12004. },
  12005. function switchStatement(node, position, buffer, readString) {
  12006. const { scope } = node;
  12007. node.discriminant = convertNode(node, node.parentScope, buffer[position], buffer, readString);
  12008. node.cases = convertNodeList(node, scope, buffer[position + 1], buffer, readString);
  12009. },
  12010. function taggedTemplateExpression(node, position, buffer, readString) {
  12011. const { scope } = node;
  12012. node.tag = convertNode(node, scope, buffer[position], buffer, readString);
  12013. node.quasi = convertNode(node, scope, buffer[position + 1], buffer, readString);
  12014. },
  12015. function templateElement(node, position, buffer, readString) {
  12016. const flags = buffer[position];
  12017. node.tail = (flags & 1) === 1;
  12018. const cookedPosition = buffer[position + 1];
  12019. const cooked = cookedPosition === 0 ? undefined : convertString(cookedPosition, buffer, readString);
  12020. const raw = convertString(buffer[position + 2], buffer, readString);
  12021. node.value = { cooked, raw };
  12022. },
  12023. function templateLiteral(node, position, buffer, readString) {
  12024. const { scope } = node;
  12025. node.quasis = convertNodeList(node, scope, buffer[position], buffer, readString);
  12026. node.expressions = convertNodeList(node, scope, buffer[position + 1], buffer, readString);
  12027. },
  12028. function thisExpression() { },
  12029. function throwStatement(node, position, buffer, readString) {
  12030. const { scope } = node;
  12031. node.argument = convertNode(node, scope, buffer[position], buffer, readString);
  12032. },
  12033. function tryStatement(node, position, buffer, readString) {
  12034. const { scope } = node;
  12035. node.block = convertNode(node, scope, buffer[position], buffer, readString);
  12036. const handlerPosition = buffer[position + 1];
  12037. node.handler =
  12038. handlerPosition === 0 ? null : convertNode(node, scope, handlerPosition, buffer, readString);
  12039. const finalizerPosition = buffer[position + 2];
  12040. node.finalizer =
  12041. finalizerPosition === 0
  12042. ? null
  12043. : convertNode(node, scope, finalizerPosition, buffer, readString);
  12044. },
  12045. function unaryExpression(node, position, buffer, readString) {
  12046. const { scope } = node;
  12047. node.operator = FIXED_STRINGS[buffer[position]];
  12048. node.argument = convertNode(node, scope, buffer[position + 1], buffer, readString);
  12049. },
  12050. function updateExpression(node, position, buffer, readString) {
  12051. const { scope } = node;
  12052. const flags = buffer[position];
  12053. node.prefix = (flags & 1) === 1;
  12054. node.operator = FIXED_STRINGS[buffer[position + 1]];
  12055. node.argument = convertNode(node, scope, buffer[position + 2], buffer, readString);
  12056. },
  12057. function variableDeclaration(node, position, buffer, readString) {
  12058. const { scope } = node;
  12059. node.kind = FIXED_STRINGS[buffer[position]];
  12060. node.declarations = convertNodeList(node, scope, buffer[position + 1], buffer, readString);
  12061. },
  12062. function variableDeclarator(node, position, buffer, readString) {
  12063. const { scope } = node;
  12064. node.id = convertNode(node, scope, buffer[position], buffer, readString);
  12065. const initPosition = buffer[position + 1];
  12066. node.init =
  12067. initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer, readString);
  12068. },
  12069. function whileStatement(node, position, buffer, readString) {
  12070. const { scope } = node;
  12071. node.test = convertNode(node, scope, buffer[position], buffer, readString);
  12072. node.body = convertNode(node, scope, buffer[position + 1], buffer, readString);
  12073. },
  12074. function yieldExpression(node, position, buffer, readString) {
  12075. const { scope } = node;
  12076. const flags = buffer[position];
  12077. node.delegate = (flags & 1) === 1;
  12078. const argumentPosition = buffer[position + 1];
  12079. node.argument =
  12080. argumentPosition === 0
  12081. ? null
  12082. : convertNode(node, scope, argumentPosition, buffer, readString);
  12083. }
  12084. ];
  12085. function convertNode(parent, parentScope, position, buffer, readString) {
  12086. const nodeType = buffer[position];
  12087. const NodeConstructor = nodeConstructors$1[nodeType];
  12088. /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
  12089. if (!NodeConstructor) {
  12090. console.trace();
  12091. throw new Error(`Unknown node type: ${nodeType}`);
  12092. }
  12093. const node = new NodeConstructor(parent, parentScope);
  12094. node.type = nodeTypeStrings[nodeType];
  12095. node.start = buffer[position + 1];
  12096. node.end = buffer[position + 2];
  12097. bufferParsers[nodeType](node, position + 3, buffer, readString);
  12098. node.initialise();
  12099. return node;
  12100. }
  12101. function convertNodeList(parent, parentScope, position, buffer, readString) {
  12102. if (position === 0)
  12103. return EMPTY_ARRAY;
  12104. const length = buffer[position++];
  12105. const list = [];
  12106. for (let index = 0; index < length; index++) {
  12107. const nodePosition = buffer[position++];
  12108. list.push(nodePosition ? convertNode(parent, parentScope, nodePosition, buffer, readString) : null);
  12109. }
  12110. return list;
  12111. }
  12112. class UnknownNode extends NodeBase {
  12113. hasEffects() {
  12114. return true;
  12115. }
  12116. include(context) {
  12117. super.include(context, true);
  12118. }
  12119. }
  12120. const nodeConstructors = {
  12121. ArrayExpression,
  12122. ArrayPattern,
  12123. ArrowFunctionExpression,
  12124. AssignmentExpression,
  12125. AssignmentPattern,
  12126. AwaitExpression,
  12127. BinaryExpression,
  12128. BlockStatement,
  12129. BreakStatement,
  12130. CallExpression,
  12131. CatchClause,
  12132. ChainExpression,
  12133. ClassBody,
  12134. ClassDeclaration,
  12135. ClassExpression,
  12136. ConditionalExpression,
  12137. ContinueStatement,
  12138. DoWhileStatement,
  12139. EmptyStatement,
  12140. ExportAllDeclaration,
  12141. ExportDefaultDeclaration,
  12142. ExportNamedDeclaration,
  12143. ExportSpecifier,
  12144. ExpressionStatement,
  12145. ForInStatement,
  12146. ForOfStatement,
  12147. ForStatement,
  12148. FunctionDeclaration,
  12149. FunctionExpression,
  12150. Identifier,
  12151. IfStatement,
  12152. ImportAttribute,
  12153. ImportDeclaration,
  12154. ImportDefaultSpecifier,
  12155. ImportExpression,
  12156. ImportNamespaceSpecifier,
  12157. ImportSpecifier,
  12158. LabeledStatement,
  12159. Literal,
  12160. LogicalExpression,
  12161. MemberExpression,
  12162. MetaProperty,
  12163. MethodDefinition,
  12164. NewExpression,
  12165. ObjectExpression,
  12166. ObjectPattern,
  12167. PanicError,
  12168. ParseError,
  12169. PrivateIdentifier,
  12170. Program,
  12171. Property,
  12172. PropertyDefinition,
  12173. RestElement,
  12174. ReturnStatement,
  12175. SequenceExpression,
  12176. SpreadElement,
  12177. StaticBlock,
  12178. Super,
  12179. SwitchCase,
  12180. SwitchStatement,
  12181. TaggedTemplateExpression,
  12182. TemplateElement,
  12183. TemplateLiteral,
  12184. ThisExpression,
  12185. ThrowStatement,
  12186. TryStatement,
  12187. UnaryExpression,
  12188. UnknownNode,
  12189. UpdateExpression,
  12190. VariableDeclaration,
  12191. VariableDeclarator,
  12192. WhileStatement,
  12193. YieldExpression
  12194. };
  12195. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  12196. class ExportShimVariable extends Variable {
  12197. constructor(module) {
  12198. super(MISSING_EXPORT_SHIM_VARIABLE);
  12199. this.module = module;
  12200. }
  12201. include() {
  12202. super.include();
  12203. this.module.needsExportShim = true;
  12204. }
  12205. }
  12206. class NamespaceVariable extends Variable {
  12207. constructor(context) {
  12208. super(context.getModuleName());
  12209. this.memberVariables = null;
  12210. this.mergedNamespaces = [];
  12211. this.referencedEarly = false;
  12212. this.references = [];
  12213. this.context = context;
  12214. this.module = context.module;
  12215. }
  12216. addReference(identifier) {
  12217. this.references.push(identifier);
  12218. this.name = identifier.name;
  12219. }
  12220. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12221. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  12222. const key = path[0];
  12223. if (typeof key === 'string') {
  12224. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  12225. }
  12226. else {
  12227. deoptimizeInteraction(interaction);
  12228. }
  12229. }
  12230. }
  12231. deoptimizePath(path) {
  12232. if (path.length > 1) {
  12233. const key = path[0];
  12234. if (typeof key === 'string') {
  12235. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  12236. }
  12237. }
  12238. }
  12239. getLiteralValueAtPath(path) {
  12240. if (path[0] === SymbolToStringTag) {
  12241. return 'Module';
  12242. }
  12243. return UnknownValue;
  12244. }
  12245. getMemberVariables() {
  12246. if (this.memberVariables) {
  12247. return this.memberVariables;
  12248. }
  12249. const memberVariables = Object.create(null);
  12250. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  12251. for (const name of sortedExports) {
  12252. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  12253. const exportedVariable = this.context.traceExport(name);
  12254. if (exportedVariable) {
  12255. memberVariables[name] = exportedVariable;
  12256. }
  12257. }
  12258. }
  12259. return (this.memberVariables = memberVariables);
  12260. }
  12261. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12262. const { type } = interaction;
  12263. if (path.length === 0) {
  12264. // This can only be a call anyway
  12265. return true;
  12266. }
  12267. if (path.length === 1 && type !== INTERACTION_CALLED) {
  12268. return type === INTERACTION_ASSIGNED;
  12269. }
  12270. const key = path[0];
  12271. if (typeof key !== 'string') {
  12272. return true;
  12273. }
  12274. const memberVariable = this.getMemberVariables()[key];
  12275. return (!memberVariable ||
  12276. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  12277. }
  12278. include() {
  12279. super.include();
  12280. this.context.includeAllExports();
  12281. }
  12282. prepare(accessedGlobalsByScope) {
  12283. if (this.mergedNamespaces.length > 0) {
  12284. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  12285. }
  12286. }
  12287. renderBlock(options) {
  12288. const { exportNamesByVariable, format, freeze, indent: t, symbols, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  12289. const memberVariables = this.getMemberVariables();
  12290. const members = Object.entries(memberVariables)
  12291. .filter(([_, variable]) => variable.included)
  12292. .map(([name, variable]) => {
  12293. if (this.referencedEarly || variable.isReassigned || variable === this) {
  12294. return [
  12295. null,
  12296. `get ${stringifyObjectKeyIfNeeded(name)}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  12297. ];
  12298. }
  12299. return [name, variable.getName(getPropertyAccess)];
  12300. });
  12301. members.unshift([null, `__proto__:${_}null`]);
  12302. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  12303. if (this.mergedNamespaces.length > 0) {
  12304. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  12305. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  12306. }
  12307. else {
  12308. // The helper to merge namespaces will also take care of freezing and toStringTag
  12309. if (symbols) {
  12310. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  12311. }
  12312. if (freeze) {
  12313. output = `/*#__PURE__*/Object.freeze(${output})`;
  12314. }
  12315. }
  12316. const name = this.getName(getPropertyAccess);
  12317. output = `${cnst} ${name}${_}=${_}${output};`;
  12318. if (format === 'system' && exportNamesByVariable.has(this)) {
  12319. output += `${n}${getSystemExportStatement([this], options)};`;
  12320. }
  12321. return output;
  12322. }
  12323. renderFirst() {
  12324. return this.referencedEarly;
  12325. }
  12326. setMergedNamespaces(mergedNamespaces) {
  12327. this.mergedNamespaces = mergedNamespaces;
  12328. const moduleExecIndex = this.context.getModuleExecIndex();
  12329. for (const identifier of this.references) {
  12330. const { context } = identifier.scope;
  12331. if (context.getModuleExecIndex() <= moduleExecIndex) {
  12332. this.referencedEarly = true;
  12333. break;
  12334. }
  12335. }
  12336. }
  12337. }
  12338. NamespaceVariable.prototype.isNamespace = true;
  12339. class SyntheticNamedExportVariable extends Variable {
  12340. constructor(context, name, syntheticNamespace) {
  12341. super(name);
  12342. this.baseVariable = null;
  12343. this.context = context;
  12344. this.module = context.module;
  12345. this.syntheticNamespace = syntheticNamespace;
  12346. }
  12347. getBaseVariable() {
  12348. if (this.baseVariable)
  12349. return this.baseVariable;
  12350. let baseVariable = this.syntheticNamespace;
  12351. while (baseVariable instanceof ExportDefaultVariable ||
  12352. baseVariable instanceof SyntheticNamedExportVariable) {
  12353. if (baseVariable instanceof ExportDefaultVariable) {
  12354. const original = baseVariable.getOriginalVariable();
  12355. if (original === baseVariable)
  12356. break;
  12357. baseVariable = original;
  12358. }
  12359. if (baseVariable instanceof SyntheticNamedExportVariable) {
  12360. baseVariable = baseVariable.syntheticNamespace;
  12361. }
  12362. }
  12363. return (this.baseVariable = baseVariable);
  12364. }
  12365. getBaseVariableName() {
  12366. return this.syntheticNamespace.getBaseVariableName();
  12367. }
  12368. getName(getPropertyAccess) {
  12369. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  12370. }
  12371. include() {
  12372. super.include();
  12373. this.context.includeVariableInModule(this.syntheticNamespace);
  12374. }
  12375. setRenderNames(baseName, name) {
  12376. super.setRenderNames(baseName, name);
  12377. }
  12378. }
  12379. var BuildPhase;
  12380. (function (BuildPhase) {
  12381. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  12382. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  12383. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  12384. })(BuildPhase || (BuildPhase = {}));
  12385. const sourceMapCache = new WeakMap();
  12386. /**
  12387. * This clears the decoded array and falls back to the encoded string form.
  12388. * Sourcemap mappings arrays can be very large and holding on to them for longer
  12389. * than is necessary leads to poor heap utilization.
  12390. */
  12391. function resetCacheToEncoded(cache) {
  12392. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  12393. cache.encodedMappings = encode(cache.decodedMappings);
  12394. }
  12395. cache.decodedMappings = undefined;
  12396. }
  12397. function resetSourcemapCache(map, sourcemapChain) {
  12398. if (map) {
  12399. const cache = sourceMapCache.get(map);
  12400. if (cache) {
  12401. resetCacheToEncoded(cache);
  12402. }
  12403. }
  12404. if (!sourcemapChain) {
  12405. return;
  12406. }
  12407. for (const map of sourcemapChain) {
  12408. if (map.missing)
  12409. continue;
  12410. resetSourcemapCache(map);
  12411. }
  12412. }
  12413. function decodedSourcemap(map) {
  12414. if (!map)
  12415. return null;
  12416. if (typeof map === 'string') {
  12417. map = JSON.parse(map);
  12418. }
  12419. if (!map.mappings) {
  12420. return {
  12421. mappings: [],
  12422. names: [],
  12423. sources: [],
  12424. version: 3
  12425. };
  12426. }
  12427. const originalMappings = map.mappings;
  12428. const isAlreadyDecoded = Array.isArray(originalMappings);
  12429. const cache = {
  12430. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  12431. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  12432. };
  12433. const decodedMap = {
  12434. ...map,
  12435. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  12436. // where the mappings field is never actually accessed. This appears to greatly reduce
  12437. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  12438. get mappings() {
  12439. if (cache.decodedMappings) {
  12440. return cache.decodedMappings;
  12441. }
  12442. // If decodedMappings doesn't exist then encodedMappings should.
  12443. // The only scenario where cache.encodedMappings should be undefined is if the map
  12444. // this was constructed from was already decoded, or if mappings was set to a new
  12445. // decoded string. In either case, this line shouldn't get hit.
  12446. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  12447. cache.encodedMappings = undefined;
  12448. return cache.decodedMappings;
  12449. }
  12450. };
  12451. sourceMapCache.set(decodedMap, cache);
  12452. return decodedMap;
  12453. }
  12454. function getId(m) {
  12455. return m.id;
  12456. }
  12457. function getOriginalLocation(sourcemapChain, location) {
  12458. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  12459. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  12460. const sourcemap = filteredSourcemapChain.pop();
  12461. const line = sourcemap.mappings[location.line - 1];
  12462. if (line) {
  12463. const filteredLine = line.filter((segment) => segment.length > 1);
  12464. const lastSegment = filteredLine[filteredLine.length - 1];
  12465. for (const segment of filteredLine) {
  12466. if (segment[0] >= location.column || segment === lastSegment) {
  12467. location = {
  12468. column: segment[3],
  12469. line: segment[2] + 1
  12470. };
  12471. continue traceSourcemap;
  12472. }
  12473. }
  12474. }
  12475. throw new Error("Can't resolve original location of error.");
  12476. }
  12477. return location;
  12478. }
  12479. const ATTRIBUTE_KEYWORDS = new Set(['assert', 'with']);
  12480. function getAttributesFromImportExpression(node) {
  12481. const { scope: { context }, options, start } = node;
  12482. if (!(options instanceof ObjectExpression)) {
  12483. if (options) {
  12484. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), start);
  12485. }
  12486. return EMPTY_OBJECT;
  12487. }
  12488. const assertProperty = options.properties.find((property) => ATTRIBUTE_KEYWORDS.has(getPropertyKey(property)))?.value;
  12489. if (!assertProperty) {
  12490. return EMPTY_OBJECT;
  12491. }
  12492. if (!(assertProperty instanceof ObjectExpression)) {
  12493. context.module.log(LOGLEVEL_WARN, logImportOptionsAreInvalid(context.module.id), start);
  12494. return EMPTY_OBJECT;
  12495. }
  12496. const assertFields = assertProperty.properties
  12497. .map(property => {
  12498. const key = getPropertyKey(property);
  12499. if (typeof key === 'string' &&
  12500. typeof property.value.value === 'string') {
  12501. return [key, property.value.value];
  12502. }
  12503. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), property.start);
  12504. return null;
  12505. })
  12506. .filter((property) => !!property);
  12507. if (assertFields.length > 0) {
  12508. return Object.fromEntries(assertFields);
  12509. }
  12510. return EMPTY_OBJECT;
  12511. }
  12512. const getPropertyKey = (property) => {
  12513. const key = property.key;
  12514. return (key &&
  12515. !property.computed &&
  12516. (key.name || key.value));
  12517. };
  12518. function getAttributesFromImportExportDeclaration(attributes) {
  12519. return attributes?.length
  12520. ? Object.fromEntries(attributes.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  12521. : EMPTY_OBJECT;
  12522. }
  12523. function doAttributesDiffer(assertionA, assertionB) {
  12524. const keysA = Object.keys(assertionA);
  12525. return (keysA.length !== Object.keys(assertionB).length ||
  12526. keysA.some(key => assertionA[key] !== assertionB[key]));
  12527. }
  12528. let timers = new Map();
  12529. function getPersistedLabel(label, level) {
  12530. switch (level) {
  12531. case 1: {
  12532. return `# ${label}`;
  12533. }
  12534. case 2: {
  12535. return `## ${label}`;
  12536. }
  12537. case 3: {
  12538. return label;
  12539. }
  12540. default: {
  12541. return `${' '.repeat(level - 4)}- ${label}`;
  12542. }
  12543. }
  12544. }
  12545. function timeStartImpl(label, level = 3) {
  12546. label = getPersistedLabel(label, level);
  12547. const startMemory = process$1.memoryUsage().heapUsed;
  12548. const startTime = performance.now();
  12549. const timer = timers.get(label);
  12550. if (timer === undefined) {
  12551. timers.set(label, {
  12552. memory: 0,
  12553. startMemory,
  12554. startTime,
  12555. time: 0,
  12556. totalMemory: 0
  12557. });
  12558. }
  12559. else {
  12560. timer.startMemory = startMemory;
  12561. timer.startTime = startTime;
  12562. }
  12563. }
  12564. function timeEndImpl(label, level = 3) {
  12565. label = getPersistedLabel(label, level);
  12566. const timer = timers.get(label);
  12567. if (timer !== undefined) {
  12568. const currentMemory = process$1.memoryUsage().heapUsed;
  12569. timer.memory += currentMemory - timer.startMemory;
  12570. timer.time += performance.now() - timer.startTime;
  12571. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  12572. }
  12573. }
  12574. function getTimings() {
  12575. const newTimings = {};
  12576. for (const [label, { memory, time, totalMemory }] of timers) {
  12577. newTimings[label] = [time, memory, totalMemory];
  12578. }
  12579. return newTimings;
  12580. }
  12581. let timeStart = doNothing;
  12582. let timeEnd = doNothing;
  12583. const TIMED_PLUGIN_HOOKS = [
  12584. 'augmentChunkHash',
  12585. 'buildEnd',
  12586. 'buildStart',
  12587. 'generateBundle',
  12588. 'load',
  12589. 'moduleParsed',
  12590. 'options',
  12591. 'outputOptions',
  12592. 'renderChunk',
  12593. 'renderDynamicImport',
  12594. 'renderStart',
  12595. 'resolveDynamicImport',
  12596. 'resolveFileUrl',
  12597. 'resolveId',
  12598. 'resolveImportMeta',
  12599. 'shouldTransformCachedModule',
  12600. 'transform',
  12601. 'writeBundle'
  12602. ];
  12603. function getPluginWithTimers(plugin, index) {
  12604. if (plugin._hasTimer)
  12605. return plugin;
  12606. plugin._hasTimer = true;
  12607. for (const hook of TIMED_PLUGIN_HOOKS) {
  12608. if (hook in plugin) {
  12609. let timerLabel = `plugin ${index}`;
  12610. if (plugin.name) {
  12611. timerLabel += ` (${plugin.name})`;
  12612. }
  12613. timerLabel += ` - ${hook}`;
  12614. const handler = function (...parameters) {
  12615. timeStart(timerLabel, 4);
  12616. const result = hookFunction.apply(this, parameters);
  12617. timeEnd(timerLabel, 4);
  12618. return result;
  12619. };
  12620. let hookFunction;
  12621. if (typeof plugin[hook].handler === 'function') {
  12622. hookFunction = plugin[hook].handler;
  12623. plugin[hook].handler = handler;
  12624. }
  12625. else {
  12626. hookFunction = plugin[hook];
  12627. plugin[hook] = handler;
  12628. }
  12629. }
  12630. }
  12631. return plugin;
  12632. }
  12633. function initialiseTimers(inputOptions) {
  12634. if (inputOptions.perf) {
  12635. timers = new Map();
  12636. timeStart = timeStartImpl;
  12637. timeEnd = timeEndImpl;
  12638. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  12639. }
  12640. else {
  12641. timeStart = doNothing;
  12642. timeEnd = doNothing;
  12643. }
  12644. }
  12645. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  12646. baseModule.isExecuted = true;
  12647. const modules = [baseModule];
  12648. const visitedModules = new Set();
  12649. for (const module of modules) {
  12650. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  12651. if (!(dependency instanceof ExternalModule) &&
  12652. !dependency.isExecuted &&
  12653. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  12654. !visitedModules.has(dependency.id)) {
  12655. dependency.isExecuted = true;
  12656. visitedModules.add(dependency.id);
  12657. modules.push(dependency);
  12658. }
  12659. }
  12660. }
  12661. }
  12662. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  12663. identifier: null,
  12664. localName: MISSING_EXPORT_SHIM_VARIABLE
  12665. };
  12666. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  12667. const searchedModules = searchedNamesAndModules.get(name);
  12668. if (searchedModules) {
  12669. if (searchedModules.has(target)) {
  12670. return isExportAllSearch ? [null] : error(logCircularReexport(name, target.id));
  12671. }
  12672. searchedModules.add(target);
  12673. }
  12674. else {
  12675. searchedNamesAndModules.set(name, new Set([target]));
  12676. }
  12677. return target.getVariableForExportName(name, {
  12678. importerForSideEffects,
  12679. isExportAllSearch,
  12680. searchedNamesAndModules
  12681. });
  12682. }
  12683. function getAndExtendSideEffectModules(variable, module) {
  12684. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  12685. let currentVariable = variable;
  12686. const referencedVariables = new Set([currentVariable]);
  12687. while (true) {
  12688. const importingModule = currentVariable.module;
  12689. currentVariable =
  12690. currentVariable instanceof ExportDefaultVariable
  12691. ? currentVariable.getDirectOriginalVariable()
  12692. : currentVariable instanceof SyntheticNamedExportVariable
  12693. ? currentVariable.syntheticNamespace
  12694. : null;
  12695. if (!currentVariable || referencedVariables.has(currentVariable)) {
  12696. break;
  12697. }
  12698. referencedVariables.add(currentVariable);
  12699. sideEffectModules.add(importingModule);
  12700. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  12701. if (originalSideEffects) {
  12702. for (const module of originalSideEffects) {
  12703. sideEffectModules.add(module);
  12704. }
  12705. }
  12706. }
  12707. return sideEffectModules;
  12708. }
  12709. class Module {
  12710. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
  12711. this.graph = graph;
  12712. this.id = id;
  12713. this.options = options;
  12714. this.alternativeReexportModules = new Map();
  12715. this.chunkFileNames = new Set();
  12716. this.chunkNames = [];
  12717. this.cycles = new Set();
  12718. this.dependencies = new Set();
  12719. this.dynamicDependencies = new Set();
  12720. this.dynamicImporters = [];
  12721. this.dynamicImports = [];
  12722. this.execIndex = Infinity;
  12723. this.implicitlyLoadedAfter = new Set();
  12724. this.implicitlyLoadedBefore = new Set();
  12725. this.importDescriptions = new Map();
  12726. this.importMetas = [];
  12727. this.importedFromNotTreeshaken = false;
  12728. this.importers = [];
  12729. this.includedDynamicImporters = [];
  12730. this.includedImports = new Set();
  12731. this.isExecuted = false;
  12732. this.isUserDefinedEntryPoint = false;
  12733. this.needsExportShim = false;
  12734. this.sideEffectDependenciesByVariable = new Map();
  12735. this.sourcesWithAttributes = new Map();
  12736. this.allExportNames = null;
  12737. this.ast = null;
  12738. this.exportAllModules = [];
  12739. this.exportAllSources = new Set();
  12740. this.exportNamesByVariable = null;
  12741. this.exportShimVariable = new ExportShimVariable(this);
  12742. this.exports = new Map();
  12743. this.namespaceReexportsByName = new Map();
  12744. this.reexportDescriptions = new Map();
  12745. this.relevantDependencies = null;
  12746. this.syntheticExports = new Map();
  12747. this.syntheticNamespace = null;
  12748. this.transformDependencies = [];
  12749. this.transitiveReexports = null;
  12750. this.excludeFromSourcemap = /\0/.test(id);
  12751. this.context = options.moduleContext(id);
  12752. this.preserveSignature = this.options.preserveEntrySignatures;
  12753. // eslint-disable-next-line @typescript-eslint/no-this-alias
  12754. const module = this;
  12755. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
  12756. this.info = {
  12757. ast: null,
  12758. attributes,
  12759. code: null,
  12760. get dynamicallyImportedIdResolutions() {
  12761. return dynamicImports
  12762. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  12763. .filter(Boolean);
  12764. },
  12765. get dynamicallyImportedIds() {
  12766. // We cannot use this.dynamicDependencies because this is needed before
  12767. // dynamicDependencies are populated
  12768. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  12769. },
  12770. get dynamicImporters() {
  12771. return dynamicImporters.sort();
  12772. },
  12773. get exportedBindings() {
  12774. const exportBindings = { '.': [...exports.keys()] };
  12775. for (const [name, { source }] of reexportDescriptions) {
  12776. (exportBindings[source] ??= []).push(name);
  12777. }
  12778. for (const source of exportAllSources) {
  12779. (exportBindings[source] ??= []).push('*');
  12780. }
  12781. return exportBindings;
  12782. },
  12783. get exports() {
  12784. return [
  12785. ...exports.keys(),
  12786. ...reexportDescriptions.keys(),
  12787. ...[...exportAllSources].map(() => '*')
  12788. ];
  12789. },
  12790. get hasDefaultExport() {
  12791. // This information is only valid after parsing
  12792. if (!module.ast) {
  12793. return null;
  12794. }
  12795. return module.exports.has('default') || reexportDescriptions.has('default');
  12796. },
  12797. id,
  12798. get implicitlyLoadedAfterOneOf() {
  12799. // eslint-disable-next-line unicorn/prefer-spread
  12800. return Array.from(implicitlyLoadedAfter, getId).sort();
  12801. },
  12802. get implicitlyLoadedBefore() {
  12803. // eslint-disable-next-line unicorn/prefer-spread
  12804. return Array.from(implicitlyLoadedBefore, getId).sort();
  12805. },
  12806. get importedIdResolutions() {
  12807. // eslint-disable-next-line unicorn/prefer-spread
  12808. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
  12809. },
  12810. get importedIds() {
  12811. // We cannot use this.dependencies because this is needed before
  12812. // dependencies are populated
  12813. // eslint-disable-next-line unicorn/prefer-spread
  12814. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  12815. },
  12816. get importers() {
  12817. return importers.sort();
  12818. },
  12819. isEntry,
  12820. isExternal: false,
  12821. get isIncluded() {
  12822. if (graph.phase !== BuildPhase.GENERATE) {
  12823. return null;
  12824. }
  12825. return module.isIncluded();
  12826. },
  12827. meta: { ...meta },
  12828. moduleSideEffects,
  12829. syntheticNamedExports
  12830. };
  12831. }
  12832. basename() {
  12833. const base = basename(this.id);
  12834. const extension = extname(this.id);
  12835. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  12836. }
  12837. bindReferences() {
  12838. this.ast.bind();
  12839. }
  12840. cacheInfoGetters() {
  12841. cacheObjectGetters(this.info, [
  12842. 'dynamicallyImportedIdResolutions',
  12843. 'dynamicallyImportedIds',
  12844. 'dynamicImporters',
  12845. 'exportedBindings',
  12846. 'exports',
  12847. 'hasDefaultExport',
  12848. 'implicitlyLoadedAfterOneOf',
  12849. 'implicitlyLoadedBefore',
  12850. 'importedIdResolutions',
  12851. 'importedIds',
  12852. 'importers'
  12853. ]);
  12854. }
  12855. error(properties, pos) {
  12856. pos !== undefined && this.addLocationToLogProps(properties, pos);
  12857. return error(properties);
  12858. }
  12859. // sum up the length of all ast nodes that are included
  12860. estimateSize() {
  12861. let size = 0;
  12862. for (const node of this.ast.body) {
  12863. if (node.included) {
  12864. size += node.end - node.start;
  12865. }
  12866. }
  12867. return size;
  12868. }
  12869. getAllExportNames() {
  12870. if (this.allExportNames) {
  12871. return this.allExportNames;
  12872. }
  12873. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  12874. for (const module of this.exportAllModules) {
  12875. if (module instanceof ExternalModule) {
  12876. this.allExportNames.add(`*${module.id}`);
  12877. continue;
  12878. }
  12879. for (const name of module.getAllExportNames()) {
  12880. if (name !== 'default')
  12881. this.allExportNames.add(name);
  12882. }
  12883. }
  12884. // We do not count the synthetic namespace as a regular export to hide it
  12885. // from entry signatures and namespace objects
  12886. if (typeof this.info.syntheticNamedExports === 'string') {
  12887. this.allExportNames.delete(this.info.syntheticNamedExports);
  12888. }
  12889. return this.allExportNames;
  12890. }
  12891. getDependenciesToBeIncluded() {
  12892. if (this.relevantDependencies)
  12893. return this.relevantDependencies;
  12894. this.relevantDependencies = new Set();
  12895. const necessaryDependencies = new Set();
  12896. const alwaysCheckedDependencies = new Set();
  12897. const dependencyVariables = new Set(this.includedImports);
  12898. if (this.info.isEntry ||
  12899. this.includedDynamicImporters.length > 0 ||
  12900. this.namespace.included ||
  12901. this.implicitlyLoadedAfter.size > 0) {
  12902. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  12903. const [exportedVariable] = this.getVariableForExportName(exportName);
  12904. if (exportedVariable?.included) {
  12905. dependencyVariables.add(exportedVariable);
  12906. }
  12907. }
  12908. }
  12909. for (let variable of dependencyVariables) {
  12910. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  12911. if (sideEffectDependencies) {
  12912. for (const module of sideEffectDependencies) {
  12913. alwaysCheckedDependencies.add(module);
  12914. }
  12915. }
  12916. if (variable instanceof SyntheticNamedExportVariable) {
  12917. variable = variable.getBaseVariable();
  12918. }
  12919. else if (variable instanceof ExportDefaultVariable) {
  12920. variable = variable.getOriginalVariable();
  12921. }
  12922. necessaryDependencies.add(variable.module);
  12923. }
  12924. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  12925. for (const dependency of this.dependencies) {
  12926. this.relevantDependencies.add(dependency);
  12927. }
  12928. }
  12929. else {
  12930. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  12931. }
  12932. for (const dependency of necessaryDependencies) {
  12933. this.relevantDependencies.add(dependency);
  12934. }
  12935. return this.relevantDependencies;
  12936. }
  12937. getExportNamesByVariable() {
  12938. if (this.exportNamesByVariable) {
  12939. return this.exportNamesByVariable;
  12940. }
  12941. const exportNamesByVariable = new Map();
  12942. for (const exportName of this.getAllExportNames()) {
  12943. let [tracedVariable] = this.getVariableForExportName(exportName);
  12944. if (tracedVariable instanceof ExportDefaultVariable) {
  12945. tracedVariable = tracedVariable.getOriginalVariable();
  12946. }
  12947. if (!tracedVariable ||
  12948. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  12949. continue;
  12950. }
  12951. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  12952. if (existingExportNames) {
  12953. existingExportNames.push(exportName);
  12954. }
  12955. else {
  12956. exportNamesByVariable.set(tracedVariable, [exportName]);
  12957. }
  12958. }
  12959. return (this.exportNamesByVariable = exportNamesByVariable);
  12960. }
  12961. getExports() {
  12962. return [...this.exports.keys()];
  12963. }
  12964. getReexports() {
  12965. if (this.transitiveReexports) {
  12966. return this.transitiveReexports;
  12967. }
  12968. // to avoid infinite recursion when using circular `export * from X`
  12969. this.transitiveReexports = [];
  12970. const reexports = new Set(this.reexportDescriptions.keys());
  12971. for (const module of this.exportAllModules) {
  12972. if (module instanceof ExternalModule) {
  12973. reexports.add(`*${module.id}`);
  12974. }
  12975. else {
  12976. for (const name of [...module.getReexports(), ...module.getExports()]) {
  12977. if (name !== 'default')
  12978. reexports.add(name);
  12979. }
  12980. }
  12981. }
  12982. return (this.transitiveReexports = [...reexports]);
  12983. }
  12984. getRenderedExports() {
  12985. // only direct exports are counted here, not reexports at all
  12986. const renderedExports = [];
  12987. const removedExports = [];
  12988. for (const exportName of this.exports.keys()) {
  12989. const [variable] = this.getVariableForExportName(exportName);
  12990. (variable?.included ? renderedExports : removedExports).push(exportName);
  12991. }
  12992. return { removedExports, renderedExports };
  12993. }
  12994. getSyntheticNamespace() {
  12995. if (this.syntheticNamespace === null) {
  12996. this.syntheticNamespace = undefined;
  12997. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  12998. ? this.info.syntheticNamedExports
  12999. : 'default', { onlyExplicit: true });
  13000. }
  13001. if (!this.syntheticNamespace) {
  13002. return error(logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  13003. }
  13004. return this.syntheticNamespace;
  13005. }
  13006. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  13007. if (name[0] === '*') {
  13008. if (name.length === 1) {
  13009. // export * from './other'
  13010. return [this.namespace];
  13011. }
  13012. // export * from 'external'
  13013. const module = this.graph.modulesById.get(name.slice(1));
  13014. return module.getVariableForExportName('*');
  13015. }
  13016. // export { foo } from './other'
  13017. const reexportDeclaration = this.reexportDescriptions.get(name);
  13018. if (reexportDeclaration) {
  13019. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  13020. if (!variable) {
  13021. return this.error(logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  13022. }
  13023. if (importerForSideEffects) {
  13024. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  13025. if (this.info.moduleSideEffects) {
  13026. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  13027. }
  13028. }
  13029. return [variable];
  13030. }
  13031. const exportDeclaration = this.exports.get(name);
  13032. if (exportDeclaration) {
  13033. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  13034. return [this.exportShimVariable];
  13035. }
  13036. const name = exportDeclaration.localName;
  13037. const variable = this.traceVariable(name, {
  13038. importerForSideEffects,
  13039. searchedNamesAndModules
  13040. });
  13041. if (importerForSideEffects) {
  13042. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  13043. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  13044. }
  13045. return [variable];
  13046. }
  13047. if (onlyExplicit) {
  13048. return [null];
  13049. }
  13050. if (name !== 'default') {
  13051. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  13052. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  13053. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  13054. if (foundNamespaceReexport[0]) {
  13055. return foundNamespaceReexport;
  13056. }
  13057. }
  13058. if (this.info.syntheticNamedExports) {
  13059. return [
  13060. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  13061. ];
  13062. }
  13063. // we don't want to create shims when we are just
  13064. // probing export * modules for exports
  13065. if (!isExportAllSearch && this.options.shimMissingExports) {
  13066. this.shimMissingExport(name);
  13067. return [this.exportShimVariable];
  13068. }
  13069. return [null];
  13070. }
  13071. hasEffects() {
  13072. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  13073. }
  13074. include() {
  13075. const context = createInclusionContext();
  13076. if (this.ast.shouldBeIncluded(context))
  13077. this.ast.include(context, false);
  13078. }
  13079. includeAllExports(includeNamespaceMembers) {
  13080. if (!this.isExecuted) {
  13081. markModuleAndImpureDependenciesAsExecuted(this);
  13082. this.graph.needsTreeshakingPass = true;
  13083. }
  13084. for (const exportName of this.exports.keys()) {
  13085. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  13086. const variable = this.getVariableForExportName(exportName)[0];
  13087. if (!variable) {
  13088. return error(logMissingEntryExport(exportName, this.id));
  13089. }
  13090. variable.deoptimizePath(UNKNOWN_PATH);
  13091. if (!variable.included) {
  13092. this.includeVariable(variable);
  13093. }
  13094. }
  13095. }
  13096. for (const name of this.getReexports()) {
  13097. const [variable] = this.getVariableForExportName(name);
  13098. if (variable) {
  13099. variable.deoptimizePath(UNKNOWN_PATH);
  13100. if (!variable.included) {
  13101. this.includeVariable(variable);
  13102. }
  13103. if (variable instanceof ExternalVariable) {
  13104. variable.module.reexported = true;
  13105. }
  13106. }
  13107. }
  13108. if (includeNamespaceMembers) {
  13109. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  13110. }
  13111. }
  13112. includeAllInBundle() {
  13113. this.ast.include(createInclusionContext(), true);
  13114. this.includeAllExports(false);
  13115. }
  13116. includeExportsByNames(names) {
  13117. if (!this.isExecuted) {
  13118. markModuleAndImpureDependenciesAsExecuted(this);
  13119. this.graph.needsTreeshakingPass = true;
  13120. }
  13121. let includeNamespaceMembers = false;
  13122. for (const name of names) {
  13123. const variable = this.getVariableForExportName(name)[0];
  13124. if (variable) {
  13125. variable.deoptimizePath(UNKNOWN_PATH);
  13126. if (!variable.included) {
  13127. this.includeVariable(variable);
  13128. }
  13129. }
  13130. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  13131. includeNamespaceMembers = true;
  13132. }
  13133. }
  13134. if (includeNamespaceMembers) {
  13135. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  13136. }
  13137. }
  13138. isIncluded() {
  13139. // Modules where this.ast is missing have been loaded via this.load and are
  13140. // not yet fully processed, hence they cannot be included.
  13141. return (this.ast &&
  13142. (this.ast.included ||
  13143. this.namespace.included ||
  13144. this.importedFromNotTreeshaken ||
  13145. this.exportShimVariable.included));
  13146. }
  13147. linkImports() {
  13148. this.addModulesToImportDescriptions(this.importDescriptions);
  13149. this.addModulesToImportDescriptions(this.reexportDescriptions);
  13150. const externalExportAllModules = [];
  13151. for (const source of this.exportAllSources) {
  13152. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  13153. if (module instanceof ExternalModule) {
  13154. externalExportAllModules.push(module);
  13155. continue;
  13156. }
  13157. this.exportAllModules.push(module);
  13158. }
  13159. this.exportAllModules.push(...externalExportAllModules);
  13160. }
  13161. log(level, properties, pos) {
  13162. this.addLocationToLogProps(properties, pos);
  13163. this.options.onLog(level, properties);
  13164. }
  13165. render(options) {
  13166. const source = this.magicString.clone();
  13167. this.ast.render(source, options);
  13168. source.trim();
  13169. const { usesTopLevelAwait } = this.astContext;
  13170. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  13171. return error(logInvalidFormatForTopLevelAwait(this.id, options.format));
  13172. }
  13173. return { source, usesTopLevelAwait };
  13174. }
  13175. async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  13176. timeStart('generate ast', 3);
  13177. if (code.startsWith('#!')) {
  13178. const shebangEndPosition = code.indexOf('\n');
  13179. this.shebang = code.slice(2, shebangEndPosition);
  13180. }
  13181. this.info.code = code;
  13182. this.originalCode = originalCode;
  13183. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  13184. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  13185. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  13186. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  13187. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  13188. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  13189. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  13190. if (transformFiles) {
  13191. this.transformFiles = transformFiles;
  13192. }
  13193. this.transformDependencies = transformDependencies;
  13194. this.customTransformCache = customTransformCache;
  13195. this.updateOptions(moduleOptions);
  13196. this.resolvedIds = resolvedIds ?? Object.create(null);
  13197. // By default, `id` is the file name. Custom resolvers and loaders
  13198. // can change that, but it makes sense to use it for the source file name
  13199. const fileName = this.id;
  13200. this.magicString = new MagicString(code, {
  13201. filename: (this.excludeFromSourcemap ? null : fileName), // don't include plugin helpers in sourcemap
  13202. indentExclusionRanges: []
  13203. });
  13204. this.astContext = {
  13205. addDynamicImport: this.addDynamicImport.bind(this),
  13206. addExport: this.addExport.bind(this),
  13207. addImport: this.addImport.bind(this),
  13208. addImportMeta: this.addImportMeta.bind(this),
  13209. code, // Only needed for debugging
  13210. deoptimizationTracker: this.graph.deoptimizationTracker,
  13211. error: this.error.bind(this),
  13212. fileName, // Needed for warnings
  13213. getExports: this.getExports.bind(this),
  13214. getModuleExecIndex: () => this.execIndex,
  13215. getModuleName: this.basename.bind(this),
  13216. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  13217. getReexports: this.getReexports.bind(this),
  13218. importDescriptions: this.importDescriptions,
  13219. includeAllExports: () => this.includeAllExports(true),
  13220. includeDynamicImport: this.includeDynamicImport.bind(this),
  13221. includeVariableInModule: this.includeVariableInModule.bind(this),
  13222. log: this.log.bind(this),
  13223. magicString: this.magicString,
  13224. manualPureFunctions: this.graph.pureFunctions,
  13225. module: this,
  13226. moduleContext: this.context,
  13227. options: this.options,
  13228. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  13229. traceExport: (name) => this.getVariableForExportName(name)[0],
  13230. traceVariable: this.traceVariable.bind(this),
  13231. usesTopLevelAwait: false
  13232. };
  13233. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  13234. this.namespace = new NamespaceVariable(this.astContext);
  13235. const programParent = { context: this.astContext, type: 'Module' };
  13236. if (ast) {
  13237. this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
  13238. this.info.ast = ast;
  13239. }
  13240. else {
  13241. // Measuring asynchronous code does not provide reasonable results
  13242. timeEnd('generate ast', 3);
  13243. const astBuffer = await parseAsync(code, false);
  13244. timeStart('generate ast', 3);
  13245. this.ast = convertProgram(astBuffer, programParent, this.scope);
  13246. // Make lazy and apply LRU cache to not hog the memory
  13247. Object.defineProperty(this.info, 'ast', {
  13248. get: () => {
  13249. if (this.graph.astLru.has(fileName)) {
  13250. return this.graph.astLru.get(fileName);
  13251. }
  13252. else {
  13253. const parsedAst = this.tryParse();
  13254. // If the cache is not disabled, we need to keep the AST in memory
  13255. // until the end when the cache is generated
  13256. if (this.options.cache !== false) {
  13257. Object.defineProperty(this.info, 'ast', {
  13258. value: parsedAst
  13259. });
  13260. return parsedAst;
  13261. }
  13262. // Otherwise, we keep it in a small LRU cache to not hog too much
  13263. // memory but allow the same AST to be requested several times.
  13264. this.graph.astLru.set(fileName, parsedAst);
  13265. return parsedAst;
  13266. }
  13267. }
  13268. });
  13269. }
  13270. timeEnd('generate ast', 3);
  13271. }
  13272. toJSON() {
  13273. return {
  13274. ast: this.info.ast,
  13275. attributes: this.info.attributes,
  13276. code: this.info.code,
  13277. customTransformCache: this.customTransformCache,
  13278. // eslint-disable-next-line unicorn/prefer-spread
  13279. dependencies: Array.from(this.dependencies, getId),
  13280. id: this.id,
  13281. meta: this.info.meta,
  13282. moduleSideEffects: this.info.moduleSideEffects,
  13283. originalCode: this.originalCode,
  13284. originalSourcemap: this.originalSourcemap,
  13285. resolvedIds: this.resolvedIds,
  13286. sourcemapChain: this.sourcemapChain,
  13287. syntheticNamedExports: this.info.syntheticNamedExports,
  13288. transformDependencies: this.transformDependencies,
  13289. transformFiles: this.transformFiles
  13290. };
  13291. }
  13292. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  13293. const localVariable = this.scope.variables.get(name);
  13294. if (localVariable) {
  13295. return localVariable;
  13296. }
  13297. const importDescription = this.importDescriptions.get(name);
  13298. if (importDescription) {
  13299. const otherModule = importDescription.module;
  13300. if (otherModule instanceof Module && importDescription.name === '*') {
  13301. return otherModule.namespace;
  13302. }
  13303. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  13304. if (!declaration) {
  13305. return this.error(logMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  13306. }
  13307. return declaration;
  13308. }
  13309. return null;
  13310. }
  13311. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  13312. if (moduleSideEffects != null) {
  13313. this.info.moduleSideEffects = moduleSideEffects;
  13314. }
  13315. if (syntheticNamedExports != null) {
  13316. this.info.syntheticNamedExports = syntheticNamedExports;
  13317. }
  13318. if (meta != null) {
  13319. Object.assign(this.info.meta, meta);
  13320. }
  13321. }
  13322. addDynamicImport(node) {
  13323. let argument = node.sourceAstNode;
  13324. if (argument.type === TemplateLiteral$1) {
  13325. if (argument.quasis.length === 1 &&
  13326. typeof argument.quasis[0].value.cooked === 'string') {
  13327. argument = argument.quasis[0].value.cooked;
  13328. }
  13329. }
  13330. else if (argument.type === Literal$1 &&
  13331. typeof argument.value === 'string') {
  13332. argument = argument.value;
  13333. }
  13334. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  13335. }
  13336. assertUniqueExportName(name, nodeStart) {
  13337. if (this.exports.has(name) || this.reexportDescriptions.has(name)) {
  13338. this.error(logDuplicateExportError(name), nodeStart);
  13339. }
  13340. }
  13341. addExport(node) {
  13342. if (node instanceof ExportDefaultDeclaration) {
  13343. // export default foo;
  13344. this.assertUniqueExportName('default', node.start);
  13345. this.exports.set('default', {
  13346. identifier: node.variable.getAssignedVariableName(),
  13347. localName: 'default'
  13348. });
  13349. }
  13350. else if (node instanceof ExportAllDeclaration) {
  13351. const source = node.source.value;
  13352. this.addSource(source, node);
  13353. if (node.exported) {
  13354. // export * as name from './other'
  13355. const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
  13356. this.assertUniqueExportName(name, node.exported.start);
  13357. this.reexportDescriptions.set(name, {
  13358. localName: '*',
  13359. module: null, // filled in later,
  13360. source,
  13361. start: node.start
  13362. });
  13363. }
  13364. else {
  13365. // export * from './other'
  13366. this.exportAllSources.add(source);
  13367. }
  13368. }
  13369. else if (node.source instanceof Literal) {
  13370. // export { name } from './other'
  13371. const source = node.source.value;
  13372. this.addSource(source, node);
  13373. for (const { exported, local, start } of node.specifiers) {
  13374. const name = exported instanceof Literal ? exported.value : exported.name;
  13375. this.assertUniqueExportName(name, start);
  13376. this.reexportDescriptions.set(name, {
  13377. localName: local instanceof Literal ? local.value : local.name,
  13378. module: null, // filled in later,
  13379. source,
  13380. start
  13381. });
  13382. }
  13383. }
  13384. else if (node.declaration) {
  13385. const declaration = node.declaration;
  13386. if (declaration instanceof VariableDeclaration) {
  13387. // export var { foo, bar } = ...
  13388. // export var foo = 1, bar = 2;
  13389. for (const declarator of declaration.declarations) {
  13390. for (const localName of extractAssignedNames(declarator.id)) {
  13391. this.assertUniqueExportName(localName, declarator.id.start);
  13392. this.exports.set(localName, { identifier: null, localName });
  13393. }
  13394. }
  13395. }
  13396. else {
  13397. // export function foo () {}
  13398. const localName = declaration.id.name;
  13399. this.assertUniqueExportName(localName, declaration.id.start);
  13400. this.exports.set(localName, { identifier: null, localName });
  13401. }
  13402. }
  13403. else {
  13404. // export { foo, bar, baz }
  13405. for (const { local, exported } of node.specifiers) {
  13406. // except for reexports, local must be an Identifier
  13407. const localName = local.name;
  13408. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  13409. this.assertUniqueExportName(exportedName, exported.start);
  13410. this.exports.set(exportedName, { identifier: null, localName });
  13411. }
  13412. }
  13413. }
  13414. addImport(node) {
  13415. const source = node.source.value;
  13416. this.addSource(source, node);
  13417. for (const specifier of node.specifiers) {
  13418. const localName = specifier.local.name;
  13419. if (this.scope.variables.has(localName) || this.importDescriptions.has(localName)) {
  13420. this.error(logRedeclarationError(localName), specifier.local.start);
  13421. }
  13422. const name = specifier instanceof ImportDefaultSpecifier
  13423. ? 'default'
  13424. : specifier instanceof ImportNamespaceSpecifier
  13425. ? '*'
  13426. : specifier.imported instanceof Identifier
  13427. ? specifier.imported.name
  13428. : specifier.imported.value;
  13429. this.importDescriptions.set(localName, {
  13430. module: null, // filled in later
  13431. name,
  13432. source,
  13433. start: specifier.start
  13434. });
  13435. }
  13436. }
  13437. addImportMeta(node) {
  13438. this.importMetas.push(node);
  13439. }
  13440. addLocationToLogProps(properties, pos) {
  13441. properties.id = this.id;
  13442. properties.pos = pos;
  13443. let code = this.info.code;
  13444. const location = locate(code, pos, { offsetLine: 1 });
  13445. if (location) {
  13446. let { column, line } = location;
  13447. try {
  13448. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  13449. code = this.originalCode;
  13450. }
  13451. catch (error_) {
  13452. this.options.onLog(LOGLEVEL_WARN, logInvalidSourcemapForError(error_, this.id, column, line, pos));
  13453. }
  13454. augmentCodeLocation(properties, { column, line }, code, this.id);
  13455. }
  13456. }
  13457. addModulesToImportDescriptions(importDescription) {
  13458. for (const specifier of importDescription.values()) {
  13459. const { id } = this.resolvedIds[specifier.source];
  13460. specifier.module = this.graph.modulesById.get(id);
  13461. }
  13462. }
  13463. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  13464. const handledDependencies = new Set();
  13465. const addSideEffectDependencies = (possibleDependencies) => {
  13466. for (const dependency of possibleDependencies) {
  13467. if (handledDependencies.has(dependency)) {
  13468. continue;
  13469. }
  13470. handledDependencies.add(dependency);
  13471. if (necessaryDependencies.has(dependency)) {
  13472. relevantDependencies.add(dependency);
  13473. continue;
  13474. }
  13475. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  13476. continue;
  13477. }
  13478. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  13479. relevantDependencies.add(dependency);
  13480. continue;
  13481. }
  13482. addSideEffectDependencies(dependency.dependencies);
  13483. }
  13484. };
  13485. addSideEffectDependencies(this.dependencies);
  13486. addSideEffectDependencies(alwaysCheckedDependencies);
  13487. }
  13488. addSource(source, declaration) {
  13489. const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
  13490. const existingAttributes = this.sourcesWithAttributes.get(source);
  13491. if (existingAttributes) {
  13492. if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
  13493. this.log(LOGLEVEL_WARN, logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
  13494. }
  13495. }
  13496. else {
  13497. this.sourcesWithAttributes.set(source, parsedAttributes);
  13498. }
  13499. }
  13500. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  13501. let foundSyntheticDeclaration = null;
  13502. const foundInternalDeclarations = new Map();
  13503. const foundExternalDeclarations = new Set();
  13504. for (const module of this.exportAllModules) {
  13505. // Synthetic namespaces should not hide "regular" exports of the same name
  13506. if (module.info.syntheticNamedExports === name) {
  13507. continue;
  13508. }
  13509. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  13510. // We are creating a copy to handle the case where the same binding is
  13511. // imported through different namespace reexports gracefully
  13512. copyNameToModulesMap(searchedNamesAndModules));
  13513. if (module instanceof ExternalModule || indirectExternal) {
  13514. foundExternalDeclarations.add(variable);
  13515. }
  13516. else if (variable instanceof SyntheticNamedExportVariable) {
  13517. if (!foundSyntheticDeclaration) {
  13518. foundSyntheticDeclaration = variable;
  13519. }
  13520. }
  13521. else if (variable) {
  13522. foundInternalDeclarations.set(variable, module);
  13523. }
  13524. }
  13525. if (foundInternalDeclarations.size > 0) {
  13526. const foundDeclarationList = [...foundInternalDeclarations];
  13527. const usedDeclaration = foundDeclarationList[0][0];
  13528. if (foundDeclarationList.length === 1) {
  13529. return [usedDeclaration];
  13530. }
  13531. this.options.onLog(LOGLEVEL_WARN, logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  13532. // TODO we are pretending it was not found while it should behave like "undefined"
  13533. return [null];
  13534. }
  13535. if (foundExternalDeclarations.size > 0) {
  13536. const foundDeclarationList = [...foundExternalDeclarations];
  13537. const usedDeclaration = foundDeclarationList[0];
  13538. if (foundDeclarationList.length > 1) {
  13539. this.options.onLog(LOGLEVEL_WARN, logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  13540. }
  13541. return [usedDeclaration, true];
  13542. }
  13543. if (foundSyntheticDeclaration) {
  13544. return [foundSyntheticDeclaration];
  13545. }
  13546. return [null];
  13547. }
  13548. includeAndGetAdditionalMergedNamespaces() {
  13549. const externalNamespaces = new Set();
  13550. const syntheticNamespaces = new Set();
  13551. for (const module of [this, ...this.exportAllModules]) {
  13552. if (module instanceof ExternalModule) {
  13553. const [externalVariable] = module.getVariableForExportName('*');
  13554. externalVariable.include();
  13555. this.includedImports.add(externalVariable);
  13556. externalNamespaces.add(externalVariable);
  13557. }
  13558. else if (module.info.syntheticNamedExports) {
  13559. const syntheticNamespace = module.getSyntheticNamespace();
  13560. syntheticNamespace.include();
  13561. this.includedImports.add(syntheticNamespace);
  13562. syntheticNamespaces.add(syntheticNamespace);
  13563. }
  13564. }
  13565. return [...syntheticNamespaces, ...externalNamespaces];
  13566. }
  13567. includeDynamicImport(node) {
  13568. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  13569. if (resolution instanceof Module) {
  13570. resolution.includedDynamicImporters.push(this);
  13571. const importedNames = this.options.treeshake
  13572. ? node.getDeterministicImportedNames()
  13573. : undefined;
  13574. if (importedNames) {
  13575. resolution.includeExportsByNames(importedNames);
  13576. }
  13577. else {
  13578. resolution.includeAllExports(true);
  13579. }
  13580. }
  13581. }
  13582. includeVariable(variable) {
  13583. const variableModule = variable.module;
  13584. if (variable.included) {
  13585. if (variableModule instanceof Module && variableModule !== this) {
  13586. getAndExtendSideEffectModules(variable, this);
  13587. }
  13588. }
  13589. else {
  13590. variable.include();
  13591. this.graph.needsTreeshakingPass = true;
  13592. if (variableModule instanceof Module) {
  13593. if (!variableModule.isExecuted) {
  13594. markModuleAndImpureDependenciesAsExecuted(variableModule);
  13595. }
  13596. if (variableModule !== this) {
  13597. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  13598. for (const module of sideEffectModules) {
  13599. if (!module.isExecuted) {
  13600. markModuleAndImpureDependenciesAsExecuted(module);
  13601. }
  13602. }
  13603. }
  13604. }
  13605. }
  13606. }
  13607. includeVariableInModule(variable) {
  13608. this.includeVariable(variable);
  13609. const variableModule = variable.module;
  13610. if (variableModule && variableModule !== this) {
  13611. this.includedImports.add(variable);
  13612. }
  13613. }
  13614. shimMissingExport(name) {
  13615. this.options.onLog(LOGLEVEL_WARN, logShimmedExport(this.id, name));
  13616. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  13617. }
  13618. tryParse() {
  13619. try {
  13620. return parseAst(this.info.code);
  13621. }
  13622. catch (error_) {
  13623. return this.error(logModuleParseError(error_, this.id), error_.pos);
  13624. }
  13625. }
  13626. }
  13627. // if there is a cyclic import in the reexport chain, we should not
  13628. // import from the original module but from the cyclic module to not
  13629. // mess up execution order.
  13630. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  13631. if (variable.module instanceof Module && variable.module !== reexporter) {
  13632. const exporterCycles = variable.module.cycles;
  13633. if (exporterCycles.size > 0) {
  13634. const importerCycles = reexporter.cycles;
  13635. for (const cycleSymbol of importerCycles) {
  13636. if (exporterCycles.has(cycleSymbol)) {
  13637. importer.alternativeReexportModules.set(variable, reexporter);
  13638. break;
  13639. }
  13640. }
  13641. }
  13642. }
  13643. }
  13644. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  13645. // eslint-disable-next-line unicorn/prefer-spread
  13646. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  13647. function removeJsExtension(name) {
  13648. return name.endsWith('.js') ? name.slice(0, -3) : name;
  13649. }
  13650. function getCompleteAmdId(options, chunkId) {
  13651. if (options.autoId) {
  13652. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  13653. }
  13654. return options.id ?? '';
  13655. }
  13656. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
  13657. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  13658. if (!namedExportsMode) {
  13659. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  13660. }
  13661. let exportBlock = '';
  13662. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13663. if (reexports && namedExportsMode) {
  13664. for (const specifier of reexports) {
  13665. if (specifier.reexported !== '*') {
  13666. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  13667. if (exportBlock)
  13668. exportBlock += n;
  13669. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  13670. const [left, right] = getDirectReturnFunction([], {
  13671. functionReturn: true,
  13672. lineBreakIndent: null,
  13673. name: null
  13674. });
  13675. exportBlock +=
  13676. `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
  13677. `${t}enumerable:${_}true,${n}` +
  13678. `${t}get:${_}${left}${importName}${right}${n}});`;
  13679. }
  13680. else if (specifier.reexported === '__proto__') {
  13681. exportBlock +=
  13682. `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  13683. `${t}enumerable:${_}true,${n}` +
  13684. `${t}value:${_}${importName}${n}});`;
  13685. }
  13686. else {
  13687. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  13688. }
  13689. }
  13690. }
  13691. }
  13692. }
  13693. for (const { exported, local } of exports) {
  13694. const lhs = `exports${getPropertyAccess(exported)}`;
  13695. const rhs = local;
  13696. if (lhs !== rhs) {
  13697. if (exportBlock)
  13698. exportBlock += n;
  13699. exportBlock +=
  13700. exported === '__proto__'
  13701. ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  13702. `${t}enumerable:${_}true,${n}` +
  13703. `${t}value:${_}${rhs}${n}});`
  13704. : `${lhs}${_}=${_}${rhs};`;
  13705. }
  13706. }
  13707. for (const { name, reexports } of dependencies) {
  13708. if (reexports && namedExportsMode) {
  13709. for (const specifier of reexports) {
  13710. if (specifier.reexported === '*') {
  13711. if (exportBlock)
  13712. exportBlock += n;
  13713. if (!specifier.needsLiveBinding && reexportProtoFromExternal) {
  13714. const protoString = "'__proto__'";
  13715. exportBlock +=
  13716. `Object.prototype.hasOwnProperty.call(${name},${_}${protoString})${_}&&${n}` +
  13717. `${t}!Object.prototype.hasOwnProperty.call(exports,${_}${protoString})${_}&&${n}` +
  13718. `${t}Object.defineProperty(exports,${_}${protoString},${_}{${n}` +
  13719. `${t}${t}enumerable:${_}true,${n}` +
  13720. `${t}${t}value:${_}${name}[${protoString}]${n}` +
  13721. `${t}});${n}${n}`;
  13722. }
  13723. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  13724. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  13725. isAsync: false,
  13726. name: null
  13727. })}${copyPropertyIfNecessary});`;
  13728. }
  13729. }
  13730. }
  13731. }
  13732. if (exportBlock) {
  13733. return `${n}${n}${exportBlock}`;
  13734. }
  13735. return '';
  13736. }
  13737. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  13738. if (exports.length > 0) {
  13739. return exports[0].local;
  13740. }
  13741. else {
  13742. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13743. if (reexports) {
  13744. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  13745. }
  13746. }
  13747. }
  13748. }
  13749. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  13750. if (imported === 'default') {
  13751. if (!isChunk) {
  13752. const moduleInterop = interop(moduleId);
  13753. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  13754. ? defaultVariableName
  13755. : moduleVariableName;
  13756. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  13757. ? `${variableName}${getPropertyAccess('default')}`
  13758. : variableName;
  13759. }
  13760. return depNamedExportsMode
  13761. ? `${moduleVariableName}${getPropertyAccess('default')}`
  13762. : moduleVariableName;
  13763. }
  13764. if (imported === '*') {
  13765. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  13766. ? namespaceVariableName
  13767. : moduleVariableName;
  13768. }
  13769. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  13770. }
  13771. function getEsModuleValue(getObject) {
  13772. return getObject([['value', 'true']], {
  13773. lineBreakIndent: null
  13774. });
  13775. }
  13776. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  13777. if (hasNamedExports) {
  13778. if (addEsModule) {
  13779. if (addNamespaceToStringTag) {
  13780. return `Object.defineProperties(exports,${_}${getObject([
  13781. ['__esModule', getEsModuleValue(getObject)],
  13782. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  13783. ], {
  13784. lineBreakIndent: null
  13785. })});`;
  13786. }
  13787. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  13788. }
  13789. if (addNamespaceToStringTag) {
  13790. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  13791. }
  13792. }
  13793. return '';
  13794. }
  13795. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  13796. if (needsLiveBinding) {
  13797. const [left, right] = getDirectReturnFunction([], {
  13798. functionReturn: true,
  13799. lineBreakIndent: null,
  13800. name: null
  13801. });
  13802. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  13803. `${t}${t}enumerable:${_}true,${n}` +
  13804. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  13805. }
  13806. return `exports[k]${_}=${_}${name}[k]`;
  13807. };
  13808. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
  13809. const { _, cnst, n } = snippets;
  13810. const neededInteropHelpers = new Set();
  13811. const interopStatements = [];
  13812. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  13813. neededInteropHelpers.add(helper);
  13814. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  13815. };
  13816. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13817. if (isChunk) {
  13818. for (const { imported, reexported } of [
  13819. ...(imports || []),
  13820. ...(reexports || [])
  13821. ]) {
  13822. if (imported === '*' && reexported !== '*') {
  13823. if (!namedExportsMode) {
  13824. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  13825. }
  13826. break;
  13827. }
  13828. }
  13829. }
  13830. else {
  13831. const moduleInterop = interop(importPath);
  13832. let hasDefault = false;
  13833. let hasNamespace = false;
  13834. for (const { imported, reexported } of [
  13835. ...(imports || []),
  13836. ...(reexports || [])
  13837. ]) {
  13838. let helper;
  13839. let variableName;
  13840. if (imported === 'default') {
  13841. if (!hasDefault) {
  13842. hasDefault = true;
  13843. if (defaultVariableName !== namespaceVariableName) {
  13844. variableName = defaultVariableName;
  13845. helper = defaultInteropHelpersByInteropType[moduleInterop];
  13846. }
  13847. }
  13848. }
  13849. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  13850. hasNamespace = true;
  13851. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  13852. variableName = namespaceVariableName;
  13853. }
  13854. if (helper) {
  13855. addInteropStatement(variableName, helper, name);
  13856. }
  13857. }
  13858. }
  13859. }
  13860. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, symbols)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  13861. }
  13862. function addJsExtension(name) {
  13863. return name.endsWith('.js') ? name : name + '.js';
  13864. }
  13865. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  13866. // The assumption is that this makes sense for all relative ids:
  13867. // https://requirejs.org/docs/api.html#jsfiles
  13868. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  13869. if (id[0] !== '.') {
  13870. return id;
  13871. }
  13872. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  13873. }
  13874. const require$$0 = [
  13875. "assert",
  13876. "async_hooks",
  13877. "buffer",
  13878. "child_process",
  13879. "cluster",
  13880. "console",
  13881. "constants",
  13882. "crypto",
  13883. "dgram",
  13884. "diagnostics_channel",
  13885. "dns",
  13886. "domain",
  13887. "events",
  13888. "fs",
  13889. "http",
  13890. "http2",
  13891. "https",
  13892. "inspector",
  13893. "module",
  13894. "net",
  13895. "os",
  13896. "path",
  13897. "perf_hooks",
  13898. "process",
  13899. "punycode",
  13900. "querystring",
  13901. "readline",
  13902. "repl",
  13903. "stream",
  13904. "string_decoder",
  13905. "timers",
  13906. "tls",
  13907. "trace_events",
  13908. "tty",
  13909. "url",
  13910. "util",
  13911. "v8",
  13912. "vm",
  13913. "wasi",
  13914. "worker_threads",
  13915. "zlib"
  13916. ];
  13917. var _static = require$$0;
  13918. const builtinModules = /*@__PURE__*/getDefaultExportFromCjs(_static);
  13919. const nodeBuiltins = new Set([
  13920. ...builtinModules,
  13921. // TODO
  13922. // remove once builtin-modules includes PR: https://github.com/sindresorhus/builtin-modules/pull/17
  13923. 'assert/strict',
  13924. 'dns/promises',
  13925. 'fs/promises',
  13926. 'path/posix',
  13927. 'path/win32',
  13928. 'readline/promises',
  13929. 'stream/consumers',
  13930. 'stream/promises',
  13931. 'stream/web',
  13932. 'timers/promises',
  13933. 'util/types'
  13934. ]);
  13935. function warnOnBuiltins(log, dependencies) {
  13936. const externalBuiltins = dependencies
  13937. .map(({ importPath }) => importPath)
  13938. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  13939. if (externalBuiltins.length === 0)
  13940. return;
  13941. log(LOGLEVEL_WARN, logMissingNodeBuiltins(externalBuiltins));
  13942. }
  13943. 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 }) {
  13944. warnOnBuiltins(log, dependencies);
  13945. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  13946. const parameters = dependencies.map(m => m.name);
  13947. const { n, getNonArrowFunctionIntro, _ } = snippets;
  13948. if (namedExportsMode && hasExports) {
  13949. parameters.unshift(`exports`);
  13950. deps.unshift(`'exports'`);
  13951. }
  13952. if (accessedGlobals.has('require')) {
  13953. parameters.unshift('require');
  13954. deps.unshift(`'require'`);
  13955. }
  13956. if (accessedGlobals.has('module')) {
  13957. parameters.unshift('module');
  13958. deps.unshift(`'module'`);
  13959. }
  13960. const completeAmdId = getCompleteAmdId(amd, id);
  13961. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  13962. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  13963. const useStrict = strict ? `${_}'use strict';` : '';
  13964. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  13965. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  13966. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  13967. if (namespaceMarkers) {
  13968. namespaceMarkers = n + n + namespaceMarkers;
  13969. }
  13970. magicString
  13971. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  13972. .indent(t)
  13973. // factory function should be wrapped by parentheses to avoid lazy parsing,
  13974. // cf. https://v8.dev/blog/preparser#pife
  13975. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  13976. isAsync: false,
  13977. name: null
  13978. })}{${useStrict}${n}${n}`)
  13979. .append(`${n}${n}}));`);
  13980. }
  13981. 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 }) {
  13982. const { _, n } = snippets;
  13983. const useStrict = strict ? `'use strict';${n}${n}` : '';
  13984. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  13985. if (namespaceMarkers) {
  13986. namespaceMarkers += n + n;
  13987. }
  13988. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  13989. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  13990. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  13991. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, `module.exports${_}=${_}`);
  13992. magicString.append(`${exportBlock}${outro}`);
  13993. }
  13994. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  13995. let importBlock = '';
  13996. let definingVariable = false;
  13997. for (const { importPath, name, reexports, imports } of dependencies) {
  13998. if (!reexports && !imports) {
  13999. if (importBlock) {
  14000. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  14001. }
  14002. definingVariable = false;
  14003. importBlock += `require('${importPath}')`;
  14004. }
  14005. else {
  14006. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  14007. definingVariable = true;
  14008. importBlock += `${name}${_}=${_}require('${importPath}')`;
  14009. }
  14010. }
  14011. if (importBlock) {
  14012. return `${importBlock};${n}${n}`;
  14013. }
  14014. return '';
  14015. }
  14016. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, generatedCode: { symbols }, importAttributesKey }) {
  14017. const { n } = snippets;
  14018. const importBlock = getImportBlock(dependencies, importAttributesKey, snippets);
  14019. if (importBlock.length > 0)
  14020. intro += importBlock.join(n) + n + n;
  14021. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols);
  14022. if (intro)
  14023. magicString.prepend(intro);
  14024. const exportBlock = getExportBlock(exports, snippets);
  14025. if (exportBlock.length > 0)
  14026. magicString.append(n + n + exportBlock.join(n).trim());
  14027. if (outro)
  14028. magicString.append(outro);
  14029. magicString.trim();
  14030. }
  14031. function getImportBlock(dependencies, importAttributesKey, { _ }) {
  14032. const importBlock = [];
  14033. for (const { importPath, reexports, imports, name, attributes } of dependencies) {
  14034. const assertion = attributes ? `${_}${importAttributesKey}${_}${attributes}` : '';
  14035. const pathWithAssertion = `'${importPath}'${assertion};`;
  14036. if (!reexports && !imports) {
  14037. importBlock.push(`import${_}${pathWithAssertion}`);
  14038. continue;
  14039. }
  14040. if (imports) {
  14041. let defaultImport = null;
  14042. let starImport = null;
  14043. const importedNames = [];
  14044. for (const specifier of imports) {
  14045. if (specifier.imported === 'default') {
  14046. defaultImport = specifier;
  14047. }
  14048. else if (specifier.imported === '*') {
  14049. starImport = specifier;
  14050. }
  14051. else {
  14052. importedNames.push(specifier);
  14053. }
  14054. }
  14055. if (starImport) {
  14056. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  14057. }
  14058. if (defaultImport && importedNames.length === 0) {
  14059. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  14060. }
  14061. else if (importedNames.length > 0) {
  14062. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  14063. .map(specifier => specifier.imported === specifier.local
  14064. ? specifier.imported
  14065. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${specifier.local}`)
  14066. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  14067. }
  14068. }
  14069. if (reexports) {
  14070. let starExport = null;
  14071. const namespaceReexports = [];
  14072. const namedReexports = [];
  14073. for (const specifier of reexports) {
  14074. if (specifier.reexported === '*') {
  14075. starExport = specifier;
  14076. }
  14077. else if (specifier.imported === '*') {
  14078. namespaceReexports.push(specifier);
  14079. }
  14080. else {
  14081. namedReexports.push(specifier);
  14082. }
  14083. }
  14084. if (starExport) {
  14085. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  14086. }
  14087. if (namespaceReexports.length > 0) {
  14088. if (!imports ||
  14089. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  14090. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  14091. }
  14092. for (const specifier of namespaceReexports) {
  14093. importBlock.push(`export${_}{${_}${name === specifier.reexported
  14094. ? name
  14095. : `${name} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`} };`);
  14096. }
  14097. }
  14098. if (namedReexports.length > 0) {
  14099. importBlock.push(`export${_}{${_}${namedReexports
  14100. .map(specifier => specifier.imported === specifier.reexported
  14101. ? stringifyIdentifierIfNeeded(specifier.imported)
  14102. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`)
  14103. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  14104. }
  14105. }
  14106. }
  14107. return importBlock;
  14108. }
  14109. function getExportBlock(exports, { _, cnst }) {
  14110. const exportBlock = [];
  14111. const exportDeclaration = [];
  14112. for (const specifier of exports) {
  14113. if (specifier.expression) {
  14114. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  14115. }
  14116. exportDeclaration.push(specifier.exported === specifier.local
  14117. ? specifier.local
  14118. : `${specifier.local} as ${stringifyIdentifierIfNeeded(specifier.exported)}`);
  14119. }
  14120. if (exportDeclaration.length > 0) {
  14121. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  14122. }
  14123. return exportBlock;
  14124. }
  14125. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  14126. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
  14127. const parts = name.split('.');
  14128. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  14129. parts.pop();
  14130. let propertyPath = root;
  14131. return (parts
  14132. .map(part => {
  14133. propertyPath += getPropertyAccess(part);
  14134. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  14135. })
  14136. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  14137. }
  14138. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
  14139. const parts = deepName.split('.');
  14140. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  14141. const last = parts.pop();
  14142. let propertyPath = root;
  14143. let deepAssignment = [
  14144. ...parts.map(part => {
  14145. propertyPath += getPropertyAccess(part);
  14146. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  14147. }),
  14148. `${propertyPath}${getPropertyAccess(last)}`
  14149. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  14150. if (parts.length > 0) {
  14151. deepAssignment = `(${deepAssignment})`;
  14152. }
  14153. return deepAssignment;
  14154. }
  14155. function trimEmptyImports(dependencies) {
  14156. let index = dependencies.length;
  14157. while (index--) {
  14158. const { imports, reexports } = dependencies[index];
  14159. if (imports || reexports) {
  14160. return dependencies.slice(0, index + 1);
  14161. }
  14162. }
  14163. return [];
  14164. }
  14165. 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 }) {
  14166. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  14167. const isNamespaced = name && name.includes('.');
  14168. const useVariableAssignment = !extend && !isNamespaced;
  14169. if (name && useVariableAssignment && !isLegal(name)) {
  14170. return error(logIllegalIdentifierAsName(name));
  14171. }
  14172. warnOnBuiltins(log, dependencies);
  14173. const external = trimEmptyImports(dependencies);
  14174. const deps = external.map(dep => dep.globalName || 'null');
  14175. const parameters = external.map(m => m.name);
  14176. if (hasExports && !name) {
  14177. log(LOGLEVEL_WARN, logMissingNameOptionForIifeExport());
  14178. }
  14179. if (namedExportsMode && hasExports) {
  14180. if (extend) {
  14181. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  14182. parameters.unshift('exports');
  14183. }
  14184. else {
  14185. deps.unshift('{}');
  14186. parameters.unshift('exports');
  14187. }
  14188. }
  14189. const useStrict = strict ? `${t}'use strict';${n}` : '';
  14190. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  14191. magicString.prepend(`${intro}${interopBlock}`);
  14192. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  14193. isAsync: false,
  14194. name: null
  14195. })}{${n}${useStrict}${n}`;
  14196. if (hasExports) {
  14197. if (name && !(extend && namedExportsMode)) {
  14198. wrapperIntro =
  14199. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  14200. `${_}=${_}${wrapperIntro}`;
  14201. }
  14202. if (isNamespaced) {
  14203. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
  14204. }
  14205. }
  14206. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  14207. if (hasExports && !extend && namedExportsMode) {
  14208. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  14209. }
  14210. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  14211. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  14212. if (namespaceMarkers) {
  14213. namespaceMarkers = n + n + namespaceMarkers;
  14214. }
  14215. magicString
  14216. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  14217. .indent(t)
  14218. .prepend(wrapperIntro)
  14219. .append(wrapperOutro);
  14220. }
  14221. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, generatedCode: { symbols }, strict, systemNullSetters }) {
  14222. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  14223. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  14224. const registeredName = name ? `'${name}',${_}` : '';
  14225. const wrapperParameters = accessedGlobals.has('module')
  14226. ? ['exports', 'module']
  14227. : hasExports
  14228. ? ['exports']
  14229. : [];
  14230. // factory function should be wrapped by parentheses to avoid lazy parsing,
  14231. // cf. https://v8.dev/blog/preparser#pife
  14232. let wrapperStart = `System.register(${registeredName}[` +
  14233. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  14234. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  14235. isAsync: false,
  14236. name: null
  14237. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  14238. getStarExcludesBlock(starExcludes, t, snippets) +
  14239. getImportBindingsBlock(importBindings, t, snippets) +
  14240. `${n}${t}return${_}{${setters.length > 0
  14241. ? `${n}${t}${t}setters:${_}[${setters
  14242. .map(setter => setter
  14243. ? `${getFunctionIntro(['module'], {
  14244. isAsync: false,
  14245. name: null
  14246. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  14247. : systemNullSetters
  14248. ? `null`
  14249. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  14250. .join(`,${_}`)}],`
  14251. : ''}${n}`;
  14252. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  14253. isAsync: usesTopLevelAwait,
  14254. name: null
  14255. })}{${n}${n}`;
  14256. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  14257. magicString
  14258. .prepend(intro +
  14259. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols) +
  14260. getHoistedExportsBlock(exports, t, snippets))
  14261. .append(`${outro}${n}${n}` +
  14262. getSyntheticExportsBlock(exports, t, snippets) +
  14263. getMissingExportsBlock(exports, t, snippets))
  14264. .indent(`${t}${t}${t}`)
  14265. .append(wrapperEnd)
  14266. .prepend(wrapperStart);
  14267. }
  14268. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  14269. const importBindings = [];
  14270. const setters = [];
  14271. let starExcludes = null;
  14272. for (const { imports, reexports } of dependencies) {
  14273. const setter = [];
  14274. if (imports) {
  14275. for (const specifier of imports) {
  14276. importBindings.push(specifier.local);
  14277. if (specifier.imported === '*') {
  14278. setter.push(`${specifier.local}${_}=${_}module;`);
  14279. }
  14280. else {
  14281. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  14282. }
  14283. }
  14284. }
  14285. if (reexports) {
  14286. const reexportedNames = [];
  14287. let hasStarReexport = false;
  14288. for (const { imported, reexported } of reexports) {
  14289. if (reexported === '*') {
  14290. hasStarReexport = true;
  14291. }
  14292. else {
  14293. reexportedNames.push([
  14294. reexported,
  14295. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  14296. ]);
  14297. }
  14298. }
  14299. if (reexportedNames.length > 1 || hasStarReexport) {
  14300. if (hasStarReexport) {
  14301. if (!starExcludes) {
  14302. starExcludes = getStarExcludes({ dependencies, exports });
  14303. }
  14304. reexportedNames.unshift([null, `__proto__:${_}null`]);
  14305. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  14306. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  14307. }
  14308. else {
  14309. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  14310. setter.push(`exports(${exportMapping});`);
  14311. }
  14312. }
  14313. else {
  14314. const [key, value] = reexportedNames[0];
  14315. setter.push(`exports(${JSON.stringify(key)},${_}${value});`);
  14316. }
  14317. }
  14318. setters.push(setter.join(`${n}${t}${t}${t}`));
  14319. }
  14320. return { importBindings, setters, starExcludes };
  14321. }
  14322. const getStarExcludes = ({ dependencies, exports }) => {
  14323. const starExcludes = new Set(exports.map(expt => expt.exported));
  14324. starExcludes.add('default');
  14325. for (const { reexports } of dependencies) {
  14326. if (reexports) {
  14327. for (const reexport of reexports) {
  14328. if (reexport.reexported !== '*')
  14329. starExcludes.add(reexport.reexported);
  14330. }
  14331. }
  14332. }
  14333. return starExcludes;
  14334. };
  14335. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => {
  14336. if (starExcludes) {
  14337. const fields = [...starExcludes].map(property => [
  14338. property,
  14339. '1'
  14340. ]);
  14341. fields.unshift([null, `__proto__:${_}null`]);
  14342. return `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(fields, {
  14343. lineBreakIndent: { base: t, t }
  14344. })};`;
  14345. }
  14346. return '';
  14347. };
  14348. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  14349. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  14350. function getExportsBlock(exports, t, { _, n }) {
  14351. if (exports.length === 0) {
  14352. return '';
  14353. }
  14354. if (exports.length === 1) {
  14355. return `exports(${JSON.stringify(exports[0].name)},${_}${exports[0].value});${n}${n}`;
  14356. }
  14357. return (`exports({${n}` +
  14358. exports
  14359. .map(({ name, value }) => `${t}${stringifyObjectKeyIfNeeded(name)}:${_}${value}`)
  14360. .join(`,${n}`) +
  14361. `${n}});${n}${n}`);
  14362. }
  14363. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  14364. .filter(expt => expt.expression)
  14365. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  14366. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  14367. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  14368. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  14369. function globalProperty(name, globalVariable, getPropertyAccess) {
  14370. if (!name)
  14371. return 'null';
  14372. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  14373. }
  14374. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  14375. let propertyPath = globalVariable;
  14376. return name
  14377. .split('.')
  14378. .map(part => (propertyPath += getPropertyAccess(part)))
  14379. .join(`${_}&&${_}`);
  14380. }
  14381. 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 }) {
  14382. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  14383. const factoryVariable = compact ? 'f' : 'factory';
  14384. const globalVariable = compact ? 'g' : 'global';
  14385. if (hasExports && !name) {
  14386. return error(logMissingNameOptionForUmdExport());
  14387. }
  14388. warnOnBuiltins(log, dependencies);
  14389. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  14390. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  14391. const trimmedImports = trimEmptyImports(dependencies);
  14392. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  14393. const factoryParameters = trimmedImports.map(m => m.name);
  14394. if (namedExportsMode && (hasExports || noConflict)) {
  14395. amdDeps.unshift(`'exports'`);
  14396. cjsDeps.unshift(`exports`);
  14397. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
  14398. factoryParameters.unshift('exports');
  14399. }
  14400. const completeAmdId = getCompleteAmdId(amd, id);
  14401. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  14402. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  14403. const define = amd.define;
  14404. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  14405. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  14406. let iifeExport;
  14407. if (noConflict) {
  14408. const noConflictExportsVariable = compact ? 'e' : 'exports';
  14409. let factory;
  14410. if (!namedExportsMode && hasExports) {
  14411. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets)};`;
  14412. }
  14413. else {
  14414. const module = globalDeps.shift();
  14415. factory =
  14416. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  14417. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  14418. }
  14419. iifeExport =
  14420. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  14421. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  14422. `${t}${t}${factory}${n}` +
  14423. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  14424. isAsync: false,
  14425. name: null
  14426. })}{${_}` +
  14427. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  14428. `${t}})()`;
  14429. }
  14430. else {
  14431. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  14432. if (!namedExportsMode && hasExports) {
  14433. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets);
  14434. }
  14435. }
  14436. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  14437. const wrapperParameters = [factoryVariable];
  14438. if (iifeNeedsGlobal) {
  14439. wrapperParameters.unshift(globalVariable);
  14440. }
  14441. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  14442. const iifeStart = iifeNeedsGlobal
  14443. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  14444. : '';
  14445. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  14446. const cjsIntro = iifeNeedsGlobal
  14447. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  14448. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  14449. : '';
  14450. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  14451. cjsIntro +
  14452. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  14453. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  14454. // factory function should be wrapped by parentheses to avoid lazy parsing,
  14455. // cf. https://v8.dev/blog/preparser#pife
  14456. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  14457. isAsync: false,
  14458. name: null
  14459. })}{${useStrict}${n}`;
  14460. const wrapperOutro = n + n + '}));';
  14461. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  14462. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  14463. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  14464. if (namespaceMarkers) {
  14465. namespaceMarkers = n + n + namespaceMarkers;
  14466. }
  14467. magicString
  14468. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  14469. .trim()
  14470. .indent(t)
  14471. .append(wrapperOutro)
  14472. .prepend(wrapperIntro);
  14473. }
  14474. const finalisers = { amd, cjs, es, iife, system, umd };
  14475. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  14476. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  14477. async function createAddons(options, outputPluginDriver, chunk) {
  14478. try {
  14479. let [banner, footer, intro, outro] = await Promise.all([
  14480. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  14481. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  14482. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  14483. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  14484. ]);
  14485. if (intro)
  14486. intro += '\n\n';
  14487. if (outro)
  14488. outro = `\n\n${outro}`;
  14489. if (banner)
  14490. banner += '\n';
  14491. if (footer)
  14492. footer = '\n' + footer;
  14493. return { banner, footer, intro, outro };
  14494. }
  14495. catch (error_) {
  14496. return error(logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  14497. }
  14498. }
  14499. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  14500. amd: deconflictImportsOther,
  14501. cjs: deconflictImportsOther,
  14502. es: deconflictImportsEsmOrSystem,
  14503. iife: deconflictImportsOther,
  14504. system: deconflictImportsEsmOrSystem,
  14505. umd: deconflictImportsOther
  14506. };
  14507. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  14508. const reversedModules = [...modules].reverse();
  14509. for (const module of reversedModules) {
  14510. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  14511. }
  14512. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  14513. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  14514. for (const module of reversedModules) {
  14515. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  14516. }
  14517. }
  14518. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  14519. // This is needed for namespace reexports
  14520. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  14521. if (preserveModules || dependency instanceof ExternalChunk) {
  14522. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  14523. }
  14524. }
  14525. for (const variable of imports) {
  14526. const module = variable.module;
  14527. const name = variable.name;
  14528. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  14529. variable.setRenderNames(null, (module instanceof ExternalModule
  14530. ? externalChunkByModule.get(module)
  14531. : chunkByModule.get(module)).variableName);
  14532. }
  14533. else if (module instanceof ExternalModule && name === 'default') {
  14534. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  14535. ? module.suggestedVariableName + '__default'
  14536. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  14537. }
  14538. else {
  14539. variable.setRenderNames(null, getSafeName(makeLegal(name), usedNames, variable.forbiddenNames));
  14540. }
  14541. }
  14542. for (const variable of syntheticExports) {
  14543. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  14544. }
  14545. }
  14546. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  14547. for (const chunk of dependencies) {
  14548. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  14549. }
  14550. for (const chunk of deconflictedNamespace) {
  14551. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  14552. }
  14553. for (const externalModule of deconflictedDefault) {
  14554. externalModule.defaultVariableName =
  14555. deconflictedNamespace.has(externalModule) &&
  14556. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  14557. ? externalModule.namespaceVariableName
  14558. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  14559. }
  14560. for (const variable of imports) {
  14561. const module = variable.module;
  14562. if (module instanceof ExternalModule) {
  14563. const chunk = externalChunkByModule.get(module);
  14564. const name = variable.name;
  14565. if (name === 'default') {
  14566. const moduleInterop = interop(module.id);
  14567. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  14568. ? chunk.defaultVariableName
  14569. : chunk.variableName;
  14570. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  14571. variable.setRenderNames(variableName, 'default');
  14572. }
  14573. else {
  14574. variable.setRenderNames(null, variableName);
  14575. }
  14576. }
  14577. else if (name === '*') {
  14578. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  14579. ? chunk.namespaceVariableName
  14580. : chunk.variableName);
  14581. }
  14582. else {
  14583. // if the second parameter is `null`, it uses its "name" for the property name
  14584. variable.setRenderNames(chunk.variableName, null);
  14585. }
  14586. }
  14587. else {
  14588. const chunk = chunkByModule.get(module);
  14589. if (preserveModules && variable.isNamespace) {
  14590. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  14591. }
  14592. else if (chunk.exportMode === 'default') {
  14593. variable.setRenderNames(null, chunk.variableName);
  14594. }
  14595. else {
  14596. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  14597. }
  14598. }
  14599. }
  14600. }
  14601. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  14602. for (const module of modules) {
  14603. for (const variable of module.scope.variables.values()) {
  14604. if (variable.included &&
  14605. // this will only happen for exports in some formats
  14606. !(variable.renderBaseName ||
  14607. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  14608. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  14609. }
  14610. }
  14611. if (includedNamespaces.has(module)) {
  14612. const namespace = module.namespace;
  14613. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  14614. }
  14615. }
  14616. }
  14617. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  14618. let nameIndex = 0;
  14619. for (const variable of exports) {
  14620. let [exportName] = variable.name;
  14621. if (exportsByName.has(exportName)) {
  14622. do {
  14623. exportName = toBase64(++nameIndex);
  14624. // skip past leading number identifiers
  14625. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  14626. nameIndex += 9 * 64 ** (exportName.length - 1);
  14627. exportName = toBase64(nameIndex);
  14628. }
  14629. } while (RESERVED_NAMES.has(exportName) || exportsByName.has(exportName));
  14630. }
  14631. exportsByName.set(exportName, variable);
  14632. exportNamesByVariable.set(variable, [exportName]);
  14633. }
  14634. }
  14635. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  14636. for (const variable of exports) {
  14637. let nameIndex = 0;
  14638. let exportName = variable.name;
  14639. while (exportsByName.has(exportName)) {
  14640. exportName = variable.name + '$' + ++nameIndex;
  14641. }
  14642. exportsByName.set(exportName, variable);
  14643. exportNamesByVariable.set(variable, [exportName]);
  14644. }
  14645. }
  14646. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  14647. const exportKeys = chunk.getExportNames();
  14648. if (exportMode === 'default') {
  14649. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  14650. return error(logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  14651. }
  14652. }
  14653. else if (exportMode === 'none' && exportKeys.length > 0) {
  14654. return error(logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  14655. }
  14656. if (exportMode === 'auto') {
  14657. if (exportKeys.length === 0) {
  14658. exportMode = 'none';
  14659. }
  14660. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  14661. exportMode = 'default';
  14662. }
  14663. else {
  14664. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  14665. log(LOGLEVEL_WARN, logMixedExport(facadeModuleId, name));
  14666. }
  14667. exportMode = 'named';
  14668. }
  14669. }
  14670. return exportMode;
  14671. }
  14672. function guessIndentString(code) {
  14673. const lines = code.split('\n');
  14674. const tabbed = lines.filter(line => /^\t+/.test(line));
  14675. const spaced = lines.filter(line => /^ {2,}/.test(line));
  14676. if (tabbed.length === 0 && spaced.length === 0) {
  14677. return null;
  14678. }
  14679. // More lines tabbed than spaced? Assume tabs, and
  14680. // default to tabs in the case of a tie (or nothing
  14681. // to go on)
  14682. if (tabbed.length >= spaced.length) {
  14683. return '\t';
  14684. }
  14685. // Otherwise, we need to guess the multiple
  14686. const min = spaced.reduce((previous, current) => {
  14687. const numberSpaces = /^ +/.exec(current)[0].length;
  14688. return Math.min(numberSpaces, previous);
  14689. }, Infinity);
  14690. return ' '.repeat(min);
  14691. }
  14692. function getIndentString(modules, options) {
  14693. if (options.indent !== true)
  14694. return options.indent;
  14695. for (const module of modules) {
  14696. const indent = guessIndentString(module.originalCode);
  14697. if (indent !== null)
  14698. return indent;
  14699. }
  14700. return '\t';
  14701. }
  14702. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  14703. const staticDependencyBlocks = [];
  14704. const handledDependencies = new Set();
  14705. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  14706. const module = orderedModules[modulePos];
  14707. if (!handledDependencies.has(module)) {
  14708. const staticDependencies = [];
  14709. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  14710. staticDependencyBlocks.unshift(staticDependencies);
  14711. }
  14712. }
  14713. const dependencies = new Set();
  14714. for (const block of staticDependencyBlocks) {
  14715. for (const dependency of block) {
  14716. dependencies.add(dependency);
  14717. }
  14718. }
  14719. return dependencies;
  14720. }
  14721. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  14722. const dependencies = module.getDependenciesToBeIncluded();
  14723. for (const dependency of dependencies) {
  14724. if (dependency instanceof ExternalModule) {
  14725. staticDependencies.push(externalChunkByModule.get(dependency));
  14726. continue;
  14727. }
  14728. const dependencyChunk = chunkByModule.get(dependency);
  14729. if (dependencyChunk !== chunk) {
  14730. staticDependencies.push(dependencyChunk);
  14731. continue;
  14732. }
  14733. if (!handledModules.has(dependency)) {
  14734. handledModules.add(dependency);
  14735. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  14736. }
  14737. }
  14738. }
  14739. // Four random characters from the private use area to minimize risk of
  14740. // conflicts
  14741. const hashPlaceholderLeft = '!~{';
  14742. const hashPlaceholderRight = '}~';
  14743. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  14744. // This is the size of a 128-bits xxhash with base64url encoding
  14745. const MAX_HASH_SIZE = 22;
  14746. const DEFAULT_HASH_SIZE = 8;
  14747. const getHashPlaceholderGenerator = () => {
  14748. let nextIndex = 0;
  14749. return (optionName, hashSize) => {
  14750. if (hashSize > MAX_HASH_SIZE) {
  14751. return error(logFailedValidation(`Hashes cannot be longer than ${MAX_HASH_SIZE} characters, received ${hashSize}. Check the "${optionName}" option.`));
  14752. }
  14753. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  14754. if (placeholder.length > hashSize) {
  14755. 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.`));
  14756. }
  14757. return placeholder;
  14758. };
  14759. };
  14760. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${MAX_HASH_SIZE - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  14761. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  14762. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  14763. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  14764. const containedPlaceholders = new Set();
  14765. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  14766. if (placeholders.has(placeholder)) {
  14767. containedPlaceholders.add(placeholder);
  14768. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  14769. }
  14770. return placeholder;
  14771. });
  14772. return { containedPlaceholders, transformedCode };
  14773. };
  14774. const lowercaseBundleKeys = Symbol('bundleKeys');
  14775. const FILE_PLACEHOLDER = {
  14776. type: 'placeholder'
  14777. };
  14778. const getOutputBundle = (outputBundleBase) => {
  14779. const reservedLowercaseBundleKeys = new Set();
  14780. return new Proxy(outputBundleBase, {
  14781. deleteProperty(target, key) {
  14782. if (typeof key === 'string') {
  14783. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  14784. }
  14785. return Reflect.deleteProperty(target, key);
  14786. },
  14787. get(target, key) {
  14788. if (key === lowercaseBundleKeys) {
  14789. return reservedLowercaseBundleKeys;
  14790. }
  14791. return Reflect.get(target, key);
  14792. },
  14793. set(target, key, value) {
  14794. if (typeof key === 'string') {
  14795. reservedLowercaseBundleKeys.add(key.toLowerCase());
  14796. }
  14797. return Reflect.set(target, key, value);
  14798. }
  14799. });
  14800. };
  14801. const removeUnreferencedAssets = (outputBundle) => {
  14802. const unreferencedAssets = new Set();
  14803. const bundleEntries = Object.values(outputBundle);
  14804. for (const asset of bundleEntries) {
  14805. asset.type === 'asset' && asset.needsCodeReference && unreferencedAssets.add(asset.fileName);
  14806. }
  14807. for (const chunk of bundleEntries) {
  14808. if (chunk.type === 'chunk') {
  14809. for (const referencedFile of chunk.referencedFiles) {
  14810. unreferencedAssets.has(referencedFile) && unreferencedAssets.delete(referencedFile);
  14811. }
  14812. }
  14813. }
  14814. for (const file of unreferencedAssets) {
  14815. delete outputBundle[file];
  14816. }
  14817. };
  14818. function renderNamePattern(pattern, patternName, replacements) {
  14819. if (isPathFragment(pattern))
  14820. 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.`));
  14821. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  14822. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  14823. return error(logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  14824. }
  14825. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  14826. if (isPathFragment(replacement))
  14827. return error(logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  14828. return replacement;
  14829. });
  14830. }
  14831. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  14832. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  14833. return name;
  14834. const extension = extname(name);
  14835. name = name.slice(0, Math.max(0, name.length - extension.length));
  14836. let uniqueName, uniqueIndex = 1;
  14837. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  14838. ;
  14839. return uniqueName;
  14840. }
  14841. const NON_ASSET_EXTENSIONS = new Set([
  14842. '.js',
  14843. '.jsx',
  14844. '.ts',
  14845. '.tsx',
  14846. '.mjs',
  14847. '.mts',
  14848. '.cjs',
  14849. '.cts'
  14850. ]);
  14851. function getGlobalName(chunk, globals, hasExports, log) {
  14852. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  14853. if (globalName) {
  14854. return globalName;
  14855. }
  14856. if (hasExports) {
  14857. log(LOGLEVEL_WARN, logMissingGlobalName(chunk.id, chunk.variableName));
  14858. return chunk.variableName;
  14859. }
  14860. }
  14861. class Chunk {
  14862. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  14863. this.orderedModules = orderedModules;
  14864. this.inputOptions = inputOptions;
  14865. this.outputOptions = outputOptions;
  14866. this.unsetOptions = unsetOptions;
  14867. this.pluginDriver = pluginDriver;
  14868. this.modulesById = modulesById;
  14869. this.chunkByModule = chunkByModule;
  14870. this.externalChunkByModule = externalChunkByModule;
  14871. this.facadeChunkByModule = facadeChunkByModule;
  14872. this.includedNamespaces = includedNamespaces;
  14873. this.manualChunkAlias = manualChunkAlias;
  14874. this.getPlaceholder = getPlaceholder;
  14875. this.bundle = bundle;
  14876. this.inputBase = inputBase;
  14877. this.snippets = snippets;
  14878. this.entryModules = [];
  14879. this.exportMode = 'named';
  14880. this.facadeModule = null;
  14881. this.namespaceVariableName = '';
  14882. this.variableName = '';
  14883. this.accessedGlobalsByScope = new Map();
  14884. this.dependencies = new Set();
  14885. this.dynamicEntryModules = [];
  14886. this.dynamicName = null;
  14887. this.exportNamesByVariable = new Map();
  14888. this.exports = new Set();
  14889. this.exportsByName = new Map();
  14890. this.fileName = null;
  14891. this.implicitEntryModules = [];
  14892. this.implicitlyLoadedBefore = new Set();
  14893. this.imports = new Set();
  14894. this.includedDynamicImports = null;
  14895. this.includedReexportsByModule = new Map();
  14896. // This may be updated in the constructor
  14897. this.isEmpty = true;
  14898. this.name = null;
  14899. this.needsExportsShim = false;
  14900. this.preRenderedChunkInfo = null;
  14901. this.preliminaryFileName = null;
  14902. this.preliminarySourcemapFileName = null;
  14903. this.renderedChunkInfo = null;
  14904. this.renderedDependencies = null;
  14905. this.renderedModules = Object.create(null);
  14906. this.sortedExportNames = null;
  14907. this.strictFacade = false;
  14908. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  14909. const chunkModules = new Set(orderedModules);
  14910. for (const module of orderedModules) {
  14911. chunkByModule.set(module, this);
  14912. if (module.namespace.included && !outputOptions.preserveModules) {
  14913. includedNamespaces.add(module);
  14914. }
  14915. if (this.isEmpty && module.isIncluded()) {
  14916. this.isEmpty = false;
  14917. }
  14918. if (module.info.isEntry || outputOptions.preserveModules) {
  14919. this.entryModules.push(module);
  14920. }
  14921. for (const importer of module.includedDynamicImporters) {
  14922. if (!chunkModules.has(importer)) {
  14923. this.dynamicEntryModules.push(module);
  14924. // Modules with synthetic exports need an artificial namespace for dynamic imports
  14925. if (module.info.syntheticNamedExports) {
  14926. includedNamespaces.add(module);
  14927. this.exports.add(module.namespace);
  14928. }
  14929. }
  14930. }
  14931. if (module.implicitlyLoadedAfter.size > 0) {
  14932. this.implicitEntryModules.push(module);
  14933. }
  14934. }
  14935. this.suggestedVariableName = makeLegal(this.generateVariableName());
  14936. }
  14937. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  14938. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  14939. chunk.assignFacadeName(facadeName, facadedModule);
  14940. if (!facadeChunkByModule.has(facadedModule)) {
  14941. facadeChunkByModule.set(facadedModule, chunk);
  14942. }
  14943. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  14944. chunk.dependencies.add(dependency instanceof Module
  14945. ? chunkByModule.get(dependency)
  14946. : externalChunkByModule.get(dependency));
  14947. }
  14948. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  14949. facadedModule.info.moduleSideEffects &&
  14950. facadedModule.hasEffects()) {
  14951. chunk.dependencies.add(chunkByModule.get(facadedModule));
  14952. }
  14953. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  14954. chunk.facadeModule = facadedModule;
  14955. chunk.strictFacade = true;
  14956. return chunk;
  14957. }
  14958. canModuleBeFacade(module, exposedVariables) {
  14959. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  14960. // All exports of this chunk need to be exposed by the candidate module
  14961. for (const exposedVariable of this.exports) {
  14962. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  14963. return false;
  14964. }
  14965. }
  14966. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  14967. for (const exposedVariable of exposedVariables) {
  14968. if (!(exposedVariable.module === module ||
  14969. moduleExportNamesByVariable.has(exposedVariable) ||
  14970. (exposedVariable instanceof SyntheticNamedExportVariable &&
  14971. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  14972. return false;
  14973. }
  14974. }
  14975. return true;
  14976. }
  14977. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  14978. const renderedChunkInfo = this.getRenderedChunkInfo();
  14979. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  14980. const preliminaryFileName = renderedChunkInfo.fileName;
  14981. const fileName = (this.fileName = finalize(preliminaryFileName));
  14982. return {
  14983. ...renderedChunkInfo,
  14984. code,
  14985. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  14986. fileName,
  14987. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  14988. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  14989. finalize(fileName),
  14990. bindings
  14991. ])),
  14992. imports: renderedChunkInfo.imports.map(finalize),
  14993. map,
  14994. preliminaryFileName,
  14995. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  14996. sourcemapFileName
  14997. };
  14998. }
  14999. generateExports() {
  15000. this.sortedExportNames = null;
  15001. const remainingExports = new Set(this.exports);
  15002. if (this.facadeModule !== null &&
  15003. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  15004. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  15005. for (const [variable, exportNames] of exportNamesByVariable) {
  15006. this.exportNamesByVariable.set(variable, [...exportNames]);
  15007. for (const exportName of exportNames) {
  15008. this.exportsByName.set(exportName, variable);
  15009. }
  15010. remainingExports.delete(variable);
  15011. }
  15012. }
  15013. if (this.outputOptions.minifyInternalExports) {
  15014. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  15015. }
  15016. else {
  15017. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  15018. }
  15019. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  15020. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  15021. }
  15022. generateFacades() {
  15023. const facades = [];
  15024. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  15025. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  15026. for (const module of entryModules) {
  15027. if (module.preserveSignature) {
  15028. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  15029. // We need to expose all entry exports from this chunk
  15030. if (this.chunkByModule.get(exportedVariable.module) === this) {
  15031. exposedVariables.add(exportedVariable);
  15032. }
  15033. }
  15034. }
  15035. }
  15036. for (const module of entryModules) {
  15037. // eslint-disable-next-line unicorn/prefer-spread
  15038. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  15039. // mapping must run after Set 'name' dedupe
  15040. name => ({
  15041. name
  15042. }));
  15043. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  15044. requiredFacades.push({});
  15045. }
  15046. // eslint-disable-next-line unicorn/prefer-spread
  15047. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  15048. if (requiredFacades.length === 0) {
  15049. requiredFacades.push({});
  15050. }
  15051. if (!this.facadeModule) {
  15052. const needsStrictFacade = !this.outputOptions.preserveModules &&
  15053. (module.preserveSignature === 'strict' ||
  15054. (module.preserveSignature === 'exports-only' &&
  15055. module.getExportNamesByVariable().size > 0));
  15056. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  15057. this.facadeModule = module;
  15058. this.facadeChunkByModule.set(module, this);
  15059. if (module.preserveSignature) {
  15060. this.strictFacade = needsStrictFacade;
  15061. }
  15062. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  15063. }
  15064. }
  15065. for (const facadeName of requiredFacades) {
  15066. 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));
  15067. }
  15068. }
  15069. for (const module of this.dynamicEntryModules) {
  15070. if (module.info.syntheticNamedExports)
  15071. continue;
  15072. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  15073. this.facadeModule = module;
  15074. this.facadeChunkByModule.set(module, this);
  15075. this.strictFacade = true;
  15076. this.dynamicName = getChunkNameFromModule(module);
  15077. }
  15078. else if (this.facadeModule === module &&
  15079. !this.strictFacade &&
  15080. this.canModuleBeFacade(module, exposedVariables)) {
  15081. this.strictFacade = true;
  15082. }
  15083. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  15084. this.includedNamespaces.add(module);
  15085. this.exports.add(module.namespace);
  15086. }
  15087. }
  15088. if (!this.outputOptions.preserveModules) {
  15089. this.addNecessaryImportsForFacades();
  15090. }
  15091. return facades;
  15092. }
  15093. getChunkName() {
  15094. return (this.name ??= this.outputOptions.sanitizeFileName(this.getFallbackChunkName()));
  15095. }
  15096. getExportNames() {
  15097. return (this.sortedExportNames ??= [...this.exportsByName.keys()].sort());
  15098. }
  15099. getFileName() {
  15100. return this.fileName || this.getPreliminaryFileName().fileName;
  15101. }
  15102. getImportPath(importer) {
  15103. return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  15104. }
  15105. getPreliminaryFileName() {
  15106. if (this.preliminaryFileName) {
  15107. return this.preliminaryFileName;
  15108. }
  15109. let fileName;
  15110. let hashPlaceholder = null;
  15111. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  15112. if (file) {
  15113. fileName = basename(file);
  15114. }
  15115. else if (this.fileName === null) {
  15116. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  15117. ? [entryFileNames, 'output.entryFileNames']
  15118. : [chunkFileNames, 'output.chunkFileNames'];
  15119. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  15120. format: () => format,
  15121. hash: size => hashPlaceholder ||
  15122. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  15123. name: () => this.getChunkName()
  15124. });
  15125. if (!hashPlaceholder) {
  15126. fileName = makeUnique(fileName, this.bundle);
  15127. }
  15128. }
  15129. else {
  15130. fileName = this.fileName;
  15131. }
  15132. if (!hashPlaceholder) {
  15133. this.bundle[fileName] = FILE_PLACEHOLDER;
  15134. }
  15135. // Caching is essential to not conflict with the file name reservation above
  15136. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  15137. }
  15138. getPreliminarySourcemapFileName() {
  15139. if (this.preliminarySourcemapFileName) {
  15140. return this.preliminarySourcemapFileName;
  15141. }
  15142. let sourcemapFileName = null;
  15143. let hashPlaceholder = null;
  15144. const { sourcemapFileNames, format } = this.outputOptions;
  15145. if (sourcemapFileNames) {
  15146. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  15147. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  15148. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  15149. format: () => format,
  15150. hash: size => hashPlaceholder ||
  15151. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  15152. name: () => this.getChunkName()
  15153. });
  15154. if (!hashPlaceholder) {
  15155. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  15156. }
  15157. }
  15158. else {
  15159. return null;
  15160. }
  15161. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  15162. }
  15163. getRenderedChunkInfo() {
  15164. if (this.renderedChunkInfo) {
  15165. return this.renderedChunkInfo;
  15166. }
  15167. return (this.renderedChunkInfo = {
  15168. ...this.getPreRenderedChunkInfo(),
  15169. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  15170. fileName: this.getFileName(),
  15171. // eslint-disable-next-line unicorn/prefer-spread
  15172. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  15173. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  15174. // eslint-disable-next-line unicorn/prefer-spread
  15175. imports: Array.from(this.dependencies, resolveFileName),
  15176. modules: this.renderedModules,
  15177. referencedFiles: this.getReferencedFiles()
  15178. });
  15179. }
  15180. getVariableExportName(variable) {
  15181. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  15182. return '*';
  15183. }
  15184. return this.exportNamesByVariable.get(variable)[0];
  15185. }
  15186. link() {
  15187. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  15188. for (const module of this.orderedModules) {
  15189. this.addImplicitlyLoadedBeforeFromModule(module);
  15190. this.setUpChunkImportsAndExportsForModule(module);
  15191. }
  15192. }
  15193. async render() {
  15194. const { dependencies, exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  15195. const { format, hoistTransitiveImports, preserveModules } = outputOptions;
  15196. // for static and dynamic entry points, add transitive dependencies to this
  15197. // chunk's dependencies to avoid loading latency
  15198. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  15199. for (const dep of dependencies) {
  15200. if (dep instanceof Chunk)
  15201. this.inlineChunkDependencies(dep);
  15202. }
  15203. }
  15204. const preliminaryFileName = this.getPreliminaryFileName();
  15205. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  15206. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  15207. const renderedDependencies = [...this.getRenderedDependencies().values()];
  15208. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  15209. let hasExports = renderedExports.length > 0;
  15210. let hasDefaultExport = false;
  15211. for (const renderedDependency of renderedDependencies) {
  15212. const { reexports } = renderedDependency;
  15213. if (reexports?.length) {
  15214. hasExports = true;
  15215. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  15216. hasDefaultExport = true;
  15217. }
  15218. if (format === 'es') {
  15219. renderedDependency.reexports = reexports.filter(
  15220. // eslint-disable-next-line unicorn/prefer-array-some
  15221. ({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  15222. }
  15223. }
  15224. }
  15225. if (!hasDefaultExport) {
  15226. for (const { exported } of renderedExports) {
  15227. if (exported === 'default') {
  15228. hasDefaultExport = true;
  15229. break;
  15230. }
  15231. }
  15232. }
  15233. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  15234. finalisers[format](renderedSource, {
  15235. accessedGlobals,
  15236. dependencies: renderedDependencies,
  15237. exports: renderedExports,
  15238. hasDefaultExport,
  15239. hasExports,
  15240. id: preliminaryFileName.fileName,
  15241. indent,
  15242. intro,
  15243. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  15244. isModuleFacade: facadeModule !== null,
  15245. log: onLog,
  15246. namedExportsMode: exportMode !== 'default',
  15247. outro,
  15248. snippets,
  15249. usesTopLevelAwait
  15250. }, outputOptions);
  15251. if (banner)
  15252. magicString.prepend(banner);
  15253. if (format === 'es' || format === 'cjs') {
  15254. const shebang = facadeModule !== null && facadeModule.info.isEntry && facadeModule.shebang;
  15255. shebang && magicString.prepend(`#!${shebang}\n`);
  15256. }
  15257. if (footer)
  15258. magicString.append(footer);
  15259. return {
  15260. chunk: this,
  15261. magicString,
  15262. preliminaryFileName,
  15263. preliminarySourcemapFileName,
  15264. usedModules
  15265. };
  15266. }
  15267. addImplicitlyLoadedBeforeFromModule(baseModule) {
  15268. const { chunkByModule, implicitlyLoadedBefore } = this;
  15269. for (const module of baseModule.implicitlyLoadedBefore) {
  15270. const chunk = chunkByModule.get(module);
  15271. if (chunk && chunk !== this) {
  15272. implicitlyLoadedBefore.add(chunk);
  15273. }
  15274. }
  15275. }
  15276. addNecessaryImportsForFacades() {
  15277. for (const [module, variables] of this.includedReexportsByModule) {
  15278. if (this.includedNamespaces.has(module)) {
  15279. for (const variable of variables) {
  15280. this.imports.add(variable);
  15281. }
  15282. }
  15283. }
  15284. }
  15285. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  15286. if (fileName) {
  15287. this.fileName = fileName;
  15288. }
  15289. else {
  15290. this.name = this.outputOptions.sanitizeFileName(name ||
  15291. (preservePath
  15292. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  15293. : getChunkNameFromModule(facadedModule)));
  15294. }
  15295. }
  15296. checkCircularDependencyImport(variable, importingModule) {
  15297. const variableModule = variable.module;
  15298. if (variableModule instanceof Module) {
  15299. const exportChunk = this.chunkByModule.get(variableModule);
  15300. let alternativeReexportModule;
  15301. do {
  15302. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  15303. if (alternativeReexportModule) {
  15304. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  15305. if (exportingChunk !== exportChunk) {
  15306. this.inputOptions.onLog(LOGLEVEL_WARN, logCyclicCrossChunkReexport(
  15307. // Namespaces do not have an export name
  15308. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  15309. }
  15310. importingModule = alternativeReexportModule;
  15311. }
  15312. } while (alternativeReexportModule);
  15313. }
  15314. }
  15315. ensureReexportsAreAvailableForModule(module) {
  15316. const includedReexports = [];
  15317. const map = module.getExportNamesByVariable();
  15318. for (const exportedVariable of map.keys()) {
  15319. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  15320. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  15321. this.checkCircularDependencyImport(importedVariable, module);
  15322. // When preserving modules, we do not create namespace objects but directly
  15323. // use the actual namespaces, which would be broken by this logic.
  15324. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  15325. const exportingModule = importedVariable.module;
  15326. if (exportingModule instanceof Module) {
  15327. const chunk = this.chunkByModule.get(exportingModule);
  15328. if (chunk && chunk !== this) {
  15329. chunk.exports.add(importedVariable);
  15330. includedReexports.push(importedVariable);
  15331. if (isSynthetic) {
  15332. this.imports.add(importedVariable);
  15333. }
  15334. }
  15335. }
  15336. }
  15337. }
  15338. if (includedReexports.length > 0) {
  15339. this.includedReexportsByModule.set(module, includedReexports);
  15340. }
  15341. }
  15342. generateVariableName() {
  15343. if (this.manualChunkAlias) {
  15344. return this.manualChunkAlias;
  15345. }
  15346. const moduleForNaming = this.entryModules[0] ||
  15347. this.implicitEntryModules[0] ||
  15348. this.dynamicEntryModules[0] ||
  15349. this.orderedModules[this.orderedModules.length - 1];
  15350. if (moduleForNaming) {
  15351. return getChunkNameFromModule(moduleForNaming);
  15352. }
  15353. return 'chunk';
  15354. }
  15355. getChunkExportDeclarations(format) {
  15356. const exports = [];
  15357. for (const exportName of this.getExportNames()) {
  15358. if (exportName[0] === '*')
  15359. continue;
  15360. const variable = this.exportsByName.get(exportName);
  15361. if (!(variable instanceof SyntheticNamedExportVariable)) {
  15362. const module = variable.module;
  15363. if (module) {
  15364. const chunk = this.chunkByModule.get(module);
  15365. if (chunk !== this) {
  15366. if (!chunk || format !== 'es') {
  15367. continue;
  15368. }
  15369. const chunkDep = this.renderedDependencies.get(chunk);
  15370. if (!chunkDep) {
  15371. continue;
  15372. }
  15373. const { imports, reexports } = chunkDep;
  15374. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  15375. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  15376. if (!isImported) {
  15377. continue;
  15378. }
  15379. }
  15380. }
  15381. }
  15382. let expression = null;
  15383. let hoisted = false;
  15384. let local = variable.getName(this.snippets.getPropertyAccess);
  15385. if (variable instanceof LocalVariable) {
  15386. for (const declaration of variable.declarations) {
  15387. if (declaration.parent instanceof FunctionDeclaration ||
  15388. (declaration instanceof ExportDefaultDeclaration &&
  15389. declaration.declaration instanceof FunctionDeclaration)) {
  15390. hoisted = true;
  15391. break;
  15392. }
  15393. }
  15394. }
  15395. else if (variable instanceof SyntheticNamedExportVariable) {
  15396. expression = local;
  15397. if (format === 'es') {
  15398. local = variable.renderName;
  15399. }
  15400. }
  15401. exports.push({
  15402. exported: exportName,
  15403. expression,
  15404. hoisted,
  15405. local
  15406. });
  15407. }
  15408. return exports;
  15409. }
  15410. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  15411. const dependencies = new Set();
  15412. const deconflictedDefault = new Set();
  15413. const deconflictedNamespace = new Set();
  15414. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  15415. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  15416. const module = variable.module;
  15417. if (module instanceof ExternalModule) {
  15418. const chunk = this.externalChunkByModule.get(module);
  15419. dependencies.add(chunk);
  15420. if (addNonNamespacesAndInteropHelpers) {
  15421. if (variable.name === 'default') {
  15422. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  15423. deconflictedDefault.add(chunk);
  15424. }
  15425. }
  15426. else if (variable.isNamespace &&
  15427. namespaceInteropHelpersByInteropType[interop(module.id)] &&
  15428. (this.imports.has(variable) ||
  15429. !this.exportNamesByVariable.get(variable)?.every(name => name.startsWith('*')))) {
  15430. // We only need to deconflict it if the namespace is actually
  15431. // created as a variable, i.e. because it is used internally or
  15432. // because it is reexported as an object
  15433. deconflictedNamespace.add(chunk);
  15434. }
  15435. }
  15436. }
  15437. else {
  15438. const chunk = this.chunkByModule.get(module);
  15439. if (chunk !== this) {
  15440. dependencies.add(chunk);
  15441. if (addNonNamespacesAndInteropHelpers &&
  15442. chunk.exportMode === 'default' &&
  15443. variable.isNamespace) {
  15444. deconflictedNamespace.add(chunk);
  15445. }
  15446. }
  15447. }
  15448. }
  15449. }
  15450. if (addDependenciesWithoutBindings) {
  15451. for (const dependency of this.dependencies) {
  15452. dependencies.add(dependency);
  15453. }
  15454. }
  15455. return { deconflictedDefault, deconflictedNamespace, dependencies };
  15456. }
  15457. getDynamicDependencies() {
  15458. return this.getIncludedDynamicImports()
  15459. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  15460. resolvedDynamicImport.chunk ||
  15461. resolvedDynamicImport.externalChunk ||
  15462. resolvedDynamicImport.resolution)
  15463. .filter((resolution) => resolution !== this &&
  15464. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  15465. }
  15466. getDynamicImportStringAndAttributes(resolution, fileName) {
  15467. if (resolution instanceof ExternalModule) {
  15468. const chunk = this.externalChunkByModule.get(resolution);
  15469. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAttributes(this.snippets)];
  15470. }
  15471. return [
  15472. resolution || '',
  15473. (this.outputOptions.format === 'es' && this.outputOptions.externalImportAttributes) || null
  15474. ];
  15475. }
  15476. getFallbackChunkName() {
  15477. if (this.manualChunkAlias) {
  15478. return this.manualChunkAlias;
  15479. }
  15480. if (this.dynamicName) {
  15481. return this.dynamicName;
  15482. }
  15483. if (this.fileName) {
  15484. return getAliasName(this.fileName);
  15485. }
  15486. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  15487. }
  15488. getImportSpecifiers() {
  15489. const { interop } = this.outputOptions;
  15490. const importsByDependency = new Map();
  15491. for (const variable of this.imports) {
  15492. const module = variable.module;
  15493. let dependency;
  15494. let imported;
  15495. if (module instanceof ExternalModule) {
  15496. dependency = this.externalChunkByModule.get(module);
  15497. imported = variable.name;
  15498. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  15499. return error(logUnexpectedNamedImport(module.id, imported, false));
  15500. }
  15501. }
  15502. else {
  15503. dependency = this.chunkByModule.get(module);
  15504. imported = dependency.getVariableExportName(variable);
  15505. }
  15506. getOrCreate(importsByDependency, dependency, getNewArray).push({
  15507. imported,
  15508. local: variable.getName(this.snippets.getPropertyAccess)
  15509. });
  15510. }
  15511. return importsByDependency;
  15512. }
  15513. getIncludedDynamicImports() {
  15514. if (this.includedDynamicImports) {
  15515. return this.includedDynamicImports;
  15516. }
  15517. const includedDynamicImports = [];
  15518. for (const module of this.orderedModules) {
  15519. for (const { node, resolution } of module.dynamicImports) {
  15520. if (!node.included) {
  15521. continue;
  15522. }
  15523. includedDynamicImports.push(resolution instanceof Module
  15524. ? {
  15525. chunk: this.chunkByModule.get(resolution),
  15526. externalChunk: null,
  15527. facadeChunk: this.facadeChunkByModule.get(resolution),
  15528. node,
  15529. resolution
  15530. }
  15531. : resolution instanceof ExternalModule
  15532. ? {
  15533. chunk: null,
  15534. externalChunk: this.externalChunkByModule.get(resolution),
  15535. facadeChunk: null,
  15536. node,
  15537. resolution
  15538. }
  15539. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  15540. }
  15541. }
  15542. return (this.includedDynamicImports = includedDynamicImports);
  15543. }
  15544. getPreRenderedChunkInfo() {
  15545. if (this.preRenderedChunkInfo) {
  15546. return this.preRenderedChunkInfo;
  15547. }
  15548. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  15549. return (this.preRenderedChunkInfo = {
  15550. exports: this.getExportNames(),
  15551. facadeModuleId: facadeModule && facadeModule.id,
  15552. isDynamicEntry: dynamicEntryModules.length > 0,
  15553. isEntry: !!facadeModule?.info.isEntry,
  15554. isImplicitEntry: implicitEntryModules.length > 0,
  15555. moduleIds: orderedModules.map(({ id }) => id),
  15556. name: this.getChunkName(),
  15557. type: 'chunk'
  15558. });
  15559. }
  15560. getPreserveModulesChunkNameFromModule(module) {
  15561. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  15562. if (predefinedChunkName)
  15563. return predefinedChunkName;
  15564. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  15565. const sanitizedId = sanitizeFileName(normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  15566. const extensionName = extname(sanitizedId);
  15567. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  15568. ? sanitizedId.slice(0, -extensionName.length)
  15569. : sanitizedId;
  15570. if (isAbsolute$1(idWithoutExtension)) {
  15571. return preserveModulesRoot && resolve$1(idWithoutExtension).startsWith(preserveModulesRoot)
  15572. ? idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '')
  15573. : relative$1(this.inputBase, idWithoutExtension);
  15574. }
  15575. else {
  15576. return `_virtual/${basename(idWithoutExtension)}`;
  15577. }
  15578. }
  15579. getReexportSpecifiers() {
  15580. const { externalLiveBindings, interop } = this.outputOptions;
  15581. const reexportSpecifiers = new Map();
  15582. for (let exportName of this.getExportNames()) {
  15583. let dependency;
  15584. let imported;
  15585. let needsLiveBinding = false;
  15586. if (exportName[0] === '*') {
  15587. const id = exportName.slice(1);
  15588. if (interop(id) === 'defaultOnly') {
  15589. this.inputOptions.onLog(LOGLEVEL_WARN, logUnexpectedNamespaceReexport(id));
  15590. }
  15591. needsLiveBinding = externalLiveBindings;
  15592. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  15593. imported = exportName = '*';
  15594. }
  15595. else {
  15596. const variable = this.exportsByName.get(exportName);
  15597. if (variable instanceof SyntheticNamedExportVariable)
  15598. continue;
  15599. const module = variable.module;
  15600. if (module instanceof Module) {
  15601. dependency = this.chunkByModule.get(module);
  15602. if (dependency === this)
  15603. continue;
  15604. imported = dependency.getVariableExportName(variable);
  15605. needsLiveBinding = variable.isReassigned;
  15606. }
  15607. else {
  15608. dependency = this.externalChunkByModule.get(module);
  15609. imported = variable.name;
  15610. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  15611. return error(logUnexpectedNamedImport(module.id, imported, true));
  15612. }
  15613. needsLiveBinding =
  15614. externalLiveBindings &&
  15615. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  15616. }
  15617. }
  15618. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  15619. imported,
  15620. needsLiveBinding,
  15621. reexported: exportName
  15622. });
  15623. }
  15624. return reexportSpecifiers;
  15625. }
  15626. getReferencedFiles() {
  15627. const referencedFiles = new Set();
  15628. for (const module of this.orderedModules) {
  15629. for (const meta of module.importMetas) {
  15630. const fileName = meta.getReferencedFileName(this.pluginDriver);
  15631. if (fileName) {
  15632. referencedFiles.add(fileName);
  15633. }
  15634. }
  15635. }
  15636. return [...referencedFiles];
  15637. }
  15638. getRenderedDependencies() {
  15639. if (this.renderedDependencies) {
  15640. return this.renderedDependencies;
  15641. }
  15642. const importSpecifiers = this.getImportSpecifiers();
  15643. const reexportSpecifiers = this.getReexportSpecifiers();
  15644. const renderedDependencies = new Map();
  15645. const fileName = this.getFileName();
  15646. for (const dependency of this.dependencies) {
  15647. const imports = importSpecifiers.get(dependency) || null;
  15648. const reexports = reexportSpecifiers.get(dependency) || null;
  15649. const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
  15650. const importPath = dependency.getImportPath(fileName);
  15651. renderedDependencies.set(dependency, {
  15652. attributes: dependency instanceof ExternalChunk
  15653. ? dependency.getImportAttributes(this.snippets)
  15654. : null,
  15655. defaultVariableName: dependency.defaultVariableName,
  15656. globalName: dependency instanceof ExternalChunk &&
  15657. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  15658. getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  15659. importPath,
  15660. imports,
  15661. isChunk: dependency instanceof Chunk,
  15662. name: dependency.variableName,
  15663. namedExportsMode,
  15664. namespaceVariableName: dependency.namespaceVariableName,
  15665. reexports
  15666. });
  15667. }
  15668. return (this.renderedDependencies = renderedDependencies);
  15669. }
  15670. inlineChunkDependencies(chunk) {
  15671. for (const dep of chunk.dependencies) {
  15672. if (this.dependencies.has(dep))
  15673. continue;
  15674. this.dependencies.add(dep);
  15675. if (dep instanceof Chunk) {
  15676. this.inlineChunkDependencies(dep);
  15677. }
  15678. }
  15679. }
  15680. // This method changes properties on the AST before rendering and must not be async
  15681. renderModules(fileName) {
  15682. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  15683. const { compact, format, freeze, generatedCode: { symbols } } = outputOptions;
  15684. const { _, cnst, n } = snippets;
  15685. this.setDynamicImportResolutions(fileName);
  15686. this.setImportMetaResolutions(fileName);
  15687. this.setIdentifierRenderResolutions();
  15688. const magicString = new Bundle$1({ separator: `${n}${n}` });
  15689. const indent = getIndentString(orderedModules, outputOptions);
  15690. const usedModules = [];
  15691. let hoistedSource = '';
  15692. const accessedGlobals = new Set();
  15693. const renderedModuleSources = new Map();
  15694. const renderOptions = {
  15695. accessedDocumentCurrentScript: false,
  15696. exportNamesByVariable,
  15697. format,
  15698. freeze,
  15699. indent,
  15700. pluginDriver,
  15701. snippets,
  15702. symbols,
  15703. useOriginalName: null
  15704. };
  15705. let usesTopLevelAwait = false;
  15706. for (const module of orderedModules) {
  15707. let renderedLength = 0;
  15708. let source;
  15709. if (module.isIncluded() || includedNamespaces.has(module)) {
  15710. const rendered = module.render(renderOptions);
  15711. if (!renderOptions.accessedDocumentCurrentScript &&
  15712. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  15713. // eslint-disable-next-line unicorn/consistent-destructuring
  15714. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  15715. }
  15716. renderOptions.accessedDocumentCurrentScript = false;
  15717. ({ source } = rendered);
  15718. usesTopLevelAwait ||= rendered.usesTopLevelAwait;
  15719. renderedLength = source.length();
  15720. if (renderedLength) {
  15721. if (compact && source.lastLine().includes('//'))
  15722. source.append('\n');
  15723. renderedModuleSources.set(module, source);
  15724. magicString.addSource(source);
  15725. usedModules.push(module);
  15726. }
  15727. const namespace = module.namespace;
  15728. if (includedNamespaces.has(module)) {
  15729. const rendered = namespace.renderBlock(renderOptions);
  15730. if (namespace.renderFirst())
  15731. hoistedSource += n + rendered;
  15732. else
  15733. magicString.addSource(new MagicString(rendered));
  15734. }
  15735. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  15736. if (accessedGlobalVariables) {
  15737. for (const name of accessedGlobalVariables) {
  15738. accessedGlobals.add(name);
  15739. }
  15740. }
  15741. }
  15742. const { renderedExports, removedExports } = module.getRenderedExports();
  15743. renderedModules[module.id] = {
  15744. get code() {
  15745. return source?.toString() ?? null;
  15746. },
  15747. originalLength: module.originalCode.length,
  15748. removedExports,
  15749. renderedExports,
  15750. renderedLength
  15751. };
  15752. }
  15753. if (hoistedSource)
  15754. magicString.prepend(hoistedSource + n + n);
  15755. // eslint-disable-next-line unicorn/consistent-destructuring
  15756. if (this.needsExportsShim) {
  15757. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  15758. }
  15759. const renderedSource = compact ? magicString : magicString.trim();
  15760. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  15761. onLog(LOGLEVEL_WARN, logEmptyChunk(this.getChunkName()));
  15762. }
  15763. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  15764. }
  15765. setDynamicImportResolutions(fileName) {
  15766. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  15767. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  15768. if (resolvedDynamicImport.chunk) {
  15769. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  15770. if (chunk === this) {
  15771. node.setInternalResolution(resolution.namespace);
  15772. }
  15773. else {
  15774. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null);
  15775. }
  15776. }
  15777. else {
  15778. const { node, resolution } = resolvedDynamicImport;
  15779. const [resolutionString, attributes] = this.getDynamicImportStringAndAttributes(resolution, fileName);
  15780. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, attributes);
  15781. }
  15782. }
  15783. }
  15784. setIdentifierRenderResolutions() {
  15785. const { format, generatedCode: { symbols }, interop, preserveModules, externalLiveBindings } = this.outputOptions;
  15786. const syntheticExports = new Set();
  15787. for (const exportName of this.getExportNames()) {
  15788. const exportVariable = this.exportsByName.get(exportName);
  15789. if (format !== 'es' &&
  15790. format !== 'system' &&
  15791. exportVariable.isReassigned &&
  15792. !exportVariable.isId) {
  15793. exportVariable.setRenderNames('exports', exportName);
  15794. }
  15795. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  15796. syntheticExports.add(exportVariable);
  15797. }
  15798. else {
  15799. exportVariable.setRenderNames(null, null);
  15800. }
  15801. }
  15802. for (const module of this.orderedModules) {
  15803. if (module.needsExportShim) {
  15804. this.needsExportsShim = true;
  15805. break;
  15806. }
  15807. }
  15808. const usedNames = new Set(['Object', 'Promise']);
  15809. if (this.needsExportsShim) {
  15810. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  15811. }
  15812. if (symbols) {
  15813. usedNames.add('Symbol');
  15814. }
  15815. switch (format) {
  15816. case 'system': {
  15817. usedNames.add('module').add('exports');
  15818. break;
  15819. }
  15820. case 'es': {
  15821. break;
  15822. }
  15823. case 'cjs': {
  15824. usedNames.add('module').add('require').add('__filename').add('__dirname');
  15825. }
  15826. // fallthrough
  15827. default: {
  15828. usedNames.add('exports');
  15829. for (const helper of HELPER_NAMES) {
  15830. usedNames.add(helper);
  15831. }
  15832. }
  15833. }
  15834. 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);
  15835. }
  15836. setImportMetaResolutions(fileName) {
  15837. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  15838. for (const module of orderedModules) {
  15839. for (const importMeta of module.importMetas) {
  15840. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  15841. }
  15842. if (includedNamespaces.has(module)) {
  15843. module.namespace.prepare(accessedGlobalsByScope);
  15844. }
  15845. }
  15846. }
  15847. setUpChunkImportsAndExportsForModule(module) {
  15848. const moduleImports = new Set(module.includedImports);
  15849. // when we are not preserving modules, we need to make all namespace variables available for
  15850. // rendering the namespace object
  15851. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  15852. const memberVariables = module.namespace.getMemberVariables();
  15853. for (const variable of Object.values(memberVariables)) {
  15854. if (variable.included) {
  15855. moduleImports.add(variable);
  15856. }
  15857. }
  15858. }
  15859. for (let variable of moduleImports) {
  15860. if (variable instanceof ExportDefaultVariable) {
  15861. variable = variable.getOriginalVariable();
  15862. }
  15863. if (variable instanceof SyntheticNamedExportVariable) {
  15864. variable = variable.getBaseVariable();
  15865. }
  15866. const chunk = this.chunkByModule.get(variable.module);
  15867. if (chunk !== this) {
  15868. this.imports.add(variable);
  15869. if (variable.module instanceof Module) {
  15870. this.checkCircularDependencyImport(variable, module);
  15871. // When preserving modules, we do not create namespace objects but directly
  15872. // use the actual namespaces, which would be broken by this logic.
  15873. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  15874. chunk.exports.add(variable);
  15875. }
  15876. }
  15877. }
  15878. }
  15879. if (this.includedNamespaces.has(module) ||
  15880. (module.info.isEntry && module.preserveSignature !== false) ||
  15881. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  15882. this.ensureReexportsAreAvailableForModule(module);
  15883. }
  15884. for (const { node, resolution } of module.dynamicImports) {
  15885. if (node.included &&
  15886. resolution instanceof Module &&
  15887. this.chunkByModule.get(resolution) === this &&
  15888. !this.includedNamespaces.has(resolution)) {
  15889. this.includedNamespaces.add(resolution);
  15890. this.ensureReexportsAreAvailableForModule(resolution);
  15891. }
  15892. }
  15893. }
  15894. }
  15895. function getChunkNameFromModule(module) {
  15896. return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id);
  15897. }
  15898. function getPredefinedChunkNameFromModule(module) {
  15899. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  15900. }
  15901. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  15902. const importedBindingsPerDependency = {};
  15903. for (const [dependency, declaration] of renderedDependencies) {
  15904. const specifiers = new Set();
  15905. if (declaration.imports) {
  15906. for (const { imported } of declaration.imports) {
  15907. specifiers.add(imported);
  15908. }
  15909. }
  15910. if (declaration.reexports) {
  15911. for (const { imported } of declaration.reexports) {
  15912. specifiers.add(imported);
  15913. }
  15914. }
  15915. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  15916. }
  15917. return importedBindingsPerDependency;
  15918. }
  15919. const QUERY_HASH_REGEX = /[#?]/;
  15920. const resolveFileName = (dependency) => dependency.getFileName();
  15921. /**
  15922. * Concatenate a number of iterables to a new iterable without fully evaluating
  15923. * their iterators. Useful when e.g. working with large sets or lists and when
  15924. * there is a chance that the iterators will not be fully exhausted.
  15925. */
  15926. function* concatLazy(iterables) {
  15927. for (const iterable of iterables) {
  15928. yield* iterable;
  15929. }
  15930. }
  15931. /**
  15932. * At its core, the algorithm first starts from each static or dynamic entry
  15933. * point and then assigns that entry point to all modules than can be reached
  15934. * via static imports. We call this the *dependent entry points* of that
  15935. * module.
  15936. *
  15937. * Then we group all modules with the same dependent entry points into chunks
  15938. * as those modules will always be loaded together.
  15939. *
  15940. * One non-trivial optimization we can apply is that dynamic entries are
  15941. * different from static entries in so far as when a dynamic import occurs,
  15942. * some modules are already in memory. If some of these modules are also
  15943. * dependencies of the dynamic entry, then it does not make sense to create a
  15944. * separate chunk for them. Instead, the dynamic import target can load them
  15945. * from the importing chunk.
  15946. *
  15947. * With regard to chunking, if B is implicitly loaded after A, then this can be
  15948. * handled the same way as if there was a dynamic import A => B.
  15949. *
  15950. * Example:
  15951. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  15952. * Then the initial algorithm would assign A into the A chunk, C into the C
  15953. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  15954. * points A and C.
  15955. * However we know that C can only be loaded from A, so A and its dependency B
  15956. * must already be in memory when C is loaded. So it is enough to create only
  15957. * two chunks A containing [AB] and C containing [C].
  15958. *
  15959. * So we do not assign the dynamic entry C as dependent entry point to modules
  15960. * that are already loaded.
  15961. *
  15962. * In a more complex example, let us assume that we have entry points X and Y.
  15963. * Further, let us assume
  15964. * X -> A, X -> B, X -> C,
  15965. * Y -> A, Y -> B,
  15966. * A => D,
  15967. * D -> B, D -> C
  15968. * So without dynamic import optimization, the dependent entry points are
  15969. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, so we would for now create six
  15970. * chunks.
  15971. *
  15972. * Now D is loaded only after A is loaded. But A is loaded if either X is
  15973. * loaded or Y is loaded. So the modules that are already in memory when D is
  15974. * loaded are the intersection of all modules that X depends on with all
  15975. * modules that Y depends on, which in this case are the modules A and B.
  15976. * We could also say they are all modules that have both X and Y as dependent
  15977. * entry points.
  15978. *
  15979. * So we can remove D as dependent entry point from A and B, which means they
  15980. * both now have only XY as dependent entry points and can be merged into the
  15981. * same chunk.
  15982. *
  15983. * Now let us extend this to the most general case where we have several
  15984. * dynamic importers for one dynamic entry point.
  15985. *
  15986. * In the most general form, it works like this:
  15987. * For each dynamic entry point, we have a number of dynamic importers, which
  15988. * are the modules importing it. Using the previous ideas, we can determine
  15989. * the modules already in memory for each dynamic importer by looking for all
  15990. * modules that have all the dependent entry points of the dynamic importer as
  15991. * dependent entry points.
  15992. * So the modules that are guaranteed to be in memory when the dynamic entry
  15993. * point is loaded are the intersection of the modules already in memory for
  15994. * each dynamic importer.
  15995. *
  15996. * Assuming that A => D and B => D and A has dependent entry points XY and B
  15997. * has dependent entry points YZ, then the modules guaranteed to be in memory
  15998. * are all modules that have at least XYZ as dependent entry points.
  15999. * We call XYZ the *dynamically dependent entry points* of D.
  16000. *
  16001. * Now there is one last case to consider: If one of the dynamically dependent
  16002. * entries is itself a dynamic entry, then any module is in memory that either
  16003. * is a dependency of that dynamic entry or again has the dynamic dependent
  16004. * entries of that dynamic entry as dependent entry points.
  16005. *
  16006. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  16007. * complexity with regard to dynamic entries that blew up for very large
  16008. * projects.
  16009. *
  16010. * If we have an efficient way to do Set operations, an alternative approach
  16011. * would be to instead collect already loaded modules per dynamic entry. And as
  16012. * all chunks from the initial grouping would behave the same, we can instead
  16013. * collect already loaded chunks for a performance improvement.
  16014. *
  16015. * To do that efficiently, need
  16016. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  16017. * imports that can be triggered by a dynamic entry
  16018. * - a Map of static dependencies per entry
  16019. * - a Map of already loaded chunks per entry that we initially populate with
  16020. * empty Sets for static entries and Sets containing all entries for dynamic
  16021. * entries
  16022. *
  16023. * For efficient operations, we assign each entry a numerical index and
  16024. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  16025. * bit index. Then the last two maps can be represented as arrays of BigInt
  16026. * values.
  16027. *
  16028. * Then we iterate through each dynamic entry. We set the already loaded modules
  16029. * to the intersection of the previously already loaded modules with the union
  16030. * of the already loaded modules of that chunk with its static dependencies.
  16031. *
  16032. * If the already loaded modules changed, then we use the Map of dynamic imports
  16033. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  16034. * them back into the iteration. As an additional optimization, we note for
  16035. * each dynamic entry which dynamic dependent entries have changed and only
  16036. * intersect those entries again on subsequent interations.
  16037. *
  16038. * Then we remove the dynamic entries from the list of dependent entries for
  16039. * those chunks that are already loaded for that dynamic entry and create
  16040. * another round of chunks.
  16041. */
  16042. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log) {
  16043. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  16044. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry } = analyzeModuleGraph(entries);
  16045. // Each chunk is identified by its position in this array
  16046. const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  16047. const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(allEntries, chunkAtoms);
  16048. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  16049. // If we no longer want this, we should make a copy here.
  16050. const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  16051. // This mutates the dependentEntries in chunkAtoms
  16052. removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry);
  16053. const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
  16054. chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
  16055. alias: null,
  16056. modules
  16057. })));
  16058. return chunkDefinitions;
  16059. }
  16060. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  16061. const chunkDefinitions = [];
  16062. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  16063. const manualChunkModulesByAlias = Object.create(null);
  16064. for (const [entry, alias] of manualChunkAliasByEntry) {
  16065. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] ||= []), modulesInManualChunks);
  16066. }
  16067. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  16068. chunkDefinitions.push({ alias, modules });
  16069. }
  16070. return { chunkDefinitions, modulesInManualChunks };
  16071. }
  16072. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  16073. const modulesToHandle = new Set([entry]);
  16074. for (const module of modulesToHandle) {
  16075. modulesInManualChunks.add(module);
  16076. manualChunkModules.push(module);
  16077. for (const dependency of module.dependencies) {
  16078. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  16079. modulesToHandle.add(dependency);
  16080. }
  16081. }
  16082. }
  16083. }
  16084. function analyzeModuleGraph(entries) {
  16085. const dynamicEntryModules = new Set();
  16086. const dependentEntriesByModule = new Map();
  16087. const dynamicImportModulesByEntry = [];
  16088. const allEntriesSet = new Set(entries);
  16089. let entryIndex = 0;
  16090. for (const currentEntry of allEntriesSet) {
  16091. const dynamicImportsForCurrentEntry = new Set();
  16092. dynamicImportModulesByEntry.push(dynamicImportsForCurrentEntry);
  16093. const modulesToHandle = new Set([currentEntry]);
  16094. for (const module of modulesToHandle) {
  16095. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  16096. for (const dependency of module.getDependenciesToBeIncluded()) {
  16097. if (!(dependency instanceof ExternalModule)) {
  16098. modulesToHandle.add(dependency);
  16099. }
  16100. }
  16101. for (const { resolution } of module.dynamicImports) {
  16102. if (resolution instanceof Module &&
  16103. resolution.includedDynamicImporters.length > 0 &&
  16104. !allEntriesSet.has(resolution)) {
  16105. dynamicEntryModules.add(resolution);
  16106. allEntriesSet.add(resolution);
  16107. dynamicImportsForCurrentEntry.add(resolution);
  16108. }
  16109. }
  16110. for (const dependency of module.implicitlyLoadedBefore) {
  16111. if (!allEntriesSet.has(dependency)) {
  16112. dynamicEntryModules.add(dependency);
  16113. allEntriesSet.add(dependency);
  16114. }
  16115. }
  16116. }
  16117. entryIndex++;
  16118. }
  16119. const allEntries = [...allEntriesSet];
  16120. const { dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry);
  16121. return {
  16122. allEntries,
  16123. dependentEntriesByModule,
  16124. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries),
  16125. dynamicImportsByEntry
  16126. };
  16127. }
  16128. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry) {
  16129. const entryIndexByModule = new Map();
  16130. const dynamicEntries = new Set();
  16131. for (const [entryIndex, entry] of allEntries.entries()) {
  16132. entryIndexByModule.set(entry, entryIndex);
  16133. if (dynamicEntryModules.has(entry)) {
  16134. dynamicEntries.add(entryIndex);
  16135. }
  16136. }
  16137. const dynamicImportsByEntry = [];
  16138. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  16139. const dynamicImports = new Set();
  16140. for (const dynamicEntry of dynamicImportModules) {
  16141. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  16142. }
  16143. dynamicImportsByEntry.push(dynamicImports);
  16144. }
  16145. return { dynamicEntries, dynamicImportsByEntry };
  16146. }
  16147. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries) {
  16148. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  16149. for (const dynamicEntryIndex of dynamicEntries) {
  16150. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  16151. const dynamicEntry = allEntries[dynamicEntryIndex];
  16152. for (const importer of concatLazy([
  16153. dynamicEntry.includedDynamicImporters,
  16154. dynamicEntry.implicitlyLoadedAfter
  16155. ])) {
  16156. for (const entry of dependentEntriesByModule.get(importer)) {
  16157. dynamicallyDependentEntries.add(entry);
  16158. }
  16159. }
  16160. }
  16161. return dynamicallyDependentEntriesByDynamicEntry;
  16162. }
  16163. function getChunksWithSameDependentEntries(modulesWithDependentEntries) {
  16164. const chunkModules = Object.create(null);
  16165. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  16166. let chunkSignature = 0n;
  16167. for (const entryIndex of dependentEntries) {
  16168. chunkSignature |= 1n << BigInt(entryIndex);
  16169. }
  16170. (chunkModules[String(chunkSignature)] ||= {
  16171. dependentEntries: new Set(dependentEntries),
  16172. modules: []
  16173. }).modules.push(...modules);
  16174. }
  16175. return Object.values(chunkModules);
  16176. }
  16177. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  16178. for (const [module, dependentEntries] of dependentEntriesByModule) {
  16179. if (!modulesInManualChunks.has(module)) {
  16180. yield { dependentEntries, modules: [module] };
  16181. }
  16182. }
  16183. }
  16184. function getStaticDependencyAtomsByEntry(allEntries, chunkAtoms) {
  16185. // The indices correspond to the indices in allEntries. The atoms correspond
  16186. // to bits in the bigint values where chunk 0 is the lowest bit.
  16187. const staticDependencyAtomsByEntry = allEntries.map(() => 0n);
  16188. // This toggles the bits for each atom that is a dependency of an entry
  16189. let atomMask = 1n;
  16190. for (const { dependentEntries } of chunkAtoms) {
  16191. for (const entryIndex of dependentEntries) {
  16192. staticDependencyAtomsByEntry[entryIndex] |= atomMask;
  16193. }
  16194. atomMask <<= 1n;
  16195. }
  16196. return staticDependencyAtomsByEntry;
  16197. }
  16198. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  16199. function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  16200. // Dynamic entries have all atoms as already loaded initially because we then
  16201. // intersect with the static dependency atoms of all dynamic importers.
  16202. // Static entries cannot have already loaded atoms.
  16203. const alreadyLoadedAtomsByEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  16204. for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByDynamicEntry) {
  16205. // We delete here so that they can be added again if necessary to be handled
  16206. // again by the loop
  16207. dynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  16208. const knownLoadedAtoms = alreadyLoadedAtomsByEntry[dynamicEntryIndex];
  16209. let updatedLoadedAtoms = knownLoadedAtoms;
  16210. for (const entryIndex of dynamicallyDependentEntries) {
  16211. updatedLoadedAtoms &=
  16212. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  16213. }
  16214. // If the knownLoadedAtoms changed, all dependent dynamic entries need to be
  16215. // updated again
  16216. if (updatedLoadedAtoms !== knownLoadedAtoms) {
  16217. alreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
  16218. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  16219. // If this adds an entry that was deleted before, it will be handled
  16220. // again. This is the reason why we delete every entry from this map
  16221. // that we processed.
  16222. getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  16223. }
  16224. }
  16225. }
  16226. return alreadyLoadedAtomsByEntry;
  16227. }
  16228. /**
  16229. * This removes all unnecessary dynamic entries from the dependentEntries in its
  16230. * first argument if a chunk is already loaded without that entry.
  16231. */
  16232. function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry) {
  16233. // Remove entries from dependent entries if a chunk is already loaded without
  16234. // that entry.
  16235. let chunkMask = 1n;
  16236. for (const { dependentEntries } of chunkAtoms) {
  16237. for (const entryIndex of dependentEntries) {
  16238. if ((alreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === chunkMask) {
  16239. dependentEntries.delete(entryIndex);
  16240. }
  16241. }
  16242. chunkMask <<= 1n;
  16243. }
  16244. }
  16245. function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
  16246. const chunksBySignature = Object.create(null);
  16247. const chunkByModule = new Map();
  16248. const sizeByAtom = [];
  16249. let sideEffectAtoms = 0n;
  16250. let atomMask = 1n;
  16251. for (const { dependentEntries, modules } of chunkAtoms) {
  16252. let chunkSignature = 0n;
  16253. let correlatedAtoms = -1n;
  16254. for (const entryIndex of dependentEntries) {
  16255. chunkSignature |= 1n << BigInt(entryIndex);
  16256. // Correlated atoms are the atoms that are guaranteed to be loaded as
  16257. // well when a given atom is loaded. It is the intersection of the already
  16258. // loaded modules of each chunk merged with its static dependencies.
  16259. correlatedAtoms &=
  16260. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  16261. }
  16262. const chunk = (chunksBySignature[String(chunkSignature)] ||= {
  16263. containedAtoms: 0n,
  16264. correlatedAtoms,
  16265. dependencies: new Set(),
  16266. dependentChunks: new Set(),
  16267. dependentEntries: new Set(dependentEntries),
  16268. modules: [],
  16269. pure: true,
  16270. size: 0
  16271. });
  16272. let atomSize = 0;
  16273. let pure = true;
  16274. for (const module of modules) {
  16275. chunkByModule.set(module, chunk);
  16276. // Unfortunately, we cannot take tree-shaking into account here because
  16277. // rendering did not happen yet, but we can detect empty modules
  16278. if (module.isIncluded()) {
  16279. pure &&= !module.hasEffects();
  16280. // we use a trivial size for the default minChunkSize to improve
  16281. // performance
  16282. atomSize += minChunkSize > 1 ? module.estimateSize() : 1;
  16283. }
  16284. }
  16285. if (!pure) {
  16286. sideEffectAtoms |= atomMask;
  16287. }
  16288. sizeByAtom.push(atomSize);
  16289. chunk.containedAtoms |= atomMask;
  16290. chunk.modules.push(...modules);
  16291. chunk.pure &&= pure;
  16292. chunk.size += atomSize;
  16293. atomMask <<= 1n;
  16294. }
  16295. const chunks = Object.values(chunksBySignature);
  16296. sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
  16297. return { chunks, sideEffectAtoms, sizeByAtom };
  16298. }
  16299. function addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, nextAvailableAtomMask) {
  16300. const signatureByExternalModule = new Map();
  16301. let externalSideEffectAtoms = 0n;
  16302. for (const chunk of chunks) {
  16303. const { dependencies, modules } = chunk;
  16304. for (const module of modules) {
  16305. for (const dependency of module.getDependenciesToBeIncluded()) {
  16306. if (dependency instanceof ExternalModule) {
  16307. if (dependency.info.moduleSideEffects) {
  16308. const signature = getOrCreate(signatureByExternalModule, dependency, () => {
  16309. const signature = nextAvailableAtomMask;
  16310. nextAvailableAtomMask <<= 1n;
  16311. externalSideEffectAtoms |= signature;
  16312. return signature;
  16313. });
  16314. chunk.containedAtoms |= signature;
  16315. chunk.correlatedAtoms |= signature;
  16316. }
  16317. }
  16318. else {
  16319. const dependencyChunk = chunkByModule.get(dependency);
  16320. if (dependencyChunk && dependencyChunk !== chunk) {
  16321. dependencies.add(dependencyChunk);
  16322. dependencyChunk.dependentChunks.add(chunk);
  16323. }
  16324. }
  16325. }
  16326. }
  16327. }
  16328. return externalSideEffectAtoms;
  16329. }
  16330. /**
  16331. * This function tries to get rid of small chunks by merging them with other
  16332. * chunks.
  16333. *
  16334. * We can only merge chunks safely if after the merge, loading any entry point
  16335. * in any allowed order will not trigger side effects that should not have been
  16336. * triggered. While side effects are usually things like global function calls,
  16337. * global variable mutations or potentially thrown errors, details do not
  16338. * matter here, and we just discern chunks without side effects (pure chunks)
  16339. * from other chunks.
  16340. *
  16341. * As a first step, we assign each pre-generated chunk with side effects a
  16342. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  16343. *
  16344. * Now to determine the side effects of loading a chunk, one also has to take
  16345. * the side effects of its dependencies into account. So if A depends on B
  16346. * (A -> B) and both have side effects, loading A triggers effects AB.
  16347. *
  16348. * Now from the previous step we know that each chunk is uniquely determine by
  16349. * the entry points that depend on it and cause it to load, which we will call
  16350. * its dependent entry points.
  16351. *
  16352. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  16353. * Starting from that idea, we can determine a set of chunks—and thus a set
  16354. * of side effects—that must have been triggered if a certain chunk has been
  16355. * loaded. Basically, it is the intersection of all chunks loaded by the
  16356. * dependent entry points of a given chunk. We call the corresponding side
  16357. * effects the correlated side effects of that chunk.
  16358. *
  16359. * Example:
  16360. * X -> ABC, Y -> ADE, A-> F, B -> D
  16361. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  16362. * The intersection is ADF. So we know that when A is loaded, D and F must also
  16363. * be in memory even though neither D nor A is a dependency of the other.
  16364. * If all have side effects, we call ADF the correlated side effects of A. The
  16365. * correlated side effects need to remain constant when merging chunks.
  16366. *
  16367. * In contrast, we have the dependency side effects of A, which represents
  16368. * the side effects we trigger if we directly load A. In this example, the
  16369. * dependency side effects are AF.
  16370. * For entry chunks, dependency and correlated side effects are the same.
  16371. *
  16372. * With these concepts, merging chunks is allowed if the correlated side
  16373. * effects of each entry do not change. Thus, we are allowed to merge two
  16374. * chunks if
  16375. *
  16376. * a) the dependency side effects of each chunk are a subset of the correlated
  16377. * side effects of the other chunk, so no additional side effects are
  16378. * triggered for any entry, or
  16379. * b) The dependent entry points of chunk A are a subset of the dependent entry
  16380. * points of chunk B while the dependency side effects of A are a subset of
  16381. * the correlated side effects of B. Because in that scenario, whenever A is
  16382. * loaded, B is loaded as well. But there are cases when B is loaded where A
  16383. * is not loaded. So if we merge the chunks, all dependency side effects of
  16384. * A will be added to the correlated side effects of B, and as the latter is
  16385. * not allowed to change, the former need to be a subset of the latter.
  16386. *
  16387. * Another consideration when merging small chunks into other chunks is to
  16388. * avoid
  16389. * that too much additional code is loaded. This is achieved when the dependent
  16390. * entries of the small chunk are a subset of the dependent entries of the
  16391. * other
  16392. * chunk. Because then when the small chunk is loaded, the other chunk was
  16393. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  16394. * additional size of the small chunk is loaded unnecessarily.
  16395. *
  16396. * So the algorithm performs merges in two passes:
  16397. *
  16398. * 1. First we try to merge small chunks A only into other chunks B if the
  16399. * dependent entries of A are a subset of the dependent entries of B and the
  16400. * dependency side effects of A are a subset of the correlated side effects
  16401. * of B.
  16402. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  16403. * following the rule (a), starting with the smallest chunks to look for
  16404. * possible merge targets.
  16405. */
  16406. function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log) {
  16407. timeStart('optimize chunks', 3);
  16408. const chunkPartition = getPartitionedChunks(chunks, minChunkSize);
  16409. if (!chunkPartition) {
  16410. timeEnd('optimize chunks', 3);
  16411. return chunks; // the actual modules
  16412. }
  16413. minChunkSize > 1 &&
  16414. log('info', logOptimizeChunkStatus(chunks.length, chunkPartition.small.size, 'Initially'));
  16415. mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
  16416. minChunkSize > 1 &&
  16417. log('info', logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  16418. timeEnd('optimize chunks', 3);
  16419. return [...chunkPartition.small, ...chunkPartition.big];
  16420. }
  16421. function getPartitionedChunks(chunks, minChunkSize) {
  16422. const smallChunks = [];
  16423. const bigChunks = [];
  16424. for (const chunk of chunks) {
  16425. (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
  16426. }
  16427. if (smallChunks.length === 0) {
  16428. return null;
  16429. }
  16430. smallChunks.sort(compareChunkSize);
  16431. bigChunks.sort(compareChunkSize);
  16432. return {
  16433. big: new Set(bigChunks),
  16434. small: new Set(smallChunks)
  16435. };
  16436. }
  16437. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  16438. return sizeA - sizeB;
  16439. }
  16440. function mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom) {
  16441. const { small } = chunkPartition;
  16442. for (const mergedChunk of small) {
  16443. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, sideEffectAtoms, sizeByAtom,
  16444. // In the default case, we do not accept size increases
  16445. minChunkSize <= 1 ? 1 : Infinity);
  16446. if (bestTargetChunk) {
  16447. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  16448. small.delete(mergedChunk);
  16449. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  16450. bestTargetChunk.modules.push(...modules);
  16451. bestTargetChunk.size += size;
  16452. bestTargetChunk.pure &&= pure;
  16453. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  16454. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  16455. bestTargetChunk.containedAtoms |= containedAtoms;
  16456. for (const entry of mergedChunk.dependentEntries) {
  16457. dependentEntries.add(entry);
  16458. }
  16459. for (const dependency of mergedChunk.dependencies) {
  16460. dependencies.add(dependency);
  16461. dependency.dependentChunks.delete(mergedChunk);
  16462. dependency.dependentChunks.add(bestTargetChunk);
  16463. }
  16464. for (const dependentChunk of mergedChunk.dependentChunks) {
  16465. dependentChunks.add(dependentChunk);
  16466. dependentChunk.dependencies.delete(mergedChunk);
  16467. dependentChunk.dependencies.add(bestTargetChunk);
  16468. }
  16469. dependencies.delete(bestTargetChunk);
  16470. dependentChunks.delete(bestTargetChunk);
  16471. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  16472. }
  16473. }
  16474. }
  16475. function findBestMergeTarget(mergedChunk, { big, small }, sideEffectAtoms, sizeByAtom, smallestAdditionalSize) {
  16476. let bestTargetChunk = null;
  16477. // In the default case, we do not accept size increases
  16478. for (const targetChunk of concatLazy([small, big])) {
  16479. if (mergedChunk === targetChunk)
  16480. continue;
  16481. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  16482. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  16483. bestTargetChunk = targetChunk;
  16484. if (additionalSizeAfterMerge === 0)
  16485. break;
  16486. smallestAdditionalSize = additionalSizeAfterMerge;
  16487. }
  16488. }
  16489. return bestTargetChunk;
  16490. }
  16491. /**
  16492. * Determine the additional unused code size that would be added by merging the
  16493. * two chunks. This is not an exact measurement but rather an upper bound. If
  16494. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  16495. * is returned.
  16496. * Merging will not produce cycles if none of the direct non-merged
  16497. * dependencies of a chunk have the other chunk as a transitive dependency.
  16498. */
  16499. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  16500. // The maximum additional unused code size allowed to be added by the merge,
  16501. // taking dependencies into account, needs to be below this number
  16502. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  16503. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  16504. return firstSize < currentAdditionalSize
  16505. ? firstSize +
  16506. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  16507. : Infinity;
  16508. }
  16509. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  16510. const { correlatedAtoms } = dependencyChunk;
  16511. let dependencyAtoms = dependentChunk.containedAtoms;
  16512. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  16513. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  16514. return Infinity;
  16515. }
  16516. const chunksToCheck = new Set(dependentChunk.dependencies);
  16517. for (const { dependencies, containedAtoms } of chunksToCheck) {
  16518. dependencyAtoms |= containedAtoms;
  16519. const containedSideEffects = containedAtoms & sideEffectAtoms;
  16520. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  16521. return Infinity;
  16522. }
  16523. for (const dependency of dependencies) {
  16524. if (dependency === dependencyChunk) {
  16525. return Infinity;
  16526. }
  16527. chunksToCheck.add(dependency);
  16528. }
  16529. }
  16530. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  16531. }
  16532. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  16533. let size = 0;
  16534. let atomIndex = 0;
  16535. let atomSignature = 1n;
  16536. const { length } = sizeByAtom;
  16537. for (; atomIndex < length; atomIndex++) {
  16538. if ((atoms & atomSignature) === atomSignature) {
  16539. size += sizeByAtom[atomIndex];
  16540. }
  16541. atomSignature <<= 1n;
  16542. if (size >= currentAdditionalSize) {
  16543. return Infinity;
  16544. }
  16545. }
  16546. return size;
  16547. }
  16548. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  16549. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  16550. }
  16551. // ported from https://github.com/substack/node-commondir
  16552. function commondir(files) {
  16553. if (files.length === 0)
  16554. return '/';
  16555. if (files.length === 1)
  16556. return dirname(files[0]);
  16557. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  16558. const pathSegments = file.split(/\/+|\\+/);
  16559. let index;
  16560. for (index = 0; commonSegments[index] === pathSegments[index] &&
  16561. index < Math.min(commonSegments.length, pathSegments.length); index++)
  16562. ;
  16563. return commonSegments.slice(0, index);
  16564. }, files[0].split(/\/+|\\+/));
  16565. // Windows correctly handles paths with forward-slashes
  16566. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  16567. }
  16568. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  16569. function sortByExecutionOrder(units) {
  16570. units.sort(compareExecIndex);
  16571. }
  16572. // This process is currently faulty in so far as it only takes the first entry
  16573. // module into account and assumes that dynamic imports are imported in a
  16574. // certain order.
  16575. // A better algorithm would follow every possible execution path and mark which
  16576. // modules are executed before or after which other modules. THen the chunking
  16577. // would need to take care that in each chunk, all modules are always executed
  16578. // in the same sequence.
  16579. function analyseModuleExecution(entryModules) {
  16580. let nextExecIndex = 0;
  16581. const cyclePaths = [];
  16582. const analysedModules = new Set();
  16583. const dynamicImports = new Set();
  16584. const parents = new Map();
  16585. const orderedModules = [];
  16586. const analyseModule = (module) => {
  16587. if (module instanceof Module) {
  16588. for (const dependency of module.dependencies) {
  16589. if (parents.has(dependency)) {
  16590. if (!analysedModules.has(dependency)) {
  16591. cyclePaths.push(getCyclePath(dependency, module, parents));
  16592. }
  16593. continue;
  16594. }
  16595. parents.set(dependency, module);
  16596. analyseModule(dependency);
  16597. }
  16598. for (const dependency of module.implicitlyLoadedBefore) {
  16599. dynamicImports.add(dependency);
  16600. }
  16601. for (const { resolution } of module.dynamicImports) {
  16602. if (resolution instanceof Module) {
  16603. dynamicImports.add(resolution);
  16604. }
  16605. }
  16606. orderedModules.push(module);
  16607. }
  16608. module.execIndex = nextExecIndex++;
  16609. analysedModules.add(module);
  16610. };
  16611. for (const currentEntry of entryModules) {
  16612. if (!parents.has(currentEntry)) {
  16613. parents.set(currentEntry, null);
  16614. analyseModule(currentEntry);
  16615. }
  16616. }
  16617. for (const currentEntry of dynamicImports) {
  16618. if (!parents.has(currentEntry)) {
  16619. parents.set(currentEntry, null);
  16620. analyseModule(currentEntry);
  16621. }
  16622. }
  16623. return { cyclePaths, orderedModules };
  16624. }
  16625. function getCyclePath(module, parent, parents) {
  16626. const cycleSymbol = Symbol(module.id);
  16627. const path = [module.id];
  16628. let nextModule = parent;
  16629. module.cycles.add(cycleSymbol);
  16630. while (nextModule !== module) {
  16631. nextModule.cycles.add(cycleSymbol);
  16632. path.push(nextModule.id);
  16633. nextModule = parents.get(nextModule);
  16634. }
  16635. path.push(path[0]);
  16636. path.reverse();
  16637. return path;
  16638. }
  16639. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  16640. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  16641. const cnst = constBindings ? 'const' : 'var';
  16642. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  16643. const getFunctionIntro = arrowFunctions
  16644. ? (parameters, { isAsync, name }) => {
  16645. const singleParameter = parameters.length === 1;
  16646. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  16647. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  16648. }
  16649. : getNonArrowFunctionIntro;
  16650. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  16651. `${getFunctionIntro(parameters, {
  16652. isAsync: false,
  16653. name
  16654. })}${arrowFunctions
  16655. ? lineBreakIndent
  16656. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  16657. : ''
  16658. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  16659. arrowFunctions
  16660. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  16661. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  16662. ];
  16663. const isValidPropertyName = reservedNamesAsProps
  16664. ? (name) => VALID_IDENTIFIER_REGEXP.test(name)
  16665. : (name) => !RESERVED_NAMES.has(name) && VALID_IDENTIFIER_REGEXP.test(name);
  16666. return {
  16667. _,
  16668. cnst,
  16669. getDirectReturnFunction,
  16670. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  16671. const [left, right] = getDirectReturnFunction(parameters, {
  16672. functionReturn: true,
  16673. lineBreakIndent: null,
  16674. name: null
  16675. });
  16676. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  16677. },
  16678. getFunctionIntro,
  16679. getNonArrowFunctionIntro,
  16680. getObject(fields, { lineBreakIndent }) {
  16681. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  16682. return `{${fields
  16683. .map(([key, value]) => {
  16684. if (key === null)
  16685. return `${prefix}${value}`;
  16686. const keyInObject = stringifyObjectKeyIfNeeded(key);
  16687. return key === value && objectShorthand && key === keyInObject
  16688. ? prefix + key
  16689. : `${prefix}${keyInObject}:${_}${value}`;
  16690. })
  16691. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  16692. },
  16693. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  16694. n,
  16695. s
  16696. };
  16697. }
  16698. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  16699. class Source {
  16700. constructor(filename, content) {
  16701. this.isOriginal = true;
  16702. this.filename = filename;
  16703. this.content = content;
  16704. }
  16705. traceSegment(line, column, name) {
  16706. return { column, line, name, source: this };
  16707. }
  16708. }
  16709. class Link {
  16710. constructor(map, sources) {
  16711. this.sources = sources;
  16712. this.names = map.names;
  16713. this.mappings = map.mappings;
  16714. }
  16715. traceMappings() {
  16716. const sources = [];
  16717. const sourceIndexMap = new Map();
  16718. const sourcesContent = [];
  16719. const names = [];
  16720. const nameIndexMap = new Map();
  16721. const mappings = [];
  16722. for (const line of this.mappings) {
  16723. const tracedLine = [];
  16724. for (const segment of line) {
  16725. if (segment.length === 1)
  16726. continue;
  16727. const source = this.sources[segment[1]];
  16728. if (!source)
  16729. continue;
  16730. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  16731. if (traced) {
  16732. const { column, line, name, source: { content, filename } } = traced;
  16733. let sourceIndex = sourceIndexMap.get(filename);
  16734. if (sourceIndex === undefined) {
  16735. sourceIndex = sources.length;
  16736. sources.push(filename);
  16737. sourceIndexMap.set(filename, sourceIndex);
  16738. sourcesContent[sourceIndex] = content;
  16739. }
  16740. else if (sourcesContent[sourceIndex] == null) {
  16741. sourcesContent[sourceIndex] = content;
  16742. }
  16743. else if (content != null && sourcesContent[sourceIndex] !== content) {
  16744. return error(logConflictingSourcemapSources(filename));
  16745. }
  16746. const tracedSegment = [segment[0], sourceIndex, line, column];
  16747. if (name) {
  16748. let nameIndex = nameIndexMap.get(name);
  16749. if (nameIndex === undefined) {
  16750. nameIndex = names.length;
  16751. names.push(name);
  16752. nameIndexMap.set(name, nameIndex);
  16753. }
  16754. tracedSegment[4] = nameIndex;
  16755. }
  16756. tracedLine.push(tracedSegment);
  16757. }
  16758. }
  16759. mappings.push(tracedLine);
  16760. }
  16761. return { mappings, names, sources, sourcesContent };
  16762. }
  16763. traceSegment(line, column, name) {
  16764. const segments = this.mappings[line];
  16765. if (!segments)
  16766. return null;
  16767. // binary search through segments for the given column
  16768. let searchStart = 0;
  16769. let searchEnd = segments.length - 1;
  16770. while (searchStart <= searchEnd) {
  16771. const m = (searchStart + searchEnd) >> 1;
  16772. const segment = segments[m];
  16773. // If a sourcemap does not have sufficient resolution to contain a
  16774. // necessary mapping, e.g. because it only contains line information, we
  16775. // use the best approximation we could find
  16776. if (segment[0] === column || searchStart === searchEnd) {
  16777. if (segment.length == 1)
  16778. return null;
  16779. const source = this.sources[segment[1]];
  16780. if (!source)
  16781. return null;
  16782. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  16783. }
  16784. if (segment[0] > column) {
  16785. searchEnd = m - 1;
  16786. }
  16787. else {
  16788. searchStart = m + 1;
  16789. }
  16790. }
  16791. return null;
  16792. }
  16793. }
  16794. function getLinkMap(log) {
  16795. return function linkMap(source, map) {
  16796. if (!map.missing) {
  16797. return new Link(map, [source]);
  16798. }
  16799. log(LOGLEVEL_WARN, logSourcemapBroken(map.plugin));
  16800. return new Link({
  16801. mappings: [],
  16802. names: []
  16803. }, [source]);
  16804. };
  16805. }
  16806. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  16807. let source;
  16808. if (originalSourcemap) {
  16809. const sources = originalSourcemap.sources;
  16810. const sourcesContent = originalSourcemap.sourcesContent || [];
  16811. const directory = dirname(id) || '.';
  16812. const sourceRoot = originalSourcemap.sourceRoot || '.';
  16813. const baseSources = sources.map((source, index) => new Source(resolve$1(directory, sourceRoot, source), sourcesContent[index]));
  16814. source = new Link(originalSourcemap, baseSources);
  16815. }
  16816. else {
  16817. source = new Source(id, originalCode);
  16818. }
  16819. return sourcemapChain.reduce(linkMap, source);
  16820. }
  16821. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  16822. const linkMap = getLinkMap(log);
  16823. const moduleSources = modules
  16824. .filter(module => !module.excludeFromSourcemap)
  16825. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  16826. const link = new Link(map, moduleSources);
  16827. const source = bundleSourcemapChain.reduce(linkMap, link);
  16828. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  16829. if (file) {
  16830. const directory = dirname(file);
  16831. sources = sources.map((source) => relative(directory, source));
  16832. file = basename(file);
  16833. }
  16834. sourcesContent = (excludeContent ? null : sourcesContent);
  16835. for (const module of modules) {
  16836. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  16837. }
  16838. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  16839. }
  16840. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  16841. if (sourcemapChain.length === 0) {
  16842. return originalSourcemap;
  16843. }
  16844. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  16845. const map = source.traceMappings();
  16846. return decodedSourcemap({ version: 3, ...map });
  16847. }
  16848. let textEncoder;
  16849. const getHash64 = input => xxhashBase64Url(ensureBuffer(input));
  16850. const getHash36 = input => xxhashBase36(ensureBuffer(input));
  16851. const getHash16 = input => xxhashBase16(ensureBuffer(input));
  16852. const hasherByType = {
  16853. base36: getHash36,
  16854. base64: getHash64,
  16855. hex: getHash16
  16856. };
  16857. function ensureBuffer(input) {
  16858. if (typeof input === 'string') {
  16859. if (typeof Buffer === 'undefined') {
  16860. textEncoder ??= new TextEncoder();
  16861. return textEncoder.encode(input);
  16862. }
  16863. return Buffer.from(input);
  16864. }
  16865. return input;
  16866. }
  16867. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  16868. // this for an actual sourceMappingURL
  16869. let SOURCEMAPPING_URL = 'sourceMa';
  16870. SOURCEMAPPING_URL += 'ppingURL';
  16871. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  16872. timeStart('render chunks', 2);
  16873. reserveEntryChunksInBundle(chunks);
  16874. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  16875. timeEnd('render chunks', 2);
  16876. timeStart('transform chunks', 2);
  16877. const getHash = hasherByType[outputOptions.hashCharacters];
  16878. const chunkGraph = getChunkGraph(chunks);
  16879. const { initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, renderedChunksByPlaceholder, hashDependenciesByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
  16880. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, bundle, getHash);
  16881. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  16882. timeEnd('transform chunks', 2);
  16883. }
  16884. function reserveEntryChunksInBundle(chunks) {
  16885. for (const chunk of chunks) {
  16886. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  16887. // reserves name in bundle as side effect if it does not contain a hash
  16888. chunk.getPreliminaryFileName();
  16889. }
  16890. }
  16891. }
  16892. function getChunkGraph(chunks) {
  16893. return Object.fromEntries(chunks.map(chunk => {
  16894. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  16895. return [renderedChunkInfo.fileName, renderedChunkInfo];
  16896. }));
  16897. }
  16898. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  16899. let map = null;
  16900. const sourcemapChain = [];
  16901. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  16902. if (result == null)
  16903. return code;
  16904. if (typeof result === 'string')
  16905. result = {
  16906. code: result,
  16907. map: undefined
  16908. };
  16909. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  16910. if (result.map !== null) {
  16911. const map = decodedSourcemap(result.map);
  16912. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  16913. }
  16914. return result.code;
  16915. });
  16916. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  16917. if (!compact && code[code.length - 1] !== '\n')
  16918. code += '\n';
  16919. if (sourcemap) {
  16920. timeStart('sourcemaps', 3);
  16921. let resultingFile;
  16922. if (file)
  16923. resultingFile = resolve$1(sourcemapFile || file);
  16924. else if (dir)
  16925. resultingFile = resolve$1(dir, fileName);
  16926. else
  16927. resultingFile = resolve$1(fileName);
  16928. const decodedMap = magicString.generateDecodedMap({});
  16929. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  16930. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  16931. let sourcePath = map.sources[sourcesIndex];
  16932. const sourcemapPath = `${resultingFile}.map`;
  16933. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  16934. if (typeof ignoreList !== 'boolean') {
  16935. error(logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  16936. }
  16937. if (ignoreList) {
  16938. if (map.x_google_ignoreList === undefined) {
  16939. map.x_google_ignoreList = [];
  16940. }
  16941. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  16942. map.x_google_ignoreList.push(sourcesIndex);
  16943. }
  16944. }
  16945. if (sourcemapPathTransform) {
  16946. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  16947. if (typeof sourcePath !== 'string') {
  16948. error(logFailedValidation(`sourcemapPathTransform function must return a string.`));
  16949. }
  16950. }
  16951. map.sources[sourcesIndex] = normalize(sourcePath);
  16952. }
  16953. timeEnd('sourcemaps', 3);
  16954. }
  16955. return {
  16956. code,
  16957. map
  16958. };
  16959. }
  16960. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
  16961. const nonHashedChunksWithPlaceholders = [];
  16962. const renderedChunksByPlaceholder = new Map();
  16963. const hashDependenciesByPlaceholder = new Map();
  16964. const initialHashesByPlaceholder = new Map();
  16965. const placeholders = new Set();
  16966. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  16967. if (hashPlaceholder)
  16968. placeholders.add(hashPlaceholder);
  16969. }
  16970. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  16971. const transformedChunk = {
  16972. chunk,
  16973. fileName,
  16974. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  16975. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  16976. };
  16977. const { code, map } = transformedChunk;
  16978. if (hashPlaceholder) {
  16979. // To create a reproducible content-only hash, all placeholders are
  16980. // replaced with the same value before hashing
  16981. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  16982. let contentToHash = transformedCode;
  16983. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  16984. if (pluginHash) {
  16985. augmentation += pluginHash;
  16986. }
  16987. return augmentation;
  16988. });
  16989. if (hashAugmentation) {
  16990. contentToHash += hashAugmentation;
  16991. }
  16992. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  16993. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  16994. containedPlaceholders,
  16995. contentHash: getHash(contentToHash)
  16996. });
  16997. }
  16998. else {
  16999. nonHashedChunksWithPlaceholders.push(transformedChunk);
  17000. }
  17001. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  17002. if (map && sourcemapHashPlaceholder) {
  17003. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  17004. }
  17005. }));
  17006. return {
  17007. hashDependenciesByPlaceholder,
  17008. initialHashesByPlaceholder,
  17009. nonHashedChunksWithPlaceholders,
  17010. renderedChunksByPlaceholder
  17011. };
  17012. }
  17013. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, bundle, getHash) {
  17014. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  17015. for (const [placeholder, { fileName }] of renderedChunksByPlaceholder) {
  17016. let contentToHash = '';
  17017. const hashDependencyPlaceholders = new Set([placeholder]);
  17018. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  17019. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  17020. contentToHash += contentHash;
  17021. for (const containedPlaceholder of containedPlaceholders) {
  17022. // When looping over a map, setting an entry only causes a new iteration if the key is new
  17023. hashDependencyPlaceholders.add(containedPlaceholder);
  17024. }
  17025. }
  17026. let finalFileName;
  17027. let finalHash;
  17028. do {
  17029. // In case of a hash collision, create a hash of the hash
  17030. if (finalHash) {
  17031. contentToHash = finalHash;
  17032. }
  17033. finalHash = getHash(contentToHash).slice(0, placeholder.length);
  17034. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  17035. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  17036. bundle[finalFileName] = FILE_PLACEHOLDER;
  17037. hashesByPlaceholder.set(placeholder, finalHash);
  17038. }
  17039. return hashesByPlaceholder;
  17040. }
  17041. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  17042. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  17043. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  17044. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  17045. let finalSourcemapFileName = null;
  17046. if (map) {
  17047. finalSourcemapFileName = sourcemapFileName
  17048. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  17049. : `${finalFileName}.map`;
  17050. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  17051. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  17052. }
  17053. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  17054. }
  17055. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  17056. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  17057. let finalSourcemapFileName = null;
  17058. if (map) {
  17059. finalSourcemapFileName = sourcemapFileName
  17060. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  17061. : `${fileName}.map`;
  17062. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  17063. }
  17064. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  17065. }
  17066. }
  17067. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  17068. let url;
  17069. if (sourcemap === 'inline') {
  17070. url = map.toUrl();
  17071. }
  17072. else {
  17073. const sourcemapFileName = basename(fileName);
  17074. url = sourcemapBaseUrl
  17075. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  17076. : sourcemapFileName;
  17077. pluginDriver.emitFile({ fileName, source: map.toString(), type: 'asset' });
  17078. }
  17079. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  17080. }
  17081. class Bundle {
  17082. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  17083. this.outputOptions = outputOptions;
  17084. this.unsetOptions = unsetOptions;
  17085. this.inputOptions = inputOptions;
  17086. this.pluginDriver = pluginDriver;
  17087. this.graph = graph;
  17088. this.facadeChunkByModule = new Map();
  17089. this.includedNamespaces = new Set();
  17090. }
  17091. async generate(isWrite) {
  17092. timeStart('GENERATE', 1);
  17093. const outputBundleBase = Object.create(null);
  17094. const outputBundle = getOutputBundle(outputBundleBase);
  17095. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  17096. try {
  17097. timeStart('initialize render', 2);
  17098. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  17099. timeEnd('initialize render', 2);
  17100. timeStart('generate chunks', 2);
  17101. const getHashPlaceholder = getHashPlaceholderGenerator();
  17102. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  17103. if (chunks.length > 1) {
  17104. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  17105. }
  17106. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  17107. for (const chunk of chunks) {
  17108. chunk.generateExports();
  17109. }
  17110. timeEnd('generate chunks', 2);
  17111. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  17112. }
  17113. catch (error_) {
  17114. await this.pluginDriver.hookParallel('renderError', [error_]);
  17115. throw error_;
  17116. }
  17117. removeUnreferencedAssets(outputBundle);
  17118. timeStart('generate bundle', 2);
  17119. await this.pluginDriver.hookSeq('generateBundle', [
  17120. this.outputOptions,
  17121. outputBundle,
  17122. isWrite
  17123. ]);
  17124. this.finaliseAssets(outputBundle);
  17125. timeEnd('generate bundle', 2);
  17126. timeEnd('GENERATE', 1);
  17127. return outputBundleBase;
  17128. }
  17129. async addManualChunks(manualChunks) {
  17130. const manualChunkAliasByEntry = new Map();
  17131. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  17132. alias,
  17133. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  17134. })));
  17135. for (const { alias, entries } of chunkEntries) {
  17136. for (const entry of entries) {
  17137. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  17138. }
  17139. }
  17140. return manualChunkAliasByEntry;
  17141. }
  17142. assignManualChunks(getManualChunk) {
  17143. // eslint-disable-next-line unicorn/prefer-module
  17144. const manualChunkAliasesWithEntry = [];
  17145. const manualChunksApi = {
  17146. getModuleIds: () => this.graph.modulesById.keys(),
  17147. getModuleInfo: this.graph.getModuleInfo
  17148. };
  17149. for (const module of this.graph.modulesById.values()) {
  17150. if (module instanceof Module) {
  17151. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  17152. if (typeof manualChunkAlias === 'string') {
  17153. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  17154. }
  17155. }
  17156. }
  17157. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  17158. const manualChunkAliasByEntry = new Map();
  17159. for (const [alias, module] of manualChunkAliasesWithEntry) {
  17160. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  17161. }
  17162. return manualChunkAliasByEntry;
  17163. }
  17164. finaliseAssets(bundle) {
  17165. if (this.outputOptions.validate) {
  17166. for (const file of Object.values(bundle)) {
  17167. if ('code' in file) {
  17168. try {
  17169. parseAst(file.code);
  17170. }
  17171. catch (error_) {
  17172. this.inputOptions.onLog(LOGLEVEL_WARN, logChunkInvalid(file, error_));
  17173. }
  17174. }
  17175. }
  17176. }
  17177. this.pluginDriver.finaliseAssets();
  17178. }
  17179. async generateChunks(bundle, getHashPlaceholder) {
  17180. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  17181. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  17182. ? await this.addManualChunks(manualChunks)
  17183. : this.assignManualChunks(manualChunks);
  17184. const snippets = getGenerateCodeSnippets(this.outputOptions);
  17185. const includedModules = getIncludedModules(this.graph.modulesById);
  17186. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  17187. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  17188. const chunks = [];
  17189. const chunkByModule = new Map();
  17190. for (const { alias, modules } of inlineDynamicImports
  17191. ? [{ alias: null, modules: includedModules }]
  17192. : preserveModules
  17193. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  17194. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog)) {
  17195. sortByExecutionOrder(modules);
  17196. 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);
  17197. chunks.push(chunk);
  17198. }
  17199. for (const chunk of chunks) {
  17200. chunk.link();
  17201. }
  17202. const facades = [];
  17203. for (const chunk of chunks) {
  17204. facades.push(...chunk.generateFacades());
  17205. }
  17206. return [...chunks, ...facades];
  17207. }
  17208. }
  17209. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  17210. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  17211. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  17212. if (typeof outputOptions.file === 'string')
  17213. 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'));
  17214. if (outputOptions.sourcemapFile)
  17215. return error(logInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  17216. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  17217. 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'));
  17218. }
  17219. function getIncludedModules(modulesById) {
  17220. const includedModules = [];
  17221. for (const module of modulesById.values()) {
  17222. if (module instanceof Module &&
  17223. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  17224. includedModules.push(module);
  17225. }
  17226. }
  17227. return includedModules;
  17228. }
  17229. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  17230. const absoluteEntryModulePaths = [];
  17231. for (const module of includedModules) {
  17232. if ((module.info.isEntry || preserveModules) && isAbsolute$1(module.id)) {
  17233. absoluteEntryModulePaths.push(module.id);
  17234. }
  17235. }
  17236. return absoluteEntryModulePaths;
  17237. }
  17238. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  17239. const externalChunkByModule = new Map();
  17240. for (const module of modulesById.values()) {
  17241. if (module instanceof ExternalModule) {
  17242. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  17243. }
  17244. }
  17245. return externalChunkByModule;
  17246. }
  17247. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  17248. const existingAlias = manualChunkAliasByEntry.get(module);
  17249. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  17250. return error(logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  17251. }
  17252. manualChunkAliasByEntry.set(module, alias);
  17253. }
  17254. function flru (max) {
  17255. var num, curr, prev;
  17256. var limit = max || 1;
  17257. function keep(key, value) {
  17258. if (++num > limit) {
  17259. prev = curr;
  17260. reset(1);
  17261. ++num;
  17262. }
  17263. curr[key] = value;
  17264. }
  17265. function reset(isPartial) {
  17266. num = 0;
  17267. curr = Object.create(null);
  17268. isPartial || (prev=Object.create(null));
  17269. }
  17270. reset();
  17271. return {
  17272. clear: reset,
  17273. has: function (key) {
  17274. return curr[key] !== void 0 || prev[key] !== void 0;
  17275. },
  17276. get: function (key) {
  17277. var val = curr[key];
  17278. if (val !== void 0) return val;
  17279. if ((val=prev[key]) !== void 0) {
  17280. keep(key, val);
  17281. return val;
  17282. }
  17283. },
  17284. set: function (key, value) {
  17285. if (curr[key] !== void 0) {
  17286. curr[key] = value;
  17287. } else {
  17288. keep(key, value);
  17289. }
  17290. }
  17291. };
  17292. }
  17293. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  17294. let skipped = null;
  17295. let replaceContext = null;
  17296. if (skip) {
  17297. skipped = new Set();
  17298. for (const skippedCall of skip) {
  17299. if (source === skippedCall.source && importer === skippedCall.importer) {
  17300. skipped.add(skippedCall.plugin);
  17301. }
  17302. }
  17303. replaceContext = (pluginContext, plugin) => ({
  17304. ...pluginContext,
  17305. resolve: (source, importer, { attributes, custom, isEntry, skipSelf } = BLANK) => {
  17306. skipSelf ??= true;
  17307. return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  17308. }
  17309. });
  17310. }
  17311. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, isEntry }], replaceContext, skipped);
  17312. }
  17313. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  17314. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes);
  17315. if (pluginResult != null) {
  17316. const [resolveIdResult, plugin] = pluginResult;
  17317. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  17318. return {
  17319. ...resolveIdResult,
  17320. resolvedBy: plugin.name
  17321. };
  17322. }
  17323. if (typeof resolveIdResult === 'string') {
  17324. return {
  17325. id: resolveIdResult,
  17326. resolvedBy: plugin.name
  17327. };
  17328. }
  17329. return resolveIdResult;
  17330. }
  17331. // external modules (non-entry modules that start with neither '.' or '/')
  17332. // are skipped at this stage.
  17333. if (importer !== undefined && !isAbsolute$1(source) && source[0] !== '.')
  17334. return null;
  17335. // `resolve` processes paths from right to left, prepending them until an
  17336. // absolute path is created. Absolute importees therefore shortcircuit the
  17337. // resolve call and require no special handing on our part.
  17338. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  17339. return addJsExtensionIfNecessary(importer ? resolve$1(dirname(importer), source) : resolve$1(source), preserveSymlinks);
  17340. }
  17341. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  17342. return ((await findFile(file, preserveSymlinks)) ??
  17343. (await findFile(file + '.mjs', preserveSymlinks)) ??
  17344. (await findFile(file + '.js', preserveSymlinks)));
  17345. }
  17346. async function findFile(file, preserveSymlinks) {
  17347. try {
  17348. const stats = await lstat(file);
  17349. if (!preserveSymlinks && stats.isSymbolicLink())
  17350. return await findFile(await realpath(file), preserveSymlinks);
  17351. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  17352. // check case
  17353. const name = basename(file);
  17354. const files = await readdir(dirname(file));
  17355. if (files.includes(name))
  17356. return file;
  17357. }
  17358. }
  17359. catch {
  17360. // suppress
  17361. }
  17362. }
  17363. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  17364. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  17365. function createPluginCache(cache) {
  17366. return {
  17367. delete(id) {
  17368. return delete cache[id];
  17369. },
  17370. get(id) {
  17371. const item = cache[id];
  17372. if (!item)
  17373. return;
  17374. item[0] = 0;
  17375. return item[1];
  17376. },
  17377. has(id) {
  17378. const item = cache[id];
  17379. if (!item)
  17380. return false;
  17381. item[0] = 0;
  17382. return true;
  17383. },
  17384. set(id, value) {
  17385. cache[id] = [0, value];
  17386. }
  17387. };
  17388. }
  17389. function getTrackedPluginCache(pluginCache, onUse) {
  17390. return {
  17391. delete(id) {
  17392. onUse();
  17393. return pluginCache.delete(id);
  17394. },
  17395. get(id) {
  17396. onUse();
  17397. return pluginCache.get(id);
  17398. },
  17399. has(id) {
  17400. onUse();
  17401. return pluginCache.has(id);
  17402. },
  17403. set(id, value) {
  17404. onUse();
  17405. return pluginCache.set(id, value);
  17406. }
  17407. };
  17408. }
  17409. const NO_CACHE = {
  17410. delete() {
  17411. return false;
  17412. },
  17413. get() {
  17414. return undefined;
  17415. },
  17416. has() {
  17417. return false;
  17418. },
  17419. set() { }
  17420. };
  17421. function uncacheablePluginError(pluginName) {
  17422. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  17423. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  17424. return error(logAnonymousPluginCache());
  17425. }
  17426. return error(logDuplicatePluginName(pluginName));
  17427. }
  17428. function getCacheForUncacheablePlugin(pluginName) {
  17429. return {
  17430. delete() {
  17431. return uncacheablePluginError(pluginName);
  17432. },
  17433. get() {
  17434. return uncacheablePluginError(pluginName);
  17435. },
  17436. has() {
  17437. return uncacheablePluginError(pluginName);
  17438. },
  17439. set() {
  17440. return uncacheablePluginError(pluginName);
  17441. }
  17442. };
  17443. }
  17444. async function asyncFlatten(array) {
  17445. do {
  17446. array = (await Promise.all(array)).flat(Infinity);
  17447. } while (array.some((v) => v?.then));
  17448. return array;
  17449. }
  17450. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  17451. const { onwarn, onLog } = config;
  17452. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  17453. if (onLog) {
  17454. const minimalPriority = logLevelPriority[logLevel];
  17455. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  17456. if (level === LOGLEVEL_ERROR) {
  17457. return error(normalizeLog(handledLog));
  17458. }
  17459. if (logLevelPriority[level] >= minimalPriority) {
  17460. defaultOnLog(level, normalizeLog(handledLog));
  17461. }
  17462. });
  17463. }
  17464. return defaultOnLog;
  17465. };
  17466. const getDefaultOnLog = (printLog, onwarn) => onwarn
  17467. ? (level, log) => {
  17468. if (level === LOGLEVEL_WARN) {
  17469. onwarn(addLogToString(log), warning => printLog(LOGLEVEL_WARN, normalizeLog(warning)));
  17470. }
  17471. else {
  17472. printLog(level, log);
  17473. }
  17474. }
  17475. : printLog;
  17476. const addLogToString = (log) => {
  17477. Object.defineProperty(log, 'toString', {
  17478. value: () => log.message,
  17479. writable: true
  17480. });
  17481. return log;
  17482. };
  17483. const normalizeLog = (log) => typeof log === 'string'
  17484. ? { message: log }
  17485. : typeof log === 'function'
  17486. ? normalizeLog(log())
  17487. : log;
  17488. const defaultPrintLog = (level, { message }) => {
  17489. switch (level) {
  17490. case LOGLEVEL_WARN: {
  17491. return console.warn(message);
  17492. }
  17493. case LOGLEVEL_DEBUG: {
  17494. return console.debug(message);
  17495. }
  17496. default: {
  17497. return console.info(message);
  17498. }
  17499. }
  17500. };
  17501. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  17502. const validOptionSet = new Set(validOptions);
  17503. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  17504. if (unknownOptions.length > 0) {
  17505. log(LOGLEVEL_WARN, logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  17506. }
  17507. }
  17508. const treeshakePresets = {
  17509. recommended: {
  17510. annotations: true,
  17511. correctVarValueBeforeDeclaration: false,
  17512. manualPureFunctions: EMPTY_ARRAY,
  17513. moduleSideEffects: () => true,
  17514. propertyReadSideEffects: true,
  17515. tryCatchDeoptimization: true,
  17516. unknownGlobalSideEffects: false
  17517. },
  17518. safest: {
  17519. annotations: true,
  17520. correctVarValueBeforeDeclaration: true,
  17521. manualPureFunctions: EMPTY_ARRAY,
  17522. moduleSideEffects: () => true,
  17523. propertyReadSideEffects: true,
  17524. tryCatchDeoptimization: true,
  17525. unknownGlobalSideEffects: true
  17526. },
  17527. smallest: {
  17528. annotations: true,
  17529. correctVarValueBeforeDeclaration: false,
  17530. manualPureFunctions: EMPTY_ARRAY,
  17531. moduleSideEffects: () => false,
  17532. propertyReadSideEffects: false,
  17533. tryCatchDeoptimization: false,
  17534. unknownGlobalSideEffects: false
  17535. }
  17536. };
  17537. const generatedCodePresets = {
  17538. es2015: {
  17539. arrowFunctions: true,
  17540. constBindings: true,
  17541. objectShorthand: true,
  17542. reservedNamesAsProps: true,
  17543. symbols: true
  17544. },
  17545. es5: {
  17546. arrowFunctions: false,
  17547. constBindings: false,
  17548. objectShorthand: false,
  17549. reservedNamesAsProps: true,
  17550. symbols: false
  17551. }
  17552. };
  17553. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  17554. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  17555. if (typeof value === 'string') {
  17556. const preset = presets[value];
  17557. if (preset) {
  17558. return preset;
  17559. }
  17560. error(logInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  17561. }
  17562. return objectifyOption(value);
  17563. };
  17564. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  17565. const presetName = value?.preset;
  17566. if (presetName) {
  17567. const preset = presets[presetName];
  17568. if (preset) {
  17569. return { ...preset, ...value };
  17570. }
  17571. else {
  17572. error(logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  17573. }
  17574. }
  17575. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  17576. };
  17577. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  17578. async function transform(source, module, pluginDriver, log) {
  17579. const id = module.id;
  17580. const sourcemapChain = [];
  17581. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  17582. const originalCode = source.code;
  17583. let ast = source.ast;
  17584. const transformDependencies = [];
  17585. const emittedFiles = [];
  17586. let customTransformCache = false;
  17587. const useCustomTransformCache = () => (customTransformCache = true);
  17588. let pluginName = '';
  17589. let currentSource = source.code;
  17590. function transformReducer(previousCode, result, plugin) {
  17591. let code;
  17592. let map;
  17593. if (typeof result === 'string') {
  17594. code = result;
  17595. }
  17596. else if (result && typeof result === 'object') {
  17597. module.updateOptions(result);
  17598. if (result.code == null) {
  17599. if (result.map || result.ast) {
  17600. log(LOGLEVEL_WARN, logNoTransformMapOrAstWithoutCode(plugin.name));
  17601. }
  17602. return previousCode;
  17603. }
  17604. ({ code, map, ast } = result);
  17605. }
  17606. else {
  17607. return previousCode;
  17608. }
  17609. // strict null check allows 'null' maps to not be pushed to the chain,
  17610. // while 'undefined' gets the missing map warning
  17611. if (map !== null) {
  17612. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  17613. missing: true,
  17614. plugin: plugin.name
  17615. });
  17616. }
  17617. currentSource = code;
  17618. return code;
  17619. }
  17620. const getLogHandler = (handler) => (log, pos) => {
  17621. log = normalizeLog(log);
  17622. if (pos)
  17623. augmentCodeLocation(log, pos, currentSource, id);
  17624. log.id = id;
  17625. log.hook = 'transform';
  17626. handler(log);
  17627. };
  17628. let code;
  17629. try {
  17630. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  17631. pluginName = plugin.name;
  17632. return {
  17633. ...pluginContext,
  17634. addWatchFile(id) {
  17635. transformDependencies.push(id);
  17636. pluginContext.addWatchFile(id);
  17637. },
  17638. cache: customTransformCache
  17639. ? pluginContext.cache
  17640. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  17641. debug: getLogHandler(pluginContext.debug),
  17642. emitFile(emittedFile) {
  17643. emittedFiles.push(emittedFile);
  17644. return pluginDriver.emitFile(emittedFile);
  17645. },
  17646. error(error_, pos) {
  17647. if (typeof error_ === 'string')
  17648. error_ = { message: error_ };
  17649. if (pos)
  17650. augmentCodeLocation(error_, pos, currentSource, id);
  17651. error_.id = id;
  17652. error_.hook = 'transform';
  17653. return pluginContext.error(error_);
  17654. },
  17655. getCombinedSourcemap() {
  17656. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  17657. if (!combinedMap) {
  17658. const magicString = new MagicString(originalCode);
  17659. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  17660. }
  17661. if (originalSourcemap !== combinedMap) {
  17662. originalSourcemap = combinedMap;
  17663. sourcemapChain.length = 0;
  17664. }
  17665. return new SourceMap({
  17666. ...combinedMap,
  17667. file: null,
  17668. sourcesContent: combinedMap.sourcesContent
  17669. });
  17670. },
  17671. info: getLogHandler(pluginContext.info),
  17672. setAssetSource() {
  17673. return this.error(logInvalidSetAssetSourceCall());
  17674. },
  17675. warn: getLogHandler(pluginContext.warn)
  17676. };
  17677. });
  17678. }
  17679. catch (error_) {
  17680. return error(logPluginError(error_, pluginName, { hook: 'transform', id }));
  17681. }
  17682. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  17683. emittedFiles.length > 0)
  17684. module.transformFiles = emittedFiles;
  17685. return {
  17686. ast,
  17687. code,
  17688. customTransformCache,
  17689. originalCode,
  17690. originalSourcemap,
  17691. sourcemapChain,
  17692. transformDependencies
  17693. };
  17694. }
  17695. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  17696. class ModuleLoader {
  17697. constructor(graph, modulesById, options, pluginDriver) {
  17698. this.graph = graph;
  17699. this.modulesById = modulesById;
  17700. this.options = options;
  17701. this.pluginDriver = pluginDriver;
  17702. this.implicitEntryModules = new Set();
  17703. this.indexedEntryModules = [];
  17704. this.latestLoadModulesPromise = Promise.resolve();
  17705. this.moduleLoadPromises = new Map();
  17706. this.modulesWithLoadedDependencies = new Set();
  17707. this.nextChunkNamePriority = 0;
  17708. this.nextEntryModuleIndex = 0;
  17709. this.resolveId = async (source, importer, customOptions, isEntry, attributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  17710. ? false
  17711. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes), importer, source), attributes);
  17712. this.hasModuleSideEffects = options.treeshake
  17713. ? options.treeshake.moduleSideEffects
  17714. : () => true;
  17715. }
  17716. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  17717. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  17718. await this.awaitLoadModulesPromise();
  17719. return result;
  17720. }
  17721. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  17722. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  17723. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  17724. const firstChunkNamePriority = this.nextChunkNamePriority;
  17725. this.nextChunkNamePriority += unresolvedEntryModules.length;
  17726. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  17727. for (const [index, entryModule] of entryModules.entries()) {
  17728. entryModule.isUserDefinedEntryPoint =
  17729. entryModule.isUserDefinedEntryPoint || isUserDefined;
  17730. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  17731. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  17732. if (existingIndexedModule) {
  17733. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  17734. }
  17735. else {
  17736. this.indexedEntryModules.push({
  17737. index: firstEntryModuleIndex + index,
  17738. module: entryModule
  17739. });
  17740. }
  17741. }
  17742. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  17743. return entryModules;
  17744. }));
  17745. await this.awaitLoadModulesPromise();
  17746. return {
  17747. entryModules: this.indexedEntryModules.map(({ module }) => module),
  17748. implicitEntryModules: [...this.implicitEntryModules],
  17749. newEntryModules
  17750. };
  17751. }
  17752. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  17753. const unresolvedModule = {
  17754. fileName: fileName || null,
  17755. id,
  17756. importer,
  17757. name: name || null
  17758. };
  17759. const module = implicitlyLoadedAfterOneOf
  17760. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  17761. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  17762. if (preserveSignature != null) {
  17763. module.preserveSignature = preserveSignature;
  17764. }
  17765. return module;
  17766. }
  17767. async preloadModule(resolvedId) {
  17768. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  17769. return module.info;
  17770. }
  17771. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  17772. const chunkNamePriority = this.nextChunkNamePriority++;
  17773. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  17774. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  17775. if (!entryModule.info.isEntry) {
  17776. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  17777. // We need to check again if this is still an entry module as these
  17778. // changes need to be performed atomically to avoid race conditions
  17779. // if the same module is re-emitted as an entry module.
  17780. // The inverse changes happen in "handleExistingModule"
  17781. if (!entryModule.info.isEntry) {
  17782. this.implicitEntryModules.add(entryModule);
  17783. for (const module of implicitlyLoadedAfterModules) {
  17784. entryModule.implicitlyLoadedAfter.add(module);
  17785. }
  17786. for (const dependant of entryModule.implicitlyLoadedAfter) {
  17787. dependant.implicitlyLoadedBefore.add(entryModule);
  17788. }
  17789. }
  17790. }
  17791. return entryModule;
  17792. }));
  17793. }
  17794. async addModuleSource(id, importer, module) {
  17795. let source;
  17796. try {
  17797. source = await this.graph.fileOperationQueue.run(async () => {
  17798. const content = await this.pluginDriver.hookFirst('load', [id]);
  17799. if (content !== null)
  17800. return content;
  17801. this.graph.watchFiles[id] = true;
  17802. return await readFile(id, 'utf8');
  17803. });
  17804. }
  17805. catch (error_) {
  17806. let message = `Could not load ${id}`;
  17807. if (importer)
  17808. message += ` (imported by ${relativeId(importer)})`;
  17809. message += `: ${error_.message}`;
  17810. error_.message = message;
  17811. throw error_;
  17812. }
  17813. const sourceDescription = typeof source === 'string'
  17814. ? { code: source }
  17815. : source != null && typeof source === 'object' && typeof source.code === 'string'
  17816. ? source
  17817. : error(logBadLoader(id));
  17818. const code = sourceDescription.code;
  17819. if (code.charCodeAt(0) === 0xfe_ff) {
  17820. sourceDescription.code = code.slice(1);
  17821. }
  17822. const cachedModule = this.graph.cachedModules.get(id);
  17823. if (cachedModule &&
  17824. !cachedModule.customTransformCache &&
  17825. cachedModule.originalCode === sourceDescription.code &&
  17826. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  17827. {
  17828. ast: cachedModule.ast,
  17829. code: cachedModule.code,
  17830. id: cachedModule.id,
  17831. meta: cachedModule.meta,
  17832. moduleSideEffects: cachedModule.moduleSideEffects,
  17833. resolvedSources: cachedModule.resolvedIds,
  17834. syntheticNamedExports: cachedModule.syntheticNamedExports
  17835. }
  17836. ]))) {
  17837. if (cachedModule.transformFiles) {
  17838. for (const emittedFile of cachedModule.transformFiles)
  17839. this.pluginDriver.emitFile(emittedFile);
  17840. }
  17841. await module.setSource(cachedModule);
  17842. }
  17843. else {
  17844. module.updateOptions(sourceDescription);
  17845. await module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  17846. }
  17847. }
  17848. async awaitLoadModulesPromise() {
  17849. let startingPromise;
  17850. do {
  17851. startingPromise = this.latestLoadModulesPromise;
  17852. await startingPromise;
  17853. } while (startingPromise !== this.latestLoadModulesPromise);
  17854. }
  17855. extendLoadModulesPromise(loadNewModulesPromise) {
  17856. this.latestLoadModulesPromise = Promise.all([
  17857. loadNewModulesPromise,
  17858. this.latestLoadModulesPromise
  17859. ]);
  17860. this.latestLoadModulesPromise.catch(() => {
  17861. /* Avoid unhandled Promise rejections */
  17862. });
  17863. return loadNewModulesPromise;
  17864. }
  17865. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  17866. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  17867. if (resolvedId === null)
  17868. return null;
  17869. if (typeof resolvedId === 'string') {
  17870. dynamicImport.resolution = resolvedId;
  17871. return null;
  17872. }
  17873. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  17874. })));
  17875. for (const dependency of dependencies) {
  17876. if (dependency) {
  17877. module.dynamicDependencies.add(dependency);
  17878. dependency.dynamicImporters.push(module.id);
  17879. }
  17880. }
  17881. }
  17882. // If this is a preload, then this method always waits for the dependencies of
  17883. // the module to be resolved.
  17884. // Otherwise, if the module does not exist, it waits for the module and all
  17885. // its dependencies to be loaded.
  17886. // Otherwise, it returns immediately.
  17887. async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  17888. const existingModule = this.modulesById.get(id);
  17889. if (existingModule instanceof Module) {
  17890. if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
  17891. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
  17892. }
  17893. await this.handleExistingModule(existingModule, isEntry, isPreload);
  17894. return existingModule;
  17895. }
  17896. if (existingModule instanceof ExternalModule) {
  17897. return error(logExternalModulesCannotBeTransformedToModules(existingModule.id));
  17898. }
  17899. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
  17900. this.modulesById.set(id, module);
  17901. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  17902. this.getResolveStaticDependencyPromises(module),
  17903. this.getResolveDynamicImportPromises(module),
  17904. loadAndResolveDependenciesPromise
  17905. ]);
  17906. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  17907. loadAndResolveDependenciesPromise.catch(() => {
  17908. /* avoid unhandled promise rejections */
  17909. });
  17910. this.moduleLoadPromises.set(module, loadPromise);
  17911. const resolveDependencyPromises = await loadPromise;
  17912. if (!isPreload) {
  17913. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  17914. }
  17915. else if (isPreload === RESOLVE_DEPENDENCIES) {
  17916. await loadAndResolveDependenciesPromise;
  17917. }
  17918. return module;
  17919. }
  17920. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  17921. if (this.modulesWithLoadedDependencies.has(module)) {
  17922. return;
  17923. }
  17924. this.modulesWithLoadedDependencies.add(module);
  17925. await Promise.all([
  17926. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  17927. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  17928. ]);
  17929. module.linkImports();
  17930. // To handle errors when resolving dependencies or in moduleParsed
  17931. await loadAndResolveDependenciesPromise;
  17932. }
  17933. fetchResolvedDependency(source, importer, resolvedId) {
  17934. if (resolvedId.external) {
  17935. const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
  17936. let externalModule = this.modulesById.get(id);
  17937. if (!externalModule) {
  17938. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute$1(id), attributes);
  17939. this.modulesById.set(id, externalModule);
  17940. }
  17941. else if (!(externalModule instanceof ExternalModule)) {
  17942. return error(logInternalIdCannotBeExternal(source, importer));
  17943. }
  17944. else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
  17945. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
  17946. }
  17947. return Promise.resolve(externalModule);
  17948. }
  17949. return this.fetchModule(resolvedId, importer, false, false);
  17950. }
  17951. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  17952. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  17953. module.dependencies.add(dependency);
  17954. dependency.importers.push(module.id);
  17955. }
  17956. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  17957. for (const dependency of module.dependencies) {
  17958. if (dependency instanceof Module) {
  17959. dependency.importedFromNotTreeshaken = true;
  17960. }
  17961. }
  17962. }
  17963. }
  17964. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  17965. const { makeAbsoluteExternalsRelative } = this.options;
  17966. if (resolveIdResult) {
  17967. if (typeof resolveIdResult === 'object') {
  17968. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  17969. return {
  17970. ...resolveIdResult,
  17971. external: external &&
  17972. (external === 'relative' ||
  17973. !isAbsolute$1(resolveIdResult.id) ||
  17974. (external === true &&
  17975. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  17976. 'absolute')
  17977. };
  17978. }
  17979. const external = this.options.external(resolveIdResult, importer, true);
  17980. return {
  17981. external: external &&
  17982. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  17983. 'absolute'),
  17984. id: external && makeAbsoluteExternalsRelative
  17985. ? normalizeRelativeExternalId(resolveIdResult, importer)
  17986. : resolveIdResult
  17987. };
  17988. }
  17989. const id = makeAbsoluteExternalsRelative
  17990. ? normalizeRelativeExternalId(source, importer)
  17991. : source;
  17992. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  17993. return null;
  17994. }
  17995. return {
  17996. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  17997. id
  17998. };
  17999. }
  18000. getResolveDynamicImportPromises(module) {
  18001. return module.dynamicImports.map(async (dynamicImport) => {
  18002. const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
  18003. if (resolvedId && typeof resolvedId === 'object') {
  18004. dynamicImport.id = resolvedId.id;
  18005. }
  18006. return [dynamicImport, resolvedId];
  18007. });
  18008. }
  18009. getResolveStaticDependencyPromises(module) {
  18010. // eslint-disable-next-line unicorn/prefer-spread
  18011. return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
  18012. source,
  18013. (module.resolvedIds[source] =
  18014. module.resolvedIds[source] ||
  18015. this.handleInvalidResolvedId(await this.resolveId(source, module.id, EMPTY_OBJECT, false, attributes), source, module.id, attributes))
  18016. ]);
  18017. }
  18018. getResolvedIdWithDefaults(resolvedId, attributes) {
  18019. if (!resolvedId) {
  18020. return null;
  18021. }
  18022. const external = resolvedId.external || false;
  18023. return {
  18024. attributes: resolvedId.attributes || attributes,
  18025. external,
  18026. id: resolvedId.id,
  18027. meta: resolvedId.meta || {},
  18028. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  18029. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  18030. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  18031. };
  18032. }
  18033. async handleExistingModule(module, isEntry, isPreload) {
  18034. const loadPromise = this.moduleLoadPromises.get(module);
  18035. if (isPreload) {
  18036. return isPreload === RESOLVE_DEPENDENCIES
  18037. ? waitForDependencyResolution(loadPromise)
  18038. : loadPromise;
  18039. }
  18040. if (isEntry) {
  18041. // This reverts the changes in addEntryWithImplicitDependants and needs to
  18042. // be performed atomically
  18043. module.info.isEntry = true;
  18044. this.implicitEntryModules.delete(module);
  18045. for (const dependant of module.implicitlyLoadedAfter) {
  18046. dependant.implicitlyLoadedBefore.delete(module);
  18047. }
  18048. module.implicitlyLoadedAfter.clear();
  18049. }
  18050. return this.fetchModuleDependencies(module, ...(await loadPromise));
  18051. }
  18052. handleInvalidResolvedId(resolvedId, source, importer, attributes) {
  18053. if (resolvedId === null) {
  18054. if (isRelative(source)) {
  18055. return error(logUnresolvedImport(source, importer));
  18056. }
  18057. this.options.onLog(LOGLEVEL_WARN, logUnresolvedImportTreatedAsExternal(source, importer));
  18058. return {
  18059. attributes,
  18060. external: true,
  18061. id: source,
  18062. meta: {},
  18063. moduleSideEffects: this.hasModuleSideEffects(source, true),
  18064. resolvedBy: 'rollup',
  18065. syntheticNamedExports: false
  18066. };
  18067. }
  18068. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  18069. this.options.onLog(LOGLEVEL_WARN, logExternalSyntheticExports(source, importer));
  18070. }
  18071. return resolvedId;
  18072. }
  18073. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  18074. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT);
  18075. if (resolveIdResult == null) {
  18076. return error(implicitlyLoadedBefore === null
  18077. ? logUnresolvedEntry(unresolvedId)
  18078. : logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  18079. }
  18080. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  18081. if (resolveIdResult === false || isExternalModules) {
  18082. return error(implicitlyLoadedBefore === null
  18083. ? isExternalModules && isLoadForManualChunks
  18084. ? logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  18085. : logEntryCannotBeExternal(unresolvedId)
  18086. : logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  18087. }
  18088. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  18089. ? resolveIdResult
  18090. : { id: resolveIdResult }, EMPTY_OBJECT), undefined, isEntry, false);
  18091. }
  18092. async resolveDynamicImport(module, specifier, importer, attributes) {
  18093. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  18094. specifier,
  18095. importer,
  18096. { attributes }
  18097. ]);
  18098. if (typeof specifier !== 'string') {
  18099. if (typeof resolution === 'string') {
  18100. return resolution;
  18101. }
  18102. if (!resolution) {
  18103. return null;
  18104. }
  18105. return this.getResolvedIdWithDefaults(resolution, attributes);
  18106. }
  18107. if (resolution == null) {
  18108. const existingResolution = module.resolvedIds[specifier];
  18109. if (existingResolution) {
  18110. if (doAttributesDiffer(existingResolution.attributes, attributes)) {
  18111. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
  18112. }
  18113. return existingResolution;
  18114. }
  18115. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false, attributes), specifier, module.id, attributes));
  18116. }
  18117. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
  18118. }
  18119. }
  18120. function normalizeRelativeExternalId(source, importer) {
  18121. return isRelative(source)
  18122. ? importer
  18123. ? resolve$1(importer, '..', source)
  18124. : resolve$1(source)
  18125. : source;
  18126. }
  18127. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  18128. if (fileName !== null) {
  18129. module.chunkFileNames.add(fileName);
  18130. }
  18131. else if (name !== null) {
  18132. // Always keep chunkNames sorted by priority
  18133. let namePosition = 0;
  18134. while (module.chunkNames[namePosition]?.priority < priority)
  18135. namePosition++;
  18136. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  18137. }
  18138. }
  18139. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  18140. return (makeAbsoluteExternalsRelative === true ||
  18141. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  18142. !isAbsolute$1(id));
  18143. }
  18144. async function waitForDependencyResolution(loadPromise) {
  18145. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  18146. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  18147. }
  18148. class GlobalScope extends Scope {
  18149. constructor() {
  18150. super();
  18151. this.parent = null;
  18152. this.variables.set('undefined', new UndefinedVariable());
  18153. }
  18154. findVariable(name) {
  18155. let variable = this.variables.get(name);
  18156. if (!variable) {
  18157. variable = new GlobalVariable(name);
  18158. this.variables.set(name, variable);
  18159. }
  18160. return variable;
  18161. }
  18162. }
  18163. function generateAssetFileName(name, source, sourceHash, outputOptions, bundle) {
  18164. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  18165. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  18166. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  18167. : outputOptions.assetFileNames, 'output.assetFileNames', {
  18168. ext: () => extname(emittedName).slice(1),
  18169. extname: () => extname(emittedName),
  18170. hash: size => sourceHash.slice(0, Math.max(0, size || DEFAULT_HASH_SIZE)),
  18171. name: () => emittedName.slice(0, Math.max(0, emittedName.length - extname(emittedName).length))
  18172. }), bundle);
  18173. }
  18174. function reserveFileNameInBundle(fileName, { bundle }, log) {
  18175. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  18176. log(LOGLEVEL_WARN, logFileNameConflict(fileName));
  18177. }
  18178. else {
  18179. bundle[fileName] = FILE_PLACEHOLDER;
  18180. }
  18181. }
  18182. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  18183. function hasValidType(emittedFile) {
  18184. return Boolean(emittedFile &&
  18185. emittedFileTypes.has(emittedFile.type));
  18186. }
  18187. function hasValidName(emittedFile) {
  18188. const validatedName = emittedFile.fileName || emittedFile.name;
  18189. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  18190. }
  18191. function getValidSource(source, emittedFile, fileReferenceId) {
  18192. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  18193. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  18194. 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.`));
  18195. }
  18196. return source;
  18197. }
  18198. function getAssetFileName(file, referenceId) {
  18199. if (typeof file.fileName !== 'string') {
  18200. return error(logAssetNotFinalisedForFileName(file.name || referenceId));
  18201. }
  18202. return file.fileName;
  18203. }
  18204. function getChunkFileName(file, facadeChunkByModule) {
  18205. if (file.fileName) {
  18206. return file.fileName;
  18207. }
  18208. if (facadeChunkByModule) {
  18209. return facadeChunkByModule.get(file.module).getFileName();
  18210. }
  18211. return error(logChunkNotGeneratedForFileName(file.fileName || file.name));
  18212. }
  18213. class FileEmitter {
  18214. constructor(graph, options, baseFileEmitter) {
  18215. this.graph = graph;
  18216. this.options = options;
  18217. this.facadeChunkByModule = null;
  18218. this.nextIdBase = 1;
  18219. this.output = null;
  18220. this.outputFileEmitters = [];
  18221. this.emitFile = (emittedFile) => {
  18222. if (!hasValidType(emittedFile)) {
  18223. return error(logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  18224. }
  18225. if (emittedFile.type === 'prebuilt-chunk') {
  18226. return this.emitPrebuiltChunk(emittedFile);
  18227. }
  18228. if (!hasValidName(emittedFile)) {
  18229. 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}".`));
  18230. }
  18231. if (emittedFile.type === 'chunk') {
  18232. return this.emitChunk(emittedFile);
  18233. }
  18234. return this.emitAsset(emittedFile);
  18235. };
  18236. this.finaliseAssets = () => {
  18237. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  18238. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  18239. return error(logNoAssetSourceSet(emittedFile.name || referenceId));
  18240. }
  18241. };
  18242. this.getFileName = (fileReferenceId) => {
  18243. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  18244. if (!emittedFile)
  18245. return error(logFileReferenceIdNotFoundForFilename(fileReferenceId));
  18246. if (emittedFile.type === 'chunk') {
  18247. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  18248. }
  18249. if (emittedFile.type === 'prebuilt-chunk') {
  18250. return emittedFile.fileName;
  18251. }
  18252. return getAssetFileName(emittedFile, fileReferenceId);
  18253. };
  18254. this.setAssetSource = (referenceId, requestedSource) => {
  18255. const consumedFile = this.filesByReferenceId.get(referenceId);
  18256. if (!consumedFile)
  18257. return error(logAssetReferenceIdNotFoundForSetSource(referenceId));
  18258. if (consumedFile.type !== 'asset') {
  18259. return error(logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  18260. }
  18261. if (consumedFile.source !== undefined) {
  18262. return error(logAssetSourceAlreadySet(consumedFile.name || referenceId));
  18263. }
  18264. const source = getValidSource(requestedSource, consumedFile, referenceId);
  18265. if (this.output) {
  18266. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  18267. }
  18268. else {
  18269. consumedFile.source = source;
  18270. for (const emitter of this.outputFileEmitters) {
  18271. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  18272. }
  18273. }
  18274. };
  18275. this.setChunkInformation = (facadeChunkByModule) => {
  18276. this.facadeChunkByModule = facadeChunkByModule;
  18277. };
  18278. this.setOutputBundle = (bundle, outputOptions) => {
  18279. const getHash = hasherByType[outputOptions.hashCharacters];
  18280. const output = (this.output = {
  18281. bundle,
  18282. fileNamesBySource: new Map(),
  18283. getHash,
  18284. outputOptions
  18285. });
  18286. for (const emittedFile of this.filesByReferenceId.values()) {
  18287. if (emittedFile.fileName) {
  18288. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  18289. }
  18290. }
  18291. const consumedAssetsByHash = new Map();
  18292. for (const consumedFile of this.filesByReferenceId.values()) {
  18293. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  18294. if (consumedFile.fileName) {
  18295. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  18296. }
  18297. else {
  18298. const sourceHash = getHash(consumedFile.source);
  18299. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  18300. }
  18301. }
  18302. else if (consumedFile.type === 'prebuilt-chunk') {
  18303. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  18304. }
  18305. }
  18306. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  18307. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  18308. }
  18309. };
  18310. this.filesByReferenceId = baseFileEmitter
  18311. ? new Map(baseFileEmitter.filesByReferenceId)
  18312. : new Map();
  18313. baseFileEmitter?.addOutputFileEmitter(this);
  18314. }
  18315. addOutputFileEmitter(outputFileEmitter) {
  18316. this.outputFileEmitters.push(outputFileEmitter);
  18317. }
  18318. assignReferenceId(file, idBase) {
  18319. let referenceId = idBase;
  18320. do {
  18321. referenceId = getHash64(referenceId).slice(0, 8).replaceAll('-', '$');
  18322. } while (this.filesByReferenceId.has(referenceId) ||
  18323. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  18324. file.referenceId = referenceId;
  18325. this.filesByReferenceId.set(referenceId, file);
  18326. for (const { filesByReferenceId } of this.outputFileEmitters) {
  18327. filesByReferenceId.set(referenceId, file);
  18328. }
  18329. return referenceId;
  18330. }
  18331. createPrebuiltChunk(prebuiltChunk) {
  18332. return {
  18333. code: prebuiltChunk.code,
  18334. dynamicImports: [],
  18335. exports: prebuiltChunk.exports || [],
  18336. facadeModuleId: null,
  18337. fileName: prebuiltChunk.fileName,
  18338. implicitlyLoadedBefore: [],
  18339. importedBindings: {},
  18340. imports: [],
  18341. isDynamicEntry: false,
  18342. isEntry: false,
  18343. isImplicitEntry: false,
  18344. map: prebuiltChunk.map || null,
  18345. moduleIds: [],
  18346. modules: {},
  18347. name: prebuiltChunk.fileName,
  18348. preliminaryFileName: prebuiltChunk.fileName,
  18349. referencedFiles: [],
  18350. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  18351. type: 'chunk'
  18352. };
  18353. }
  18354. emitAsset(emittedAsset) {
  18355. const source = emittedAsset.source === undefined
  18356. ? undefined
  18357. : getValidSource(emittedAsset.source, emittedAsset, null);
  18358. const consumedAsset = {
  18359. fileName: emittedAsset.fileName,
  18360. name: emittedAsset.name,
  18361. needsCodeReference: !!emittedAsset.needsCodeReference,
  18362. referenceId: '',
  18363. source,
  18364. type: 'asset'
  18365. };
  18366. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  18367. if (this.output) {
  18368. this.emitAssetWithReferenceId(consumedAsset, this.output);
  18369. }
  18370. else {
  18371. for (const fileEmitter of this.outputFileEmitters) {
  18372. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  18373. }
  18374. }
  18375. return referenceId;
  18376. }
  18377. emitAssetWithReferenceId(consumedAsset, output) {
  18378. const { fileName, source } = consumedAsset;
  18379. if (fileName) {
  18380. reserveFileNameInBundle(fileName, output, this.options.onLog);
  18381. }
  18382. if (source !== undefined) {
  18383. this.finalizeAdditionalAsset(consumedAsset, source, output);
  18384. }
  18385. }
  18386. emitChunk(emittedChunk) {
  18387. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  18388. return error(logInvalidRollupPhaseForChunkEmission());
  18389. }
  18390. if (typeof emittedChunk.id !== 'string') {
  18391. return error(logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  18392. }
  18393. const consumedChunk = {
  18394. fileName: emittedChunk.fileName,
  18395. module: null,
  18396. name: emittedChunk.name || emittedChunk.id,
  18397. referenceId: '',
  18398. type: 'chunk'
  18399. };
  18400. this.graph.moduleLoader
  18401. .emitChunk(emittedChunk)
  18402. .then(module => (consumedChunk.module = module))
  18403. .catch(() => {
  18404. // Avoid unhandled Promise rejection as the error will be thrown later
  18405. // once module loading has finished
  18406. });
  18407. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  18408. }
  18409. emitPrebuiltChunk(emitPrebuiltChunk) {
  18410. if (typeof emitPrebuiltChunk.code !== 'string') {
  18411. return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  18412. }
  18413. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  18414. isPathFragment(emitPrebuiltChunk.fileName)) {
  18415. return error(logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  18416. }
  18417. const consumedPrebuiltChunk = {
  18418. code: emitPrebuiltChunk.code,
  18419. exports: emitPrebuiltChunk.exports,
  18420. fileName: emitPrebuiltChunk.fileName,
  18421. map: emitPrebuiltChunk.map,
  18422. referenceId: '',
  18423. type: 'prebuilt-chunk'
  18424. };
  18425. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  18426. if (this.output) {
  18427. this.output.bundle[consumedPrebuiltChunk.fileName] =
  18428. this.createPrebuiltChunk(consumedPrebuiltChunk);
  18429. }
  18430. return referenceId;
  18431. }
  18432. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySource, getHash, outputOptions }) {
  18433. let { fileName, needsCodeReference, referenceId } = consumedFile;
  18434. // Deduplicate assets if an explicit fileName is not provided
  18435. if (!fileName) {
  18436. const sourceHash = getHash(source);
  18437. fileName = fileNamesBySource.get(sourceHash);
  18438. if (!fileName) {
  18439. fileName = generateAssetFileName(consumedFile.name, source, sourceHash, outputOptions, bundle);
  18440. fileNamesBySource.set(sourceHash, fileName);
  18441. }
  18442. }
  18443. // We must not modify the original assets to avoid interaction between outputs
  18444. const assetWithFileName = { ...consumedFile, fileName, source };
  18445. this.filesByReferenceId.set(referenceId, assetWithFileName);
  18446. const existingAsset = bundle[fileName];
  18447. if (existingAsset?.type === 'asset') {
  18448. existingAsset.needsCodeReference &&= needsCodeReference;
  18449. }
  18450. else {
  18451. bundle[fileName] = {
  18452. fileName,
  18453. name: consumedFile.name,
  18454. needsCodeReference,
  18455. source,
  18456. type: 'asset'
  18457. };
  18458. }
  18459. }
  18460. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySource, outputOptions }) {
  18461. let fileName = '';
  18462. let usedConsumedFile;
  18463. let needsCodeReference = true;
  18464. for (const consumedFile of consumedFiles) {
  18465. needsCodeReference &&= consumedFile.needsCodeReference;
  18466. const assetFileName = generateAssetFileName(consumedFile.name, consumedFile.source, sourceHash, outputOptions, bundle);
  18467. if (!fileName ||
  18468. assetFileName.length < fileName.length ||
  18469. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  18470. fileName = assetFileName;
  18471. usedConsumedFile = consumedFile;
  18472. }
  18473. }
  18474. fileNamesBySource.set(sourceHash, fileName);
  18475. for (const consumedFile of consumedFiles) {
  18476. // We must not modify the original assets to avoid interaction between outputs
  18477. const assetWithFileName = { ...consumedFile, fileName };
  18478. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  18479. }
  18480. bundle[fileName] = {
  18481. fileName,
  18482. name: usedConsumedFile.name,
  18483. needsCodeReference,
  18484. source: usedConsumedFile.source,
  18485. type: 'asset'
  18486. };
  18487. }
  18488. }
  18489. function getLogHandler(level, code, logger, pluginName, logLevel) {
  18490. if (logLevelPriority[level] < logLevelPriority[logLevel]) {
  18491. return doNothing;
  18492. }
  18493. return (log, pos) => {
  18494. if (pos != null) {
  18495. logger(LOGLEVEL_WARN, logInvalidLogPosition(pluginName));
  18496. }
  18497. log = normalizeLog(log);
  18498. if (log.code && !log.pluginCode) {
  18499. log.pluginCode = log.code;
  18500. }
  18501. log.code = code;
  18502. log.plugin = pluginName;
  18503. logger(level, log);
  18504. };
  18505. }
  18506. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  18507. const { logLevel, onLog } = options;
  18508. let cacheable = true;
  18509. if (typeof plugin.cacheKey !== 'string') {
  18510. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  18511. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  18512. existingPluginNames.has(plugin.name)) {
  18513. cacheable = false;
  18514. }
  18515. else {
  18516. existingPluginNames.add(plugin.name);
  18517. }
  18518. }
  18519. let cacheInstance;
  18520. if (!pluginCache) {
  18521. cacheInstance = NO_CACHE;
  18522. }
  18523. else if (cacheable) {
  18524. const cacheKey = plugin.cacheKey || plugin.name;
  18525. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  18526. }
  18527. else {
  18528. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  18529. }
  18530. return {
  18531. addWatchFile(id) {
  18532. graph.watchFiles[id] = true;
  18533. },
  18534. cache: cacheInstance,
  18535. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  18536. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  18537. error(error_) {
  18538. return error(logPluginError(normalizeLog(error_), plugin.name));
  18539. },
  18540. getFileName: fileEmitter.getFileName,
  18541. getModuleIds: () => graph.modulesById.keys(),
  18542. getModuleInfo: graph.getModuleInfo,
  18543. getWatchFiles: () => Object.keys(graph.watchFiles),
  18544. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  18545. load(resolvedId) {
  18546. return graph.moduleLoader.preloadModule(resolvedId);
  18547. },
  18548. meta: {
  18549. rollupVersion: version,
  18550. watchMode: graph.watchMode
  18551. },
  18552. parse: parseAst,
  18553. resolve(source, importer, { attributes, custom, isEntry, skipSelf } = BLANK) {
  18554. skipSelf ??= true;
  18555. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  18556. },
  18557. setAssetSource: fileEmitter.setAssetSource,
  18558. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  18559. };
  18560. }
  18561. // This will make sure no input hook is omitted
  18562. const inputHookNames = {
  18563. buildEnd: 1,
  18564. buildStart: 1,
  18565. closeBundle: 1,
  18566. closeWatcher: 1,
  18567. load: 1,
  18568. moduleParsed: 1,
  18569. onLog: 1,
  18570. options: 1,
  18571. resolveDynamicImport: 1,
  18572. resolveId: 1,
  18573. shouldTransformCachedModule: 1,
  18574. transform: 1,
  18575. watchChange: 1
  18576. };
  18577. const inputHooks = Object.keys(inputHookNames);
  18578. class PluginDriver {
  18579. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  18580. this.graph = graph;
  18581. this.options = options;
  18582. this.pluginCache = pluginCache;
  18583. this.sortedPlugins = new Map();
  18584. this.unfulfilledActions = new Set();
  18585. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  18586. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  18587. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  18588. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  18589. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  18590. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  18591. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  18592. const existingPluginNames = new Set();
  18593. this.pluginContexts = new Map(this.plugins.map(plugin => [
  18594. plugin,
  18595. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  18596. ]));
  18597. if (basePluginDriver) {
  18598. for (const plugin of userPlugins) {
  18599. for (const hook of inputHooks) {
  18600. if (hook in plugin) {
  18601. options.onLog(LOGLEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
  18602. }
  18603. }
  18604. }
  18605. }
  18606. }
  18607. createOutputPluginDriver(plugins) {
  18608. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  18609. }
  18610. getUnfulfilledHookActions() {
  18611. return this.unfulfilledActions;
  18612. }
  18613. // chains, first non-null result stops and returns
  18614. hookFirst(hookName, parameters, replaceContext, skipped) {
  18615. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  18616. }
  18617. // chains, first non-null result stops and returns result and last plugin
  18618. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  18619. for (const plugin of this.getSortedPlugins(hookName)) {
  18620. if (skipped?.has(plugin))
  18621. continue;
  18622. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  18623. if (result != null)
  18624. return [result, plugin];
  18625. }
  18626. return null;
  18627. }
  18628. // chains synchronously, first non-null result stops and returns
  18629. hookFirstSync(hookName, parameters, replaceContext) {
  18630. for (const plugin of this.getSortedPlugins(hookName)) {
  18631. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  18632. if (result != null)
  18633. return result;
  18634. }
  18635. return null;
  18636. }
  18637. // parallel, ignores returns
  18638. async hookParallel(hookName, parameters, replaceContext) {
  18639. const parallelPromises = [];
  18640. for (const plugin of this.getSortedPlugins(hookName)) {
  18641. if (plugin[hookName].sequential) {
  18642. await Promise.all(parallelPromises);
  18643. parallelPromises.length = 0;
  18644. await this.runHook(hookName, parameters, plugin, replaceContext);
  18645. }
  18646. else {
  18647. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  18648. }
  18649. }
  18650. await Promise.all(parallelPromises);
  18651. }
  18652. // chains, reduces returned value, handling the reduced value as the first hook argument
  18653. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  18654. let promise = Promise.resolve(argument0);
  18655. for (const plugin of this.getSortedPlugins(hookName)) {
  18656. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  18657. }
  18658. return promise;
  18659. }
  18660. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  18661. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  18662. for (const plugin of this.getSortedPlugins(hookName)) {
  18663. const parameters = [argument0, ...rest];
  18664. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  18665. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  18666. }
  18667. return argument0;
  18668. }
  18669. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  18670. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  18671. const results = [];
  18672. const parallelResults = [];
  18673. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  18674. if (plugin[hookName].sequential) {
  18675. results.push(...(await Promise.all(parallelResults)));
  18676. parallelResults.length = 0;
  18677. results.push(await this.runHook(hookName, parameters, plugin));
  18678. }
  18679. else {
  18680. parallelResults.push(this.runHook(hookName, parameters, plugin));
  18681. }
  18682. }
  18683. results.push(...(await Promise.all(parallelResults)));
  18684. return results.reduce(reducer, await initialValue);
  18685. }
  18686. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  18687. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  18688. let accumulator = initialValue;
  18689. for (const plugin of this.getSortedPlugins(hookName)) {
  18690. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  18691. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  18692. }
  18693. return accumulator;
  18694. }
  18695. // chains, ignores returns
  18696. hookSeq(hookName, parameters, replaceContext) {
  18697. let promise = Promise.resolve();
  18698. for (const plugin of this.getSortedPlugins(hookName)) {
  18699. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  18700. }
  18701. return promise.then(noReturn);
  18702. }
  18703. getSortedPlugins(hookName, validateHandler) {
  18704. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  18705. }
  18706. // Implementation signature
  18707. runHook(hookName, parameters, plugin, replaceContext) {
  18708. // We always filter for plugins that support the hook before running it
  18709. const hook = plugin[hookName];
  18710. const handler = typeof hook === 'object' ? hook.handler : hook;
  18711. let context = this.pluginContexts.get(plugin);
  18712. if (replaceContext) {
  18713. context = replaceContext(context, plugin);
  18714. }
  18715. let action = null;
  18716. return Promise.resolve()
  18717. .then(() => {
  18718. if (typeof handler !== 'function') {
  18719. return handler;
  18720. }
  18721. // eslint-disable-next-line @typescript-eslint/ban-types
  18722. const hookResult = handler.apply(context, parameters);
  18723. if (!hookResult?.then) {
  18724. // short circuit for non-thenables and non-Promises
  18725. return hookResult;
  18726. }
  18727. // Track pending hook actions to properly error out when
  18728. // unfulfilled promises cause rollup to abruptly and confusingly
  18729. // exit with a successful 0 return code but without producing any
  18730. // output, errors or warnings.
  18731. action = [plugin.name, hookName, parameters];
  18732. this.unfulfilledActions.add(action);
  18733. // Although it would be more elegant to just return hookResult here
  18734. // and put the .then() handler just above the .catch() handler below,
  18735. // doing so would subtly change the defacto async event dispatch order
  18736. // which at least one test and some plugins in the wild may depend on.
  18737. return Promise.resolve(hookResult).then(result => {
  18738. // action was fulfilled
  18739. this.unfulfilledActions.delete(action);
  18740. return result;
  18741. });
  18742. })
  18743. .catch(error_ => {
  18744. if (action !== null) {
  18745. // action considered to be fulfilled since error being handled
  18746. this.unfulfilledActions.delete(action);
  18747. }
  18748. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  18749. });
  18750. }
  18751. /**
  18752. * Run a sync plugin hook and return the result.
  18753. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  18754. * @param args Arguments passed to the plugin hook.
  18755. * @param plugin The acutal plugin
  18756. * @param replaceContext When passed, the plugin context can be overridden.
  18757. */
  18758. runHookSync(hookName, parameters, plugin, replaceContext) {
  18759. const hook = plugin[hookName];
  18760. const handler = typeof hook === 'object' ? hook.handler : hook;
  18761. let context = this.pluginContexts.get(plugin);
  18762. if (replaceContext) {
  18763. context = replaceContext(context, plugin);
  18764. }
  18765. try {
  18766. // eslint-disable-next-line @typescript-eslint/ban-types
  18767. return handler.apply(context, parameters);
  18768. }
  18769. catch (error_) {
  18770. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  18771. }
  18772. }
  18773. }
  18774. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  18775. const pre = [];
  18776. const normal = [];
  18777. const post = [];
  18778. for (const plugin of plugins) {
  18779. const hook = plugin[hookName];
  18780. if (hook) {
  18781. if (typeof hook === 'object') {
  18782. validateHandler(hook.handler, hookName, plugin);
  18783. if (hook.order === 'pre') {
  18784. pre.push(plugin);
  18785. continue;
  18786. }
  18787. if (hook.order === 'post') {
  18788. post.push(plugin);
  18789. continue;
  18790. }
  18791. }
  18792. else {
  18793. validateHandler(hook, hookName, plugin);
  18794. }
  18795. normal.push(plugin);
  18796. }
  18797. }
  18798. return [...pre, ...normal, ...post];
  18799. }
  18800. function validateFunctionPluginHandler(handler, hookName, plugin) {
  18801. if (typeof handler !== 'function') {
  18802. error(logInvalidFunctionPluginHook(hookName, plugin.name));
  18803. }
  18804. }
  18805. function validateAddonPluginHandler(handler, hookName, plugin) {
  18806. if (typeof handler !== 'string' && typeof handler !== 'function') {
  18807. return error(logInvalidAddonPluginHook(hookName, plugin.name));
  18808. }
  18809. }
  18810. function noReturn() { }
  18811. class Queue {
  18812. constructor(maxParallel) {
  18813. this.maxParallel = maxParallel;
  18814. this.queue = [];
  18815. this.workerCount = 0;
  18816. }
  18817. run(task) {
  18818. return new Promise((resolve, reject) => {
  18819. this.queue.push({ reject, resolve, task });
  18820. this.work();
  18821. });
  18822. }
  18823. async work() {
  18824. if (this.workerCount >= this.maxParallel)
  18825. return;
  18826. this.workerCount++;
  18827. let entry;
  18828. while ((entry = this.queue.shift())) {
  18829. const { reject, resolve, task } = entry;
  18830. try {
  18831. const result = await task();
  18832. resolve(result);
  18833. }
  18834. catch (error) {
  18835. reject(error);
  18836. }
  18837. }
  18838. this.workerCount--;
  18839. }
  18840. }
  18841. function normalizeEntryModules(entryModules) {
  18842. if (Array.isArray(entryModules)) {
  18843. return entryModules.map(id => ({
  18844. fileName: null,
  18845. id,
  18846. implicitlyLoadedAfter: [],
  18847. importer: undefined,
  18848. name: null
  18849. }));
  18850. }
  18851. return Object.entries(entryModules).map(([name, id]) => ({
  18852. fileName: null,
  18853. id,
  18854. implicitlyLoadedAfter: [],
  18855. importer: undefined,
  18856. name
  18857. }));
  18858. }
  18859. class Graph {
  18860. constructor(options, watcher) {
  18861. this.options = options;
  18862. this.astLru = flru(5);
  18863. this.cachedModules = new Map();
  18864. this.deoptimizationTracker = new PathTracker();
  18865. this.entryModules = [];
  18866. this.modulesById = new Map();
  18867. this.needsTreeshakingPass = false;
  18868. this.phase = BuildPhase.LOAD_AND_PARSE;
  18869. this.scope = new GlobalScope();
  18870. this.watchFiles = Object.create(null);
  18871. this.watchMode = false;
  18872. this.externalModules = [];
  18873. this.implicitEntryModules = [];
  18874. this.modules = [];
  18875. this.getModuleInfo = (moduleId) => {
  18876. const foundModule = this.modulesById.get(moduleId);
  18877. if (!foundModule)
  18878. return null;
  18879. return foundModule.info;
  18880. };
  18881. if (options.cache !== false) {
  18882. if (options.cache?.modules) {
  18883. for (const module of options.cache.modules)
  18884. this.cachedModules.set(module.id, module);
  18885. }
  18886. this.pluginCache = options.cache?.plugins || Object.create(null);
  18887. // increment access counter
  18888. for (const name in this.pluginCache) {
  18889. const cache = this.pluginCache[name];
  18890. for (const value of Object.values(cache))
  18891. value[0]++;
  18892. }
  18893. }
  18894. if (watcher) {
  18895. this.watchMode = true;
  18896. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  18897. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  18898. watcher.onCurrentRun('change', handleChange);
  18899. watcher.onCurrentRun('close', handleClose);
  18900. }
  18901. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  18902. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  18903. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  18904. this.pureFunctions = getPureFunctions(options);
  18905. }
  18906. async build() {
  18907. timeStart('generate module graph', 2);
  18908. await this.generateModuleGraph();
  18909. timeEnd('generate module graph', 2);
  18910. timeStart('sort and bind modules', 2);
  18911. this.phase = BuildPhase.ANALYSE;
  18912. this.sortModules();
  18913. timeEnd('sort and bind modules', 2);
  18914. timeStart('mark included statements', 2);
  18915. this.includeStatements();
  18916. timeEnd('mark included statements', 2);
  18917. this.phase = BuildPhase.GENERATE;
  18918. }
  18919. getCache() {
  18920. // handle plugin cache eviction
  18921. for (const name in this.pluginCache) {
  18922. const cache = this.pluginCache[name];
  18923. let allDeleted = true;
  18924. for (const [key, value] of Object.entries(cache)) {
  18925. if (value[0] >= this.options.experimentalCacheExpiry)
  18926. delete cache[key];
  18927. else
  18928. allDeleted = false;
  18929. }
  18930. if (allDeleted)
  18931. delete this.pluginCache[name];
  18932. }
  18933. return {
  18934. modules: this.modules.map(module => module.toJSON()),
  18935. plugins: this.pluginCache
  18936. };
  18937. }
  18938. async generateModuleGraph() {
  18939. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  18940. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  18941. if (this.entryModules.length === 0) {
  18942. throw new Error('You must supply options.input to rollup');
  18943. }
  18944. for (const module of this.modulesById.values()) {
  18945. module.cacheInfoGetters();
  18946. if (module instanceof Module) {
  18947. this.modules.push(module);
  18948. }
  18949. else {
  18950. this.externalModules.push(module);
  18951. }
  18952. }
  18953. }
  18954. includeStatements() {
  18955. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  18956. for (const module of entryModules) {
  18957. markModuleAndImpureDependenciesAsExecuted(module);
  18958. }
  18959. if (this.options.treeshake) {
  18960. let treeshakingPass = 1;
  18961. do {
  18962. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  18963. this.needsTreeshakingPass = false;
  18964. for (const module of this.modules) {
  18965. if (module.isExecuted) {
  18966. if (module.info.moduleSideEffects === 'no-treeshake') {
  18967. module.includeAllInBundle();
  18968. }
  18969. else {
  18970. module.include();
  18971. }
  18972. }
  18973. }
  18974. if (treeshakingPass === 1) {
  18975. // We only include exports after the first pass to avoid issues with
  18976. // the TDZ detection logic
  18977. for (const module of entryModules) {
  18978. if (module.preserveSignature !== false) {
  18979. module.includeAllExports(false);
  18980. this.needsTreeshakingPass = true;
  18981. }
  18982. }
  18983. }
  18984. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  18985. } while (this.needsTreeshakingPass);
  18986. }
  18987. else {
  18988. for (const module of this.modules)
  18989. module.includeAllInBundle();
  18990. }
  18991. for (const externalModule of this.externalModules)
  18992. externalModule.warnUnusedImports();
  18993. for (const module of this.implicitEntryModules) {
  18994. for (const dependant of module.implicitlyLoadedAfter) {
  18995. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  18996. error(logImplicitDependantIsNotIncluded(dependant));
  18997. }
  18998. }
  18999. }
  19000. }
  19001. sortModules() {
  19002. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  19003. for (const cyclePath of cyclePaths) {
  19004. this.options.onLog(LOGLEVEL_WARN, logCircularDependency(cyclePath));
  19005. }
  19006. this.modules = orderedModules;
  19007. for (const module of this.modules) {
  19008. module.bindReferences();
  19009. }
  19010. this.warnForMissingExports();
  19011. }
  19012. warnForMissingExports() {
  19013. for (const module of this.modules) {
  19014. for (const importDescription of module.importDescriptions.values()) {
  19015. if (importDescription.name !== '*' &&
  19016. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  19017. module.log(LOGLEVEL_WARN, logMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  19018. }
  19019. }
  19020. }
  19021. }
  19022. }
  19023. function formatAction([pluginName, hookName, parameters]) {
  19024. const action = `(${pluginName}) ${hookName}`;
  19025. const s = JSON.stringify;
  19026. switch (hookName) {
  19027. case 'resolveId': {
  19028. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  19029. }
  19030. case 'load': {
  19031. return `${action} ${s(parameters[0])}`;
  19032. }
  19033. case 'transform': {
  19034. return `${action} ${s(parameters[1])}`;
  19035. }
  19036. case 'shouldTransformCachedModule': {
  19037. return `${action} ${s(parameters[0].id)}`;
  19038. }
  19039. case 'moduleParsed': {
  19040. return `${action} ${s(parameters[0].id)}`;
  19041. }
  19042. }
  19043. return action;
  19044. }
  19045. let handleBeforeExit = null;
  19046. const rejectByPluginDriver = new Map();
  19047. async function catchUnfinishedHookActions(pluginDriver, callback) {
  19048. const emptyEventLoopPromise = new Promise((_, reject) => {
  19049. rejectByPluginDriver.set(pluginDriver, reject);
  19050. if (!handleBeforeExit) {
  19051. // We only ever create a single event listener to avoid max listener and
  19052. // other issues
  19053. handleBeforeExit = () => {
  19054. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  19055. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  19056. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  19057. [...unfulfilledActions].map(formatAction).join('\n')));
  19058. }
  19059. };
  19060. process$1.once('beforeExit', handleBeforeExit);
  19061. }
  19062. });
  19063. try {
  19064. return await Promise.race([callback(), emptyEventLoopPromise]);
  19065. }
  19066. finally {
  19067. rejectByPluginDriver.delete(pluginDriver);
  19068. if (rejectByPluginDriver.size === 0) {
  19069. process$1.off('beforeExit', handleBeforeExit);
  19070. handleBeforeExit = null;
  19071. }
  19072. }
  19073. }
  19074. async function initWasm() { }
  19075. function getLogger(plugins, onLog, watchMode, logLevel) {
  19076. plugins = getSortedValidatedPlugins('onLog', plugins);
  19077. const minimalPriority = logLevelPriority[logLevel];
  19078. const logger = (level, log, skipped = EMPTY_SET) => {
  19079. augmentLogMessage(log);
  19080. const logPriority = logLevelPriority[level];
  19081. if (logPriority < minimalPriority) {
  19082. return;
  19083. }
  19084. for (const plugin of plugins) {
  19085. if (skipped.has(plugin))
  19086. continue;
  19087. const { onLog: pluginOnLog } = plugin;
  19088. const getLogHandler = (level) => {
  19089. if (logLevelPriority[level] < minimalPriority) {
  19090. return doNothing;
  19091. }
  19092. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  19093. };
  19094. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  19095. if (handler.call({
  19096. debug: getLogHandler(LOGLEVEL_DEBUG),
  19097. error: (log) => error(normalizeLog(log)),
  19098. info: getLogHandler(LOGLEVEL_INFO),
  19099. meta: { rollupVersion: version, watchMode },
  19100. warn: getLogHandler(LOGLEVEL_WARN)
  19101. }, level, log) === false) {
  19102. return;
  19103. }
  19104. }
  19105. onLog(level, log);
  19106. };
  19107. return logger;
  19108. }
  19109. function ensureArray(items) {
  19110. if (Array.isArray(items)) {
  19111. return items.filter(Boolean);
  19112. }
  19113. if (items) {
  19114. return [items];
  19115. }
  19116. return [];
  19117. }
  19118. async function normalizeInputOptions(config, watchMode) {
  19119. // These are options that may trigger special warnings or behaviour later
  19120. // if the user did not select an explicit value
  19121. const unsetOptions = new Set();
  19122. const context = config.context ?? 'undefined';
  19123. const plugins = await normalizePluginOption(config.plugins);
  19124. const logLevel = config.logLevel || LOGLEVEL_INFO;
  19125. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  19126. const strictDeprecations = config.strictDeprecations || false;
  19127. const maxParallelFileOps = getMaxParallelFileOps(config);
  19128. const options = {
  19129. cache: getCache(config),
  19130. context,
  19131. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  19132. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  19133. external: getIdMatcher(config.external),
  19134. input: getInput(config),
  19135. logLevel,
  19136. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  19137. maxParallelFileOps,
  19138. moduleContext: getModuleContext(config, context),
  19139. onLog,
  19140. perf: config.perf || false,
  19141. plugins,
  19142. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  19143. preserveSymlinks: config.preserveSymlinks || false,
  19144. shimMissingExports: config.shimMissingExports || false,
  19145. strictDeprecations,
  19146. treeshake: getTreeshake(config)
  19147. };
  19148. warnUnknownOptions(config, [...Object.keys(options), 'onwarn', 'watch'], 'input options', onLog, /^(output)$/);
  19149. return { options, unsetOptions };
  19150. }
  19151. const getCache = (config) => config.cache === true // `true` is the default
  19152. ? undefined
  19153. : config.cache?.cache || config.cache;
  19154. const getIdMatcher = (option) => {
  19155. if (option === true) {
  19156. return () => true;
  19157. }
  19158. if (typeof option === 'function') {
  19159. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  19160. }
  19161. if (option) {
  19162. const ids = new Set();
  19163. const matchers = [];
  19164. for (const value of ensureArray(option)) {
  19165. if (value instanceof RegExp) {
  19166. matchers.push(value);
  19167. }
  19168. else {
  19169. ids.add(value);
  19170. }
  19171. }
  19172. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  19173. }
  19174. return () => false;
  19175. };
  19176. const getInput = (config) => {
  19177. const configInput = config.input;
  19178. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  19179. };
  19180. const getMaxParallelFileOps = (config) => {
  19181. const maxParallelFileOps = config.maxParallelFileOps;
  19182. if (typeof maxParallelFileOps === 'number') {
  19183. if (maxParallelFileOps <= 0)
  19184. return Infinity;
  19185. return maxParallelFileOps;
  19186. }
  19187. return 20;
  19188. };
  19189. const getModuleContext = (config, context) => {
  19190. const configModuleContext = config.moduleContext;
  19191. if (typeof configModuleContext === 'function') {
  19192. return id => configModuleContext(id) ?? context;
  19193. }
  19194. if (configModuleContext) {
  19195. const contextByModuleId = Object.create(null);
  19196. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  19197. contextByModuleId[resolve$1(key)] = moduleContext;
  19198. }
  19199. return id => contextByModuleId[id] ?? context;
  19200. }
  19201. return () => context;
  19202. };
  19203. const getTreeshake = (config) => {
  19204. const configTreeshake = config.treeshake;
  19205. if (configTreeshake === false) {
  19206. return false;
  19207. }
  19208. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ');
  19209. return {
  19210. annotations: configWithPreset.annotations !== false,
  19211. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  19212. manualPureFunctions: configWithPreset.manualPureFunctions ?? EMPTY_ARRAY,
  19213. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  19214. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  19215. ? 'always'
  19216. : configWithPreset.propertyReadSideEffects !== false,
  19217. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  19218. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  19219. };
  19220. };
  19221. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  19222. if (typeof moduleSideEffectsOption === 'boolean') {
  19223. return () => moduleSideEffectsOption;
  19224. }
  19225. if (moduleSideEffectsOption === 'no-external') {
  19226. return (_id, external) => !external;
  19227. }
  19228. if (typeof moduleSideEffectsOption === 'function') {
  19229. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  19230. }
  19231. if (Array.isArray(moduleSideEffectsOption)) {
  19232. const ids = new Set(moduleSideEffectsOption);
  19233. return id => ids.has(id);
  19234. }
  19235. if (moduleSideEffectsOption) {
  19236. error(logInvalidOption('treeshake.moduleSideEffects', URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  19237. }
  19238. return () => true;
  19239. };
  19240. // https://datatracker.ietf.org/doc/html/rfc2396
  19241. // eslint-disable-next-line no-control-regex
  19242. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$&*+,:;<=>?[\]^`{|}\u007F]/g;
  19243. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  19244. function sanitizeFileName(name) {
  19245. const match = DRIVE_LETTER_REGEX.exec(name);
  19246. const driveLetter = match ? match[0] : '';
  19247. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  19248. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  19249. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  19250. }
  19251. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  19252. // These are options that may trigger special warnings or behaviour later
  19253. // if the user did not select an explicit value
  19254. const unsetOptions = new Set(unsetInputOptions);
  19255. const compact = config.compact || false;
  19256. const format = getFormat(config);
  19257. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  19258. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  19259. const file = getFile(config, preserveModules, inputOptions);
  19260. const generatedCode = getGeneratedCode(config);
  19261. const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
  19262. const outputOptions = {
  19263. amd: getAmd(config),
  19264. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  19265. banner: getAddon(config, 'banner'),
  19266. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  19267. compact,
  19268. dir: getDir(config, file),
  19269. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  19270. entryFileNames: getEntryFileNames(config, unsetOptions),
  19271. esModule: config.esModule ?? 'if-default-prop',
  19272. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  19273. exports: getExports(config, unsetOptions),
  19274. extend: config.extend || false,
  19275. externalImportAssertions: externalImportAttributes,
  19276. externalImportAttributes,
  19277. externalLiveBindings: config.externalLiveBindings ?? true,
  19278. file,
  19279. footer: getAddon(config, 'footer'),
  19280. format,
  19281. freeze: config.freeze ?? true,
  19282. generatedCode,
  19283. globals: config.globals || {},
  19284. hashCharacters: config.hashCharacters ?? 'base64',
  19285. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  19286. importAttributesKey: config.importAttributesKey ?? 'assert',
  19287. indent: getIndent(config, compact),
  19288. inlineDynamicImports,
  19289. interop: getInterop(config),
  19290. intro: getAddon(config, 'intro'),
  19291. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules),
  19292. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  19293. name: config.name,
  19294. noConflict: config.noConflict || false,
  19295. outro: getAddon(config, 'outro'),
  19296. paths: config.paths || {},
  19297. plugins: await normalizePluginOption(config.plugins),
  19298. preserveModules,
  19299. preserveModulesRoot: getPreserveModulesRoot(config),
  19300. reexportProtoFromExternal: config.reexportProtoFromExternal ?? true,
  19301. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  19302. ? config.sanitizeFileName
  19303. : config.sanitizeFileName === false
  19304. ? id => id
  19305. : sanitizeFileName,
  19306. sourcemap: config.sourcemap || false,
  19307. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  19308. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  19309. sourcemapFile: config.sourcemapFile,
  19310. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  19311. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  19312. ? config.sourcemapIgnoreList
  19313. : config.sourcemapIgnoreList === false
  19314. ? () => false
  19315. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  19316. sourcemapPathTransform: config.sourcemapPathTransform,
  19317. strict: config.strict ?? true,
  19318. systemNullSetters: config.systemNullSetters ?? true,
  19319. validate: config.validate || false
  19320. };
  19321. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  19322. return { options: outputOptions, unsetOptions };
  19323. }
  19324. const getFile = (config, preserveModules, inputOptions) => {
  19325. const { file } = config;
  19326. if (typeof file === 'string') {
  19327. if (preserveModules) {
  19328. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  19329. }
  19330. if (!Array.isArray(inputOptions.input))
  19331. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  19332. }
  19333. return file;
  19334. };
  19335. const getFormat = (config) => {
  19336. const configFormat = config.format;
  19337. switch (configFormat) {
  19338. case undefined:
  19339. case 'es':
  19340. case 'esm':
  19341. case 'module': {
  19342. return 'es';
  19343. }
  19344. case 'cjs':
  19345. case 'commonjs': {
  19346. return 'cjs';
  19347. }
  19348. case 'system':
  19349. case 'systemjs': {
  19350. return 'system';
  19351. }
  19352. case 'amd':
  19353. case 'iife':
  19354. case 'umd': {
  19355. return configFormat;
  19356. }
  19357. default: {
  19358. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  19359. }
  19360. }
  19361. };
  19362. const getInlineDynamicImports = (config, inputOptions) => {
  19363. const inlineDynamicImports = config.inlineDynamicImports || false;
  19364. const { input } = inputOptions;
  19365. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  19366. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  19367. }
  19368. return inlineDynamicImports;
  19369. };
  19370. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  19371. const preserveModules = config.preserveModules || false;
  19372. if (preserveModules) {
  19373. if (inlineDynamicImports) {
  19374. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  19375. }
  19376. if (inputOptions.preserveEntrySignatures === false) {
  19377. return error(logInvalidOption('preserveEntrySignatures', URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  19378. }
  19379. }
  19380. return preserveModules;
  19381. };
  19382. const getPreserveModulesRoot = (config) => {
  19383. const { preserveModulesRoot } = config;
  19384. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  19385. return undefined;
  19386. }
  19387. return resolve$1(preserveModulesRoot);
  19388. };
  19389. const getAmd = (config) => {
  19390. const mergedOption = {
  19391. autoId: false,
  19392. basePath: '',
  19393. define: 'define',
  19394. forceJsExtensionForImports: false,
  19395. ...config.amd
  19396. };
  19397. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  19398. return error(logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  19399. }
  19400. if (mergedOption.basePath && !mergedOption.autoId) {
  19401. return error(logInvalidOption('output.amd.basePath', URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  19402. }
  19403. return mergedOption.autoId
  19404. ? {
  19405. autoId: true,
  19406. basePath: mergedOption.basePath,
  19407. define: mergedOption.define,
  19408. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  19409. }
  19410. : {
  19411. autoId: false,
  19412. define: mergedOption.define,
  19413. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  19414. id: mergedOption.id
  19415. };
  19416. };
  19417. const getAddon = (config, name) => {
  19418. const configAddon = config[name];
  19419. if (typeof configAddon === 'function') {
  19420. return configAddon;
  19421. }
  19422. return () => configAddon || '';
  19423. };
  19424. // eslint-disable-next-line unicorn/prevent-abbreviations
  19425. const getDir = (config, file) => {
  19426. const { dir } = config;
  19427. if (typeof dir === 'string' && typeof file === 'string') {
  19428. 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'));
  19429. }
  19430. return dir;
  19431. };
  19432. const getEntryFileNames = (config, unsetOptions) => {
  19433. const configEntryFileNames = config.entryFileNames;
  19434. if (configEntryFileNames == null) {
  19435. unsetOptions.add('entryFileNames');
  19436. }
  19437. return configEntryFileNames ?? '[name].js';
  19438. };
  19439. function getExports(config, unsetOptions) {
  19440. const configExports = config.exports;
  19441. if (configExports == null) {
  19442. unsetOptions.add('exports');
  19443. }
  19444. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  19445. return error(logInvalidExportOptionValue(configExports));
  19446. }
  19447. return configExports || 'auto';
  19448. }
  19449. const getExternalImportAttributes = (config, inputOptions) => {
  19450. if (config.externalImportAssertions != undefined) {
  19451. warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
  19452. }
  19453. return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
  19454. };
  19455. const getGeneratedCode = (config) => {
  19456. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
  19457. return {
  19458. arrowFunctions: configWithPreset.arrowFunctions === true,
  19459. constBindings: configWithPreset.constBindings === true,
  19460. objectShorthand: configWithPreset.objectShorthand === true,
  19461. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  19462. symbols: configWithPreset.symbols === true
  19463. };
  19464. };
  19465. const getIndent = (config, compact) => {
  19466. if (compact) {
  19467. return '';
  19468. }
  19469. const configIndent = config.indent;
  19470. return configIndent === false ? '' : configIndent ?? true;
  19471. };
  19472. const ALLOWED_INTEROP_TYPES = new Set([
  19473. 'compat',
  19474. 'auto',
  19475. 'esModule',
  19476. 'default',
  19477. 'defaultOnly'
  19478. ]);
  19479. const getInterop = (config) => {
  19480. const configInterop = config.interop;
  19481. if (typeof configInterop === 'function') {
  19482. const interopPerId = Object.create(null);
  19483. let defaultInterop = null;
  19484. return id => id === null
  19485. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  19486. : id in interopPerId
  19487. ? interopPerId[id]
  19488. : validateInterop((interopPerId[id] = configInterop(id)));
  19489. }
  19490. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  19491. };
  19492. const validateInterop = (interop) => {
  19493. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  19494. return error(logInvalidOption('output.interop', URL_OUTPUT_INTEROP,
  19495. // eslint-disable-next-line unicorn/prefer-spread
  19496. `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  19497. }
  19498. return interop;
  19499. };
  19500. const getManualChunks = (config, inlineDynamicImports, preserveModules) => {
  19501. const configManualChunks = config.manualChunks;
  19502. if (configManualChunks) {
  19503. if (inlineDynamicImports) {
  19504. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  19505. }
  19506. if (preserveModules) {
  19507. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  19508. }
  19509. }
  19510. return configManualChunks || {};
  19511. };
  19512. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  19513. const getSourcemapFileNames = (config, unsetOptions) => {
  19514. const configSourcemapFileNames = config.sourcemapFileNames;
  19515. if (configSourcemapFileNames == null) {
  19516. unsetOptions.add('sourcemapFileNames');
  19517. }
  19518. return configSourcemapFileNames;
  19519. };
  19520. const getSourcemapBaseUrl = (config) => {
  19521. const { sourcemapBaseUrl } = config;
  19522. if (sourcemapBaseUrl) {
  19523. if (isValidUrl(sourcemapBaseUrl)) {
  19524. return addTrailingSlashIfMissed(sourcemapBaseUrl);
  19525. }
  19526. return error(logInvalidOption('output.sourcemapBaseUrl', URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  19527. }
  19528. };
  19529. function rollup(rawInputOptions) {
  19530. return rollupInternal(rawInputOptions, null);
  19531. }
  19532. async function rollupInternal(rawInputOptions, watcher) {
  19533. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  19534. initialiseTimers(inputOptions);
  19535. await initWasm();
  19536. const graph = new Graph(inputOptions, watcher);
  19537. // remove the cache object from the memory after graph creation (cache is not used anymore)
  19538. const useCache = rawInputOptions.cache !== false;
  19539. if (rawInputOptions.cache) {
  19540. inputOptions.cache = undefined;
  19541. rawInputOptions.cache = undefined;
  19542. }
  19543. timeStart('BUILD', 1);
  19544. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  19545. try {
  19546. timeStart('initialize', 2);
  19547. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  19548. timeEnd('initialize', 2);
  19549. await graph.build();
  19550. }
  19551. catch (error_) {
  19552. const watchFiles = Object.keys(graph.watchFiles);
  19553. if (watchFiles.length > 0) {
  19554. error_.watchFiles = watchFiles;
  19555. }
  19556. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  19557. await graph.pluginDriver.hookParallel('closeBundle', []);
  19558. throw error_;
  19559. }
  19560. await graph.pluginDriver.hookParallel('buildEnd', []);
  19561. });
  19562. timeEnd('BUILD', 1);
  19563. const result = {
  19564. cache: useCache ? graph.getCache() : undefined,
  19565. async close() {
  19566. if (result.closed)
  19567. return;
  19568. result.closed = true;
  19569. await graph.pluginDriver.hookParallel('closeBundle', []);
  19570. },
  19571. closed: false,
  19572. async generate(rawOutputOptions) {
  19573. if (result.closed)
  19574. return error(logAlreadyClosed());
  19575. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  19576. },
  19577. get watchFiles() {
  19578. return Object.keys(graph.watchFiles);
  19579. },
  19580. async write(rawOutputOptions) {
  19581. if (result.closed)
  19582. return error(logAlreadyClosed());
  19583. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  19584. }
  19585. };
  19586. if (inputOptions.perf)
  19587. result.getTimings = getTimings;
  19588. return result;
  19589. }
  19590. async function getInputOptions(initialInputOptions, watchMode) {
  19591. if (!initialInputOptions) {
  19592. throw new Error('You must supply an options object to rollup');
  19593. }
  19594. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  19595. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  19596. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  19597. return { options, unsetOptions };
  19598. }
  19599. async function getProcessedInputOptions(inputOptions, watchMode) {
  19600. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  19601. const logLevel = inputOptions.logLevel || LOGLEVEL_INFO;
  19602. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  19603. for (const plugin of plugins) {
  19604. const { name, options } = plugin;
  19605. const handler = 'handler' in options ? options.handler : options;
  19606. const processedOptions = await handler.call({
  19607. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  19608. error: (error_) => error(logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  19609. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  19610. meta: { rollupVersion: version, watchMode },
  19611. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  19612. }, inputOptions);
  19613. if (processedOptions) {
  19614. inputOptions = processedOptions;
  19615. }
  19616. }
  19617. return inputOptions;
  19618. }
  19619. function normalizePlugins(plugins, anonymousPrefix) {
  19620. for (const [index, plugin] of plugins.entries()) {
  19621. if (!plugin.name) {
  19622. plugin.name = `${anonymousPrefix}${index + 1}`;
  19623. }
  19624. }
  19625. }
  19626. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  19627. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  19628. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  19629. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  19630. const generated = await bundle.generate(isWrite);
  19631. if (isWrite) {
  19632. timeStart('WRITE', 1);
  19633. if (!outputOptions.dir && !outputOptions.file) {
  19634. return error(logMissingFileOrDirOption());
  19635. }
  19636. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  19637. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  19638. timeEnd('WRITE', 1);
  19639. }
  19640. return createOutput(generated);
  19641. });
  19642. }
  19643. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  19644. if (!rawOutputOptions) {
  19645. throw new Error('You must supply an options object');
  19646. }
  19647. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  19648. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  19649. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  19650. return {
  19651. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  19652. outputPluginDriver
  19653. };
  19654. }
  19655. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  19656. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  19657. const emitError = () => pluginContext.error(logCannotEmitFromOptionsHook());
  19658. return {
  19659. ...pluginContext,
  19660. emitFile: emitError,
  19661. setAssetSource: emitError
  19662. };
  19663. }), inputOptions, unsetInputOptions);
  19664. }
  19665. function createOutput(outputBundle) {
  19666. return {
  19667. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  19668. };
  19669. }
  19670. var SortingFileType;
  19671. (function (SortingFileType) {
  19672. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  19673. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  19674. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  19675. })(SortingFileType || (SortingFileType = {}));
  19676. function getSortingFileType(file) {
  19677. if (file.type === 'asset') {
  19678. return SortingFileType.ASSET;
  19679. }
  19680. if (file.isEntry) {
  19681. return SortingFileType.ENTRY_CHUNK;
  19682. }
  19683. return SortingFileType.SECONDARY_CHUNK;
  19684. }
  19685. async function writeOutputFile(outputFile, outputOptions) {
  19686. const fileName = resolve$1(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  19687. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  19688. await mkdir(dirname(fileName), { recursive: true });
  19689. return writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  19690. }
  19691. /**
  19692. * Auxiliary function for defining rollup configuration
  19693. * Mainly to facilitate IDE code prompts, after all, export default does not
  19694. * prompt, even if you add @type annotations, it is not accurate
  19695. * @param options
  19696. */
  19697. function defineConfig(options) {
  19698. return options;
  19699. }
  19700. const {
  19701. env = {},
  19702. argv = [],
  19703. platform = "",
  19704. } = typeof process === "undefined" ? {} : process;
  19705. const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
  19706. const isForced = "FORCE_COLOR" in env || argv.includes("--color");
  19707. const isWindows = platform === "win32";
  19708. const isDumbTerminal = env.TERM === "dumb";
  19709. const isCompatibleTerminal =
  19710. tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
  19711. const isCI =
  19712. "CI" in env &&
  19713. ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
  19714. const isColorSupported =
  19715. !isDisabled &&
  19716. (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);
  19717. const replaceClose = (
  19718. index,
  19719. string,
  19720. close,
  19721. replace,
  19722. head = string.substring(0, index) + replace,
  19723. tail = string.substring(index + close.length),
  19724. next = tail.indexOf(close)
  19725. ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
  19726. const clearBleed = (index, string, open, close, replace) =>
  19727. index < 0
  19728. ? open + string + close
  19729. : open + replaceClose(index, string, close, replace) + close;
  19730. const filterEmpty =
  19731. (open, close, replace = open, at = open.length + 1) =>
  19732. (string) =>
  19733. string || !(string === "" || string === undefined)
  19734. ? clearBleed(
  19735. ("" + string).indexOf(close, at),
  19736. string,
  19737. open,
  19738. close,
  19739. replace
  19740. )
  19741. : "";
  19742. const init = (open, close, replace) =>
  19743. filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
  19744. const colors = {
  19745. reset: init(0, 0),
  19746. bold: init(1, 22, "\x1b[22m\x1b[1m"),
  19747. dim: init(2, 22, "\x1b[22m\x1b[2m"),
  19748. italic: init(3, 23),
  19749. underline: init(4, 24),
  19750. inverse: init(7, 27),
  19751. hidden: init(8, 28),
  19752. strikethrough: init(9, 29),
  19753. black: init(30, 39),
  19754. red: init(31, 39),
  19755. green: init(32, 39),
  19756. yellow: init(33, 39),
  19757. blue: init(34, 39),
  19758. magenta: init(35, 39),
  19759. cyan: init(36, 39),
  19760. white: init(37, 39),
  19761. gray: init(90, 39),
  19762. bgBlack: init(40, 49),
  19763. bgRed: init(41, 49),
  19764. bgGreen: init(42, 49),
  19765. bgYellow: init(43, 49),
  19766. bgBlue: init(44, 49),
  19767. bgMagenta: init(45, 49),
  19768. bgCyan: init(46, 49),
  19769. bgWhite: init(47, 49),
  19770. blackBright: init(90, 39),
  19771. redBright: init(91, 39),
  19772. greenBright: init(92, 39),
  19773. yellowBright: init(93, 39),
  19774. blueBright: init(94, 39),
  19775. magentaBright: init(95, 39),
  19776. cyanBright: init(96, 39),
  19777. whiteBright: init(97, 39),
  19778. bgBlackBright: init(100, 49),
  19779. bgRedBright: init(101, 49),
  19780. bgGreenBright: init(102, 49),
  19781. bgYellowBright: init(103, 49),
  19782. bgBlueBright: init(104, 49),
  19783. bgMagentaBright: init(105, 49),
  19784. bgCyanBright: init(106, 49),
  19785. bgWhiteBright: init(107, 49),
  19786. };
  19787. const createColors = ({ useColor = isColorSupported } = {}) =>
  19788. useColor
  19789. ? colors
  19790. : Object.keys(colors).reduce(
  19791. (colors, key) => ({ ...colors, [key]: String }),
  19792. {}
  19793. );
  19794. createColors();
  19795. // @see https://no-color.org
  19796. // @see https://www.npmjs.com/package/chalk
  19797. const { bold, cyan, dim, gray, green, red, underline, yellow } = createColors({
  19798. useColor: env$1.FORCE_COLOR !== '0' && !env$1.NO_COLOR
  19799. });
  19800. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  19801. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  19802. function handleError(error, recover = false) {
  19803. const name = error.name || error.cause?.name;
  19804. const nameSection = name ? `${name}: ` : '';
  19805. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  19806. const message = `${pluginSection}${nameSection}${error.message}`;
  19807. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  19808. if (error.url) {
  19809. outputLines.push(cyan(error.url));
  19810. }
  19811. if (error.loc) {
  19812. outputLines.push(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  19813. }
  19814. else if (error.id) {
  19815. outputLines.push(relativeId(error.id));
  19816. }
  19817. if (error.frame) {
  19818. outputLines.push(dim(error.frame));
  19819. }
  19820. if (error.stack) {
  19821. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  19822. }
  19823. // ES2022: Error.prototype.cause is optional
  19824. if (error.cause) {
  19825. let cause = error.cause;
  19826. const causeErrorLines = [];
  19827. let indent = '';
  19828. while (cause) {
  19829. indent += ' ';
  19830. const message = cause.stack || cause;
  19831. causeErrorLines.push(...`[cause] ${message}`.split('\n').map(line => indent + line));
  19832. cause = cause.cause;
  19833. }
  19834. outputLines.push(dim(causeErrorLines.join('\n')));
  19835. }
  19836. outputLines.push('', '');
  19837. stderr(outputLines.join('\n'));
  19838. if (!recover)
  19839. process$1.exit(1);
  19840. }
  19841. const commandAliases = {
  19842. c: 'config',
  19843. d: 'dir',
  19844. e: 'external',
  19845. f: 'format',
  19846. g: 'globals',
  19847. h: 'help',
  19848. i: 'input',
  19849. m: 'sourcemap',
  19850. n: 'name',
  19851. o: 'file',
  19852. p: 'plugin',
  19853. v: 'version',
  19854. w: 'watch'
  19855. };
  19856. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  19857. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  19858. const command = getCommandOptions(rawCommandOptions);
  19859. const plugins = await normalizePluginOption(config.plugins);
  19860. const logLevel = config.logLevel || LOGLEVEL_INFO;
  19861. const onLog = getOnLog(config, logLevel, printLog);
  19862. const log = getLogger(plugins, onLog, watchMode, logLevel);
  19863. const inputOptions = mergeInputOptions(config, command, plugins, log, onLog);
  19864. if (command.output) {
  19865. Object.assign(command, command.output);
  19866. }
  19867. const outputOptionsArray = ensureArray(config.output);
  19868. if (outputOptionsArray.length === 0)
  19869. outputOptionsArray.push({});
  19870. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  19871. warnUnknownOptions(command, [
  19872. ...Object.keys(inputOptions),
  19873. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  19874. ...Object.keys(commandAliases),
  19875. 'bundleConfigAsCjs',
  19876. 'config',
  19877. 'configPlugin',
  19878. 'environment',
  19879. 'failAfterWarnings',
  19880. 'filterLogs',
  19881. 'forceExit',
  19882. 'plugin',
  19883. 'silent',
  19884. 'stdin',
  19885. 'waitForBundleInput'
  19886. ], 'CLI flags', log, /^_$|output$|config/);
  19887. inputOptions.output = outputOptions;
  19888. return inputOptions;
  19889. }
  19890. function getCommandOptions(rawCommandOptions) {
  19891. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  19892. ? rawCommandOptions.external.split(',')
  19893. : [];
  19894. return {
  19895. ...rawCommandOptions,
  19896. external,
  19897. globals: typeof rawCommandOptions.globals === 'string'
  19898. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  19899. const [id, variableName] = globalDefinition.split(':');
  19900. globals[id] = variableName;
  19901. if (!external.includes(id)) {
  19902. external.push(id);
  19903. }
  19904. return globals;
  19905. }, Object.create(null))
  19906. : undefined
  19907. };
  19908. }
  19909. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  19910. const getOption = (name) => overrides[name] ?? config[name];
  19911. const inputOptions = {
  19912. cache: config.cache,
  19913. context: getOption('context'),
  19914. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  19915. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  19916. external: getExternal(config, overrides),
  19917. input: getOption('input') || [],
  19918. logLevel: getOption('logLevel'),
  19919. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  19920. maxParallelFileOps: getOption('maxParallelFileOps'),
  19921. moduleContext: getOption('moduleContext'),
  19922. onLog,
  19923. onwarn: undefined,
  19924. perf: getOption('perf'),
  19925. plugins,
  19926. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  19927. preserveSymlinks: getOption('preserveSymlinks'),
  19928. shimMissingExports: getOption('shimMissingExports'),
  19929. strictDeprecations: getOption('strictDeprecations'),
  19930. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ')),
  19931. watch: getWatch(config, overrides)
  19932. };
  19933. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  19934. return inputOptions;
  19935. }
  19936. const getExternal = (config, overrides) => {
  19937. const configExternal = config.external;
  19938. return typeof configExternal === 'function'
  19939. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  19940. : [...ensureArray(configExternal), ...overrides.external];
  19941. };
  19942. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  19943. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  19944. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  19945. if (commandOption !== undefined) {
  19946. return commandOption && { ...configOption, ...commandOption };
  19947. }
  19948. return configOption;
  19949. };
  19950. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  19951. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  19952. if (!optionValue) {
  19953. return optionValue;
  19954. }
  19955. if (Array.isArray(optionValue)) {
  19956. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  19957. }
  19958. return objectifyValue(optionValue);
  19959. };
  19960. async function mergeOutputOptions(config, overrides, log) {
  19961. const getOption = (name) => overrides[name] ?? config[name];
  19962. const outputOptions = {
  19963. amd: getObjectOption(config, overrides, 'amd'),
  19964. assetFileNames: getOption('assetFileNames'),
  19965. banner: getOption('banner'),
  19966. chunkFileNames: getOption('chunkFileNames'),
  19967. compact: getOption('compact'),
  19968. dir: getOption('dir'),
  19969. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  19970. entryFileNames: getOption('entryFileNames'),
  19971. esModule: getOption('esModule'),
  19972. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  19973. exports: getOption('exports'),
  19974. extend: getOption('extend'),
  19975. externalImportAssertions: getOption('externalImportAssertions'),
  19976. externalImportAttributes: getOption('externalImportAttributes'),
  19977. externalLiveBindings: getOption('externalLiveBindings'),
  19978. file: getOption('file'),
  19979. footer: getOption('footer'),
  19980. format: getOption('format'),
  19981. freeze: getOption('freeze'),
  19982. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '')),
  19983. globals: getOption('globals'),
  19984. hashCharacters: getOption('hashCharacters'),
  19985. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  19986. importAttributesKey: getOption('importAttributesKey'),
  19987. indent: getOption('indent'),
  19988. inlineDynamicImports: getOption('inlineDynamicImports'),
  19989. interop: getOption('interop'),
  19990. intro: getOption('intro'),
  19991. manualChunks: getOption('manualChunks'),
  19992. minifyInternalExports: getOption('minifyInternalExports'),
  19993. name: getOption('name'),
  19994. noConflict: getOption('noConflict'),
  19995. outro: getOption('outro'),
  19996. paths: getOption('paths'),
  19997. plugins: await normalizePluginOption(config.plugins),
  19998. preserveModules: getOption('preserveModules'),
  19999. preserveModulesRoot: getOption('preserveModulesRoot'),
  20000. reexportProtoFromExternal: getOption('reexportProtoFromExternal'),
  20001. sanitizeFileName: getOption('sanitizeFileName'),
  20002. sourcemap: getOption('sourcemap'),
  20003. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  20004. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  20005. sourcemapFile: getOption('sourcemapFile'),
  20006. sourcemapFileNames: getOption('sourcemapFileNames'),
  20007. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  20008. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  20009. strict: getOption('strict'),
  20010. systemNullSetters: getOption('systemNullSetters'),
  20011. validate: getOption('validate')
  20012. };
  20013. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  20014. return outputOptions;
  20015. }
  20016. class WatchEmitter {
  20017. constructor() {
  20018. this.currentHandlers = Object.create(null);
  20019. this.persistentHandlers = Object.create(null);
  20020. }
  20021. // Will be overwritten by Rollup
  20022. async close() { }
  20023. emit(event, ...parameters) {
  20024. return Promise.all([...this.getCurrentHandlers(event), ...this.getPersistentHandlers(event)].map(handler => handler(...parameters)));
  20025. }
  20026. off(event, listener) {
  20027. const listeners = this.persistentHandlers[event];
  20028. if (listeners) {
  20029. // A hack stolen from "mitt": ">>> 0" does not change numbers >= 0, but -1
  20030. // (which would remove the last array element if used unchanged) is turned
  20031. // into max_int, which is outside the array and does not change anything.
  20032. listeners.splice(listeners.indexOf(listener) >>> 0, 1);
  20033. }
  20034. return this;
  20035. }
  20036. on(event, listener) {
  20037. this.getPersistentHandlers(event).push(listener);
  20038. return this;
  20039. }
  20040. onCurrentRun(event, listener) {
  20041. this.getCurrentHandlers(event).push(listener);
  20042. return this;
  20043. }
  20044. once(event, listener) {
  20045. const selfRemovingListener = (...parameters) => {
  20046. this.off(event, selfRemovingListener);
  20047. return listener(...parameters);
  20048. };
  20049. this.on(event, selfRemovingListener);
  20050. return this;
  20051. }
  20052. removeAllListeners() {
  20053. this.removeListenersForCurrentRun();
  20054. this.persistentHandlers = Object.create(null);
  20055. return this;
  20056. }
  20057. removeListenersForCurrentRun() {
  20058. this.currentHandlers = Object.create(null);
  20059. return this;
  20060. }
  20061. getCurrentHandlers(event) {
  20062. return this.currentHandlers[event] || (this.currentHandlers[event] = []);
  20063. }
  20064. getPersistentHandlers(event) {
  20065. return this.persistentHandlers[event] || (this.persistentHandlers[event] = []);
  20066. }
  20067. }
  20068. let fsEvents;
  20069. let fsEventsImportError;
  20070. async function loadFsEvents() {
  20071. try {
  20072. ({ default: fsEvents } = await import('fsevents'));
  20073. }
  20074. catch (error) {
  20075. fsEventsImportError = error;
  20076. }
  20077. }
  20078. // A call to this function will be injected into the chokidar code
  20079. function getFsEvents() {
  20080. if (fsEventsImportError)
  20081. throw fsEventsImportError;
  20082. return fsEvents;
  20083. }
  20084. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  20085. __proto__: null,
  20086. getFsEvents,
  20087. loadFsEvents
  20088. }, Symbol.toStringTag, { value: 'Module' });
  20089. function watch(configs) {
  20090. const emitter = new WatchEmitter();
  20091. watchInternal(configs, emitter).catch(error => {
  20092. handleError(error);
  20093. });
  20094. return emitter;
  20095. }
  20096. async function watchInternal(configs, emitter) {
  20097. const optionsList = await Promise.all(ensureArray(configs).map(config => mergeOptions(config, true)));
  20098. const watchOptionsList = optionsList.filter(config => config.watch !== false);
  20099. if (watchOptionsList.length === 0) {
  20100. return error(logInvalidOption('watch', URL_WATCH, 'there must be at least one config where "watch" is not set to "false"'));
  20101. }
  20102. await loadFsEvents();
  20103. const { Watcher } = await import('./watch.js');
  20104. new Watcher(watchOptionsList, emitter);
  20105. }
  20106. export { createFilter, defineConfig, fseventsImporter, getAugmentedNamespace, picomatch, rollup, rollupInternal, version, watch };