rollup.js 954 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988
  1. /*
  2. @license
  3. Rollup.js v3.18.0
  4. Wed, 01 Mar 2023 18:45:12 GMT - commit 25bdc129d21685b69a00ee55397d42ac6eff6449
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. const process$1 = require('node:process');
  10. const tty = require('tty');
  11. const node_path = require('node:path');
  12. const require$$0$1 = require('path');
  13. const node_perf_hooks = require('node:perf_hooks');
  14. const node_crypto = require('node:crypto');
  15. const promises = require('node:fs/promises');
  16. const node_events = require('node:events');
  17. function _interopNamespaceDefault(e) {
  18. const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
  19. if (e) {
  20. for (const k in e) {
  21. n[k] = e[k];
  22. }
  23. }
  24. n.default = e;
  25. return n;
  26. }
  27. const tty__namespace = /*#__PURE__*/_interopNamespaceDefault(tty);
  28. var version$1 = "3.18.0";
  29. function ensureArray$1(items) {
  30. if (Array.isArray(items)) {
  31. return items.filter(Boolean);
  32. }
  33. if (items) {
  34. return [items];
  35. }
  36. return [];
  37. }
  38. // troubleshooting
  39. const URL_AVOIDING_EVAL = 'troubleshooting/#avoiding-eval';
  40. const URL_NAME_IS_NOT_EXPORTED = 'troubleshooting/#error-name-is-not-exported-by-module';
  41. const URL_THIS_IS_UNDEFINED = 'troubleshooting/#error-this-is-undefined';
  42. const URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY = 'troubleshooting/#warning-treating-module-as-external-dependency';
  43. const URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT = 'troubleshooting/#warning-sourcemap-is-likely-to-be-incorrect';
  44. // configuration-options
  45. const URL_MAXPARALLELFILEOPS = 'configuration-options/#maxparallelfileops';
  46. const URL_OUTPUT_AMD_ID = 'configuration-options/#output-amd-id';
  47. const URL_OUTPUT_AMD_BASEPATH = 'configuration-options/#output-amd-basepath';
  48. const URL_OUTPUT_DIR = 'configuration-options/#output-dir';
  49. const URL_OUTPUT_DYNAMICIMPORTFUNCTION = 'configuration-options/#output-dynamicimportfunction';
  50. const URL_OUTPUT_EXPORTS = 'configuration-options/#output-exports';
  51. const URL_OUTPUT_EXTEND = 'configuration-options/#output-extend';
  52. const URL_OUTPUT_FORMAT = 'configuration-options/#output-format';
  53. const URL_OUTPUT_GENERATEDCODE = 'configuration-options/#output-generatedcode';
  54. const URL_OUTPUT_EXPERIMENTALDEEPCHUNKOPTIMIZATION = 'configuration-options/#output-experimentaldeepdynamicchunkoptimization';
  55. const URL_OUTPUT_GENERATEDCODE_CONSTBINDINGS = 'configuration-options/#output-generatedcode-constbindings';
  56. const URL_OUTPUT_GENERATEDCODE_SYMBOLS = 'configuration-options/#output-generatedcode-symbols';
  57. const URL_OUTPUT_GLOBALS = 'configuration-options/#output-globals';
  58. const URL_OUTPUT_INLINEDYNAMICIMPORTS = 'configuration-options/#output-inlinedynamicimports';
  59. const URL_OUTPUT_INTEROP = 'configuration-options/#output-interop';
  60. const URL_OUTPUT_MANUALCHUNKS = 'configuration-options/#output-manualchunks';
  61. const URL_OUTPUT_NAME = 'configuration-options/#output-name';
  62. const URL_OUTPUT_PRESERVEMODULES = 'configuration-options/#output-preservemodules';
  63. const URL_OUTPUT_SOURCEMAPBASEURL = 'configuration-options/#output-sourcemapbaseurl';
  64. const URL_OUTPUT_SOURCEMAPFILE = 'configuration-options/#output-sourcemapfile';
  65. const URL_PRESERVEENTRYSIGNATURES = 'configuration-options/#preserveentrysignatures';
  66. const URL_TREESHAKE = 'configuration-options/#treeshake';
  67. const URL_TREESHAKE_MODULESIDEEFFECTS = 'configuration-options/#treeshake-modulesideeffects';
  68. const URL_WATCH = 'configuration-options/#watch';
  69. // command-line-interface
  70. const URL_BUNDLE_CONFIG_AS_CJS = 'command-line-interface/#bundleconfigascjs';
  71. const URL_CONFIGURATION_FILES = 'command-line-interface/#configuration-files';
  72. const URL_RENDERDYNAMICIMPORT = 'plugin-development/#renderdynamicimport';
  73. const URL_THIS_GETMODULEIDS = 'plugin-development/#this-getmoduleids';
  74. const URL_THIS_GETMODULEINFO = 'plugin-development/#this-getmoduleinfo';
  75. async function asyncFlatten(array) {
  76. do {
  77. array = (await Promise.all(array)).flat(Infinity);
  78. } while (array.some((v) => v?.then));
  79. return array;
  80. }
  81. const BLANK = Object.freeze(Object.create(null));
  82. const EMPTY_OBJECT = Object.freeze({});
  83. const EMPTY_ARRAY = Object.freeze([]);
  84. function getLocator$1(source, options) {
  85. if (options === void 0) { options = {}; }
  86. var offsetLine = options.offsetLine || 0;
  87. var offsetColumn = options.offsetColumn || 0;
  88. var originalLines = source.split('\n');
  89. var start = 0;
  90. var lineRanges = originalLines.map(function (line, i) {
  91. var end = start + line.length + 1;
  92. var range = { start: start, end: end, line: i };
  93. start = end;
  94. return range;
  95. });
  96. var i = 0;
  97. function rangeContains(range, index) {
  98. return range.start <= index && index < range.end;
  99. }
  100. function getLocation(range, index) {
  101. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  102. }
  103. function locate(search, startIndex) {
  104. if (typeof search === 'string') {
  105. search = source.indexOf(search, startIndex || 0);
  106. }
  107. var range = lineRanges[i];
  108. var d = search >= range.end ? 1 : -1;
  109. while (range) {
  110. if (rangeContains(range, search))
  111. return getLocation(range, search);
  112. i += d;
  113. range = lineRanges[i];
  114. }
  115. }
  116. return locate;
  117. }
  118. function locate(source, search, options) {
  119. if (typeof options === 'number') {
  120. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  121. }
  122. return getLocator$1(source, options)(search, options && options.startIndex);
  123. }
  124. function spaces(index) {
  125. let result = '';
  126. while (index--)
  127. result += ' ';
  128. return result;
  129. }
  130. function tabsToSpaces(value) {
  131. return value.replace(/^\t+/, match => match.split('\t').join(' '));
  132. }
  133. const LINE_TRUNCATE_LENGTH = 120;
  134. const MIN_CHARACTERS_SHOWN_AFTER_LOCATION = 10;
  135. const ELLIPSIS = '...';
  136. function getCodeFrame(source, line, column) {
  137. let lines = source.split('\n');
  138. const maxLineLength = Math.max(tabsToSpaces(lines[line - 1].slice(0, column)).length +
  139. MIN_CHARACTERS_SHOWN_AFTER_LOCATION +
  140. ELLIPSIS.length, LINE_TRUNCATE_LENGTH);
  141. const frameStart = Math.max(0, line - 3);
  142. let frameEnd = Math.min(line + 2, lines.length);
  143. lines = lines.slice(frameStart, frameEnd);
  144. while (!/\S/.test(lines[lines.length - 1])) {
  145. lines.pop();
  146. frameEnd -= 1;
  147. }
  148. const digits = String(frameEnd).length;
  149. return lines
  150. .map((sourceLine, index) => {
  151. const isErrorLine = frameStart + index + 1 === line;
  152. let lineNumber = String(index + frameStart + 1);
  153. while (lineNumber.length < digits)
  154. lineNumber = ` ${lineNumber}`;
  155. let displayedLine = tabsToSpaces(sourceLine);
  156. if (displayedLine.length > maxLineLength) {
  157. displayedLine = `${displayedLine.slice(0, maxLineLength - ELLIPSIS.length)}${ELLIPSIS}`;
  158. }
  159. if (isErrorLine) {
  160. const indicator = spaces(digits + 2 + tabsToSpaces(sourceLine.slice(0, column)).length) + '^';
  161. return `${lineNumber}: ${displayedLine}\n${indicator}`;
  162. }
  163. return `${lineNumber}: ${displayedLine}`;
  164. })
  165. .join('\n');
  166. }
  167. const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[/\\|])/;
  168. const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
  169. function isAbsolute(path) {
  170. return ABSOLUTE_PATH_REGEX.test(path);
  171. }
  172. function isRelative(path) {
  173. return RELATIVE_PATH_REGEX.test(path);
  174. }
  175. const BACKSLASH_REGEX = /\\/g;
  176. function normalize(path) {
  177. return path.replace(BACKSLASH_REGEX, '/');
  178. }
  179. function printQuotedStringList(list, verbs) {
  180. const isSingleItem = list.length <= 1;
  181. const quotedList = list.map(item => `"${item}"`);
  182. let output = isSingleItem
  183. ? quotedList[0]
  184. : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
  185. if (verbs) {
  186. output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
  187. }
  188. return output;
  189. }
  190. const ANY_SLASH_REGEX = /[/\\]/;
  191. function relative(from, to) {
  192. const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
  193. const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
  194. if (fromParts[0] === '.')
  195. fromParts.shift();
  196. if (toParts[0] === '.')
  197. toParts.shift();
  198. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  199. fromParts.shift();
  200. toParts.shift();
  201. }
  202. while (toParts[0] === '..' && fromParts.length > 0) {
  203. toParts.shift();
  204. fromParts.pop();
  205. }
  206. while (fromParts.pop()) {
  207. toParts.unshift('..');
  208. }
  209. return toParts.join('/');
  210. }
  211. function getAliasName(id) {
  212. const base = node_path.basename(id);
  213. return base.slice(0, Math.max(0, base.length - node_path.extname(id).length));
  214. }
  215. function relativeId(id) {
  216. if (!isAbsolute(id))
  217. return id;
  218. return relative(node_path.resolve(), id);
  219. }
  220. function isPathFragment(name) {
  221. // starting with "/", "./", "../", "C:/"
  222. return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
  223. }
  224. const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
  225. function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
  226. let relativePath = normalize(relative(node_path.dirname(importerId), targetPath));
  227. if (stripJsExtension && relativePath.endsWith('.js')) {
  228. relativePath = relativePath.slice(0, -3);
  229. }
  230. if (ensureFileName) {
  231. if (relativePath === '')
  232. return '../' + node_path.basename(targetPath);
  233. if (UPPER_DIR_REGEX.test(relativePath)) {
  234. return [...relativePath.split('/'), '..', node_path.basename(targetPath)].join('/');
  235. }
  236. }
  237. return relativePath ? (relativePath.startsWith('..') ? relativePath : './' + relativePath) : '.';
  238. }
  239. function isValidUrl(url) {
  240. try {
  241. new URL(url);
  242. }
  243. catch {
  244. return false;
  245. }
  246. return true;
  247. }
  248. function getRollupUrl(snippet) {
  249. return `https://rollupjs.org/${snippet}`;
  250. }
  251. function error(base) {
  252. if (!(base instanceof Error)) {
  253. base = Object.assign(new Error(base.message), base);
  254. Object.defineProperty(base, 'name', { value: 'RollupError' });
  255. }
  256. throw base;
  257. }
  258. function augmentCodeLocation(properties, pos, source, id) {
  259. if (typeof pos === 'object') {
  260. const { line, column } = pos;
  261. properties.loc = { column, file: id, line };
  262. }
  263. else {
  264. properties.pos = pos;
  265. const { line, column } = locate(source, pos, { offsetLine: 1 });
  266. properties.loc = { column, file: id, line };
  267. }
  268. if (properties.frame === undefined) {
  269. const { line, column } = properties.loc;
  270. properties.frame = getCodeFrame(source, line, column);
  271. }
  272. }
  273. // Error codes should be sorted alphabetically while errors should be sorted by
  274. // error code below
  275. const ADDON_ERROR = 'ADDON_ERROR', ALREADY_CLOSED = 'ALREADY_CLOSED', AMBIGUOUS_EXTERNAL_NAMESPACES = 'AMBIGUOUS_EXTERNAL_NAMESPACES', ANONYMOUS_PLUGIN_CACHE = 'ANONYMOUS_PLUGIN_CACHE', ASSET_NOT_FINALISED = 'ASSET_NOT_FINALISED', ASSET_NOT_FOUND = 'ASSET_NOT_FOUND', ASSET_SOURCE_ALREADY_SET = 'ASSET_SOURCE_ALREADY_SET', ASSET_SOURCE_MISSING = 'ASSET_SOURCE_MISSING', BAD_LOADER = 'BAD_LOADER', CANNOT_CALL_NAMESPACE = 'CANNOT_CALL_NAMESPACE', CANNOT_EMIT_FROM_OPTIONS_HOOK = 'CANNOT_EMIT_FROM_OPTIONS_HOOK', CHUNK_NOT_GENERATED = 'CHUNK_NOT_GENERATED', CHUNK_INVALID = 'CHUNK_INVALID', CIRCULAR_DEPENDENCY = 'CIRCULAR_DEPENDENCY', CIRCULAR_REEXPORT = 'CIRCULAR_REEXPORT', CYCLIC_CROSS_CHUNK_REEXPORT = 'CYCLIC_CROSS_CHUNK_REEXPORT', DEPRECATED_FEATURE = 'DEPRECATED_FEATURE', DUPLICATE_IMPORT_OPTIONS = 'DUPLICATE_IMPORT_OPTIONS', DUPLICATE_PLUGIN_NAME = 'DUPLICATE_PLUGIN_NAME', EMPTY_BUNDLE = 'EMPTY_BUNDLE', EVAL = 'EVAL', EXTERNAL_SYNTHETIC_EXPORTS = 'EXTERNAL_SYNTHETIC_EXPORTS', FAIL_AFTER_WARNINGS = 'FAIL_AFTER_WARNINGS', FILE_NAME_CONFLICT = 'FILE_NAME_CONFLICT', FILE_NOT_FOUND = 'FILE_NOT_FOUND', ILLEGAL_IDENTIFIER_AS_NAME = 'ILLEGAL_IDENTIFIER_AS_NAME', ILLEGAL_REASSIGNMENT = 'ILLEGAL_REASSIGNMENT', INCONSISTENT_IMPORT_ASSERTIONS = 'INCONSISTENT_IMPORT_ASSERTIONS', INPUT_HOOK_IN_OUTPUT_PLUGIN = 'INPUT_HOOK_IN_OUTPUT_PLUGIN', INVALID_CHUNK = 'INVALID_CHUNK', INVALID_CONFIG_MODULE_FORMAT = 'INVALID_CONFIG_MODULE_FORMAT', INVALID_EXPORT_OPTION = 'INVALID_EXPORT_OPTION', INVALID_EXTERNAL_ID = 'INVALID_EXTERNAL_ID', INVALID_OPTION = 'INVALID_OPTION', INVALID_PLUGIN_HOOK = 'INVALID_PLUGIN_HOOK', INVALID_ROLLUP_PHASE = 'INVALID_ROLLUP_PHASE', INVALID_SETASSETSOURCE = 'INVALID_SETASSETSOURCE', INVALID_TLA_FORMAT = 'INVALID_TLA_FORMAT', MISSING_CONFIG = 'MISSING_CONFIG', MISSING_EXPORT = 'MISSING_EXPORT', MISSING_EXTERNAL_CONFIG = 'MISSING_EXTERNAL_CONFIG', MISSING_GLOBAL_NAME = 'MISSING_GLOBAL_NAME', MISSING_IMPLICIT_DEPENDANT = 'MISSING_IMPLICIT_DEPENDANT', MISSING_NAME_OPTION_FOR_IIFE_EXPORT = 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT', MISSING_NODE_BUILTINS = 'MISSING_NODE_BUILTINS', MISSING_OPTION = 'MISSING_OPTION', MIXED_EXPORTS = 'MIXED_EXPORTS', MODULE_LEVEL_DIRECTIVE = 'MODULE_LEVEL_DIRECTIVE', NAMESPACE_CONFLICT = 'NAMESPACE_CONFLICT', NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE = 'NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE', ONLY_INLINE_SOURCEMAPS = 'ONLY_INLINE_SOURCEMAPS', PARSE_ERROR = 'PARSE_ERROR', PLUGIN_ERROR = 'PLUGIN_ERROR', SHIMMED_EXPORT = 'SHIMMED_EXPORT', SOURCEMAP_BROKEN = 'SOURCEMAP_BROKEN', SOURCEMAP_ERROR = 'SOURCEMAP_ERROR', SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT = 'SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT', THIS_IS_UNDEFINED = 'THIS_IS_UNDEFINED', UNEXPECTED_NAMED_IMPORT = 'UNEXPECTED_NAMED_IMPORT', UNKNOWN_OPTION = 'UNKNOWN_OPTION', UNRESOLVED_ENTRY = 'UNRESOLVED_ENTRY', UNRESOLVED_IMPORT = 'UNRESOLVED_IMPORT', UNUSED_EXTERNAL_IMPORT = 'UNUSED_EXTERNAL_IMPORT', VALIDATION_ERROR = 'VALIDATION_ERROR';
  276. function errorAddonNotGenerated(message, hook, plugin) {
  277. return {
  278. code: ADDON_ERROR,
  279. message: `Could not retrieve "${hook}". Check configuration of plugin "${plugin}".
  280. \tError Message: ${message}`
  281. };
  282. }
  283. function errorAlreadyClosed() {
  284. return {
  285. code: ALREADY_CLOSED,
  286. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  287. };
  288. }
  289. function errorAmbiguousExternalNamespaces(binding, reexportingModule, usedModule, sources) {
  290. return {
  291. binding,
  292. code: AMBIGUOUS_EXTERNAL_NAMESPACES,
  293. ids: sources,
  294. message: `Ambiguous external namespace resolution: "${relativeId(reexportingModule)}" re-exports "${binding}" from one of the external modules ${printQuotedStringList(sources.map(module => relativeId(module)))}, guessing "${relativeId(usedModule)}".`,
  295. reexporter: reexportingModule
  296. };
  297. }
  298. function errorAnonymousPluginCache() {
  299. return {
  300. code: ANONYMOUS_PLUGIN_CACHE,
  301. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  302. };
  303. }
  304. function errorAssetNotFinalisedForFileName(name) {
  305. return {
  306. code: ASSET_NOT_FINALISED,
  307. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first. If you reference assets via import.meta.ROLLUP_FILE_URL_<referenceId>, you need to either have set their source after "renderStart" or need to provide an explicit "fileName" when emitting them.`
  308. };
  309. }
  310. function errorAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  311. return {
  312. code: ASSET_NOT_FOUND,
  313. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  314. };
  315. }
  316. function errorAssetSourceAlreadySet(name) {
  317. return {
  318. code: ASSET_SOURCE_ALREADY_SET,
  319. message: `Unable to set the source for asset "${name}", source already set.`
  320. };
  321. }
  322. function errorNoAssetSourceSet(assetName) {
  323. return {
  324. code: ASSET_SOURCE_MISSING,
  325. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  326. };
  327. }
  328. function errorBadLoader(id) {
  329. return {
  330. code: BAD_LOADER,
  331. message: `Error loading "${relativeId(id)}": plugin load hook should return a string, a { code, map } object, or nothing/null.`
  332. };
  333. }
  334. function errorCannotCallNamespace(name) {
  335. return {
  336. code: CANNOT_CALL_NAMESPACE,
  337. message: `Cannot call a namespace ("${name}").`
  338. };
  339. }
  340. function errorCannotEmitFromOptionsHook() {
  341. return {
  342. code: CANNOT_EMIT_FROM_OPTIONS_HOOK,
  343. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  344. };
  345. }
  346. function errorChunkNotGeneratedForFileName(name) {
  347. return {
  348. code: CHUNK_NOT_GENERATED,
  349. message: `Plugin error - Unable to get file name for emitted chunk "${name}". You can only get file names once chunks have been generated after the "renderStart" hook.`
  350. };
  351. }
  352. function errorChunkInvalid({ fileName, code }, exception) {
  353. const errorProperties = {
  354. code: CHUNK_INVALID,
  355. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  356. };
  357. augmentCodeLocation(errorProperties, exception.loc, code, fileName);
  358. return errorProperties;
  359. }
  360. function errorCircularDependency(cyclePath) {
  361. return {
  362. code: CIRCULAR_DEPENDENCY,
  363. ids: cyclePath,
  364. message: `Circular dependency: ${cyclePath.map(relativeId).join(' -> ')}`
  365. };
  366. }
  367. function errorCircularReexport(exportName, exporter) {
  368. return {
  369. code: CIRCULAR_REEXPORT,
  370. exporter,
  371. message: `"${exportName}" cannot be exported from "${relativeId(exporter)}" as it is a reexport that references itself.`
  372. };
  373. }
  374. function errorCyclicCrossChunkReexport(exportName, exporter, reexporter, importer, preserveModules) {
  375. return {
  376. code: CYCLIC_CROSS_CHUNK_REEXPORT,
  377. exporter,
  378. id: importer,
  379. message: `Export "${exportName}" of module "${relativeId(exporter)}" was reexported through module "${relativeId(reexporter)}" while both modules are dependencies of each other and will end up in different chunks by current Rollup settings. This scenario is not well supported at the moment as it will produce a circular dependency between chunks and will likely lead to broken execution order.\nEither change the import in "${relativeId(importer)}" to point directly to the exporting module or ${preserveModules ? 'do not use "output.preserveModules"' : 'reconfigure "output.manualChunks"'} to ensure these modules end up in the same chunk.`,
  380. reexporter
  381. };
  382. }
  383. function errorDeprecation(deprecation, urlSnippet, plugin) {
  384. return {
  385. code: DEPRECATED_FEATURE,
  386. message: deprecation,
  387. url: getRollupUrl(urlSnippet),
  388. ...(plugin ? { plugin } : {})
  389. };
  390. }
  391. function errorDuplicateImportOptions() {
  392. return {
  393. code: DUPLICATE_IMPORT_OPTIONS,
  394. message: 'Either use --input, or pass input path as argument'
  395. };
  396. }
  397. function errorDuplicatePluginName(plugin) {
  398. return {
  399. code: DUPLICATE_PLUGIN_NAME,
  400. message: `The plugin name ${plugin} is being used twice in the same build. Plugin names must be distinct or provide a cacheKey (please post an issue to the plugin if you are a plugin user).`
  401. };
  402. }
  403. function errorEmptyChunk(chunkName) {
  404. return {
  405. code: EMPTY_BUNDLE,
  406. message: `Generated an empty chunk: "${chunkName}".`,
  407. names: [chunkName]
  408. };
  409. }
  410. function errorEval(id) {
  411. return {
  412. code: EVAL,
  413. id,
  414. message: `Use of eval in "${relativeId(id)}" is strongly discouraged as it poses security risks and may cause issues with minification.`,
  415. url: getRollupUrl(URL_AVOIDING_EVAL)
  416. };
  417. }
  418. function errorExternalSyntheticExports(id, importer) {
  419. return {
  420. code: EXTERNAL_SYNTHETIC_EXPORTS,
  421. exporter: id,
  422. message: `External "${id}" cannot have "syntheticNamedExports" enabled (imported by "${relativeId(importer)}").`
  423. };
  424. }
  425. function errorFailAfterWarnings() {
  426. return {
  427. code: FAIL_AFTER_WARNINGS,
  428. message: 'Warnings occurred and --failAfterWarnings flag present.'
  429. };
  430. }
  431. function errorFileNameConflict(fileName) {
  432. return {
  433. code: FILE_NAME_CONFLICT,
  434. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  435. };
  436. }
  437. function errorFileReferenceIdNotFoundForFilename(assetReferenceId) {
  438. return {
  439. code: FILE_NOT_FOUND,
  440. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  441. };
  442. }
  443. function errorIllegalIdentifierAsName(name) {
  444. return {
  445. code: ILLEGAL_IDENTIFIER_AS_NAME,
  446. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`,
  447. url: getRollupUrl(URL_OUTPUT_EXTEND)
  448. };
  449. }
  450. function errorIllegalImportReassignment(name, importingId) {
  451. return {
  452. code: ILLEGAL_REASSIGNMENT,
  453. message: `Illegal reassignment of import "${name}" in "${relativeId(importingId)}".`
  454. };
  455. }
  456. function errorInconsistentImportAssertions(existingAssertions, newAssertions, source, importer) {
  457. return {
  458. code: INCONSISTENT_IMPORT_ASSERTIONS,
  459. message: `Module "${relativeId(importer)}" tried to import "${relativeId(source)}" with ${formatAssertions$1(newAssertions)} assertions, but it was already imported elsewhere with ${formatAssertions$1(existingAssertions)} assertions. Please ensure that import assertions for the same module are always consistent.`
  460. };
  461. }
  462. const formatAssertions$1 = (assertions) => {
  463. const entries = Object.entries(assertions);
  464. if (entries.length === 0)
  465. return 'no';
  466. return entries.map(([key, value]) => `"${key}": "${value}"`).join(', ');
  467. };
  468. function errorInputHookInOutputPlugin(pluginName, hookName) {
  469. return {
  470. code: INPUT_HOOK_IN_OUTPUT_PLUGIN,
  471. message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
  472. };
  473. }
  474. function errorCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  475. return {
  476. code: INVALID_CHUNK,
  477. message: `Cannot assign "${relativeId(moduleId)}" to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  478. };
  479. }
  480. function errorCannotBundleConfigAsEsm(originalError) {
  481. return {
  482. cause: originalError,
  483. code: INVALID_CONFIG_MODULE_FORMAT,
  484. message: `Rollup transpiled your configuration to an ES module even though it appears to contain CommonJS elements. To resolve this, you can pass the "--bundleConfigAsCjs" flag to Rollup or change your configuration to only contain valid ESM code.\n\nOriginal error: ${originalError.message}`,
  485. stack: originalError.stack,
  486. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  487. };
  488. }
  489. function errorCannotLoadConfigAsCjs(originalError) {
  490. return {
  491. cause: originalError,
  492. code: INVALID_CONFIG_MODULE_FORMAT,
  493. message: `Node tried to load your configuration file as CommonJS even though it is likely an ES module. To resolve this, change the extension of your configuration to ".mjs", set "type": "module" in your package.json file or pass the "--bundleConfigAsCjs" flag.\n\nOriginal error: ${originalError.message}`,
  494. stack: originalError.stack,
  495. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  496. };
  497. }
  498. function errorCannotLoadConfigAsEsm(originalError) {
  499. return {
  500. cause: originalError,
  501. code: INVALID_CONFIG_MODULE_FORMAT,
  502. message: `Node tried to load your configuration as an ES module even though it is likely CommonJS. To resolve this, change the extension of your configuration to ".cjs" or pass the "--bundleConfigAsCjs" flag.\n\nOriginal error: ${originalError.message}`,
  503. stack: originalError.stack,
  504. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  505. };
  506. }
  507. function errorInvalidExportOptionValue(optionValue) {
  508. return {
  509. code: INVALID_EXPORT_OPTION,
  510. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}".`,
  511. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  512. };
  513. }
  514. function errorIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  515. return {
  516. code: INVALID_EXPORT_OPTION,
  517. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${printQuotedStringList(keys)}`,
  518. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  519. };
  520. }
  521. function errorInternalIdCannotBeExternal(source, importer) {
  522. return {
  523. code: INVALID_EXTERNAL_ID,
  524. message: `"${source}" is imported as an external by "${relativeId(importer)}", but is already an existing non-external module id.`
  525. };
  526. }
  527. function errorInvalidOption(option, urlSnippet, explanation, value) {
  528. return {
  529. code: INVALID_OPTION,
  530. message: `Invalid value ${value === undefined ? '' : `${JSON.stringify(value)} `}for option "${option}" - ${explanation}.`,
  531. url: getRollupUrl(urlSnippet)
  532. };
  533. }
  534. function errorInvalidAddonPluginHook(hook, plugin) {
  535. return {
  536. code: INVALID_PLUGIN_HOOK,
  537. hook,
  538. message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a string, a function hook or an object with a "handler" string or function.`,
  539. plugin
  540. };
  541. }
  542. function errorInvalidFunctionPluginHook(hook, plugin) {
  543. return {
  544. code: INVALID_PLUGIN_HOOK,
  545. hook,
  546. message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a function hook or an object with a "handler" function.`,
  547. plugin
  548. };
  549. }
  550. function errorInvalidRollupPhaseForAddWatchFile() {
  551. return {
  552. code: INVALID_ROLLUP_PHASE,
  553. message: `Cannot call "addWatchFile" after the build has finished.`
  554. };
  555. }
  556. function errorInvalidRollupPhaseForChunkEmission() {
  557. return {
  558. code: INVALID_ROLLUP_PHASE,
  559. message: `Cannot emit chunks after module loading has finished.`
  560. };
  561. }
  562. function errorInvalidSetAssetSourceCall() {
  563. return {
  564. code: INVALID_SETASSETSOURCE,
  565. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  566. };
  567. }
  568. function errorInvalidFormatForTopLevelAwait(id, format) {
  569. return {
  570. code: INVALID_TLA_FORMAT,
  571. id,
  572. message: `Module format "${format}" does not support top-level await. Use the "es" or "system" output formats rather.`
  573. };
  574. }
  575. function errorMissingConfig() {
  576. return {
  577. code: MISSING_CONFIG,
  578. message: 'Config file must export an options object, or an array of options objects',
  579. url: getRollupUrl(URL_CONFIGURATION_FILES)
  580. };
  581. }
  582. function errorMissingExport(binding, importingModule, exporter) {
  583. const isJson = node_path.extname(exporter) === '.json';
  584. return {
  585. binding,
  586. code: MISSING_EXPORT,
  587. exporter,
  588. id: importingModule,
  589. message: `"${binding}" is not exported by "${relativeId(exporter)}", imported by "${relativeId(importingModule)}".${isJson ? ' (Note that you need @rollup/plugin-json to import JSON files)' : ''}`,
  590. url: getRollupUrl(URL_NAME_IS_NOT_EXPORTED)
  591. };
  592. }
  593. function errorMissingExternalConfig(file) {
  594. return {
  595. code: MISSING_EXTERNAL_CONFIG,
  596. message: `Could not resolve config file "${file}"`
  597. };
  598. }
  599. function errorMissingGlobalName(externalId, guess) {
  600. return {
  601. code: MISSING_GLOBAL_NAME,
  602. id: externalId,
  603. message: `No name was provided for external module "${externalId}" in "output.globals" – guessing "${guess}".`,
  604. names: [guess],
  605. url: getRollupUrl(URL_OUTPUT_GLOBALS)
  606. };
  607. }
  608. function errorImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  609. return {
  610. code: MISSING_IMPLICIT_DEPENDANT,
  611. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  612. };
  613. }
  614. function errorUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  615. return {
  616. code: MISSING_IMPLICIT_DEPENDANT,
  617. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  618. };
  619. }
  620. function errorImplicitDependantIsNotIncluded(module) {
  621. const implicitDependencies = [...module.implicitlyLoadedBefore]
  622. .map(dependency => relativeId(dependency.id))
  623. .sort();
  624. return {
  625. code: MISSING_IMPLICIT_DEPENDANT,
  626. message: `Module "${relativeId(module.id)}" that should be implicitly loaded before ${printQuotedStringList(implicitDependencies)} is not included in the module graph. Either it was not imported by an included module or only via a tree-shaken dynamic import, or no imported bindings were used and it had otherwise no side-effects.`
  627. };
  628. }
  629. function errorMissingNameOptionForIifeExport() {
  630. return {
  631. code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
  632. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`,
  633. url: getRollupUrl(URL_OUTPUT_NAME)
  634. };
  635. }
  636. function errorMissingNameOptionForUmdExport() {
  637. return {
  638. code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
  639. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.',
  640. url: getRollupUrl(URL_OUTPUT_NAME)
  641. };
  642. }
  643. function errorMissingNodeBuiltins(externalBuiltins) {
  644. return {
  645. code: MISSING_NODE_BUILTINS,
  646. ids: externalBuiltins,
  647. message: `Creating a browser bundle that depends on Node.js built-in modules (${printQuotedStringList(externalBuiltins)}). You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node`
  648. };
  649. }
  650. // eslint-disable-next-line unicorn/prevent-abbreviations
  651. function errorMissingFileOrDirOption() {
  652. return {
  653. code: MISSING_OPTION,
  654. message: 'You must specify "output.file" or "output.dir" for the build.',
  655. url: getRollupUrl(URL_OUTPUT_DIR)
  656. };
  657. }
  658. function errorMixedExport(facadeModuleId, name) {
  659. return {
  660. code: MIXED_EXPORTS,
  661. id: facadeModuleId,
  662. message: `Entry module "${relativeId(facadeModuleId)}" is using named and default exports together. Consumers of your bundle will have to use \`${name || 'chunk'}.default\` to access the default export, which may not be what you want. Use \`output.exports: "named"\` to disable this warning.`,
  663. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  664. };
  665. }
  666. function errorModuleLevelDirective(directive, id) {
  667. return {
  668. code: MODULE_LEVEL_DIRECTIVE,
  669. id,
  670. message: `Module level directives cause errors when bundled, "${directive}" in "${relativeId(id)}" was ignored.`
  671. };
  672. }
  673. function errorNamespaceConflict(binding, reexportingModuleId, sources) {
  674. return {
  675. binding,
  676. code: NAMESPACE_CONFLICT,
  677. ids: sources,
  678. message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${binding}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored).`,
  679. reexporter: reexportingModuleId
  680. };
  681. }
  682. function errorNoTransformMapOrAstWithoutCode(pluginName) {
  683. return {
  684. code: NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  685. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  686. 'a "code". This will be ignored.'
  687. };
  688. }
  689. function errorOnlyInlineSourcemapsForStdout() {
  690. return {
  691. code: ONLY_INLINE_SOURCEMAPS,
  692. message: 'Only inline sourcemaps are supported when bundling to stdout.'
  693. };
  694. }
  695. function errorParseError(error, moduleId) {
  696. let message = error.message.replace(/ \(\d+:\d+\)$/, '');
  697. if (moduleId.endsWith('.json')) {
  698. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  699. }
  700. else if (!moduleId.endsWith('.js')) {
  701. message += ' (Note that you need plugins to import files that are not JavaScript)';
  702. }
  703. return {
  704. cause: error,
  705. code: PARSE_ERROR,
  706. id: moduleId,
  707. message
  708. };
  709. }
  710. function errorPluginError(error, plugin, { hook, id } = {}) {
  711. if (typeof error === 'string')
  712. error = { message: error };
  713. if (error.code && error.code !== PLUGIN_ERROR) {
  714. error.pluginCode = error.code;
  715. }
  716. error.code = PLUGIN_ERROR;
  717. error.plugin = plugin;
  718. if (hook) {
  719. error.hook = hook;
  720. }
  721. if (id) {
  722. error.id = id;
  723. }
  724. return error;
  725. }
  726. function errorShimmedExport(id, binding) {
  727. return {
  728. binding,
  729. code: SHIMMED_EXPORT,
  730. exporter: id,
  731. message: `Missing export "${binding}" has been shimmed in module "${relativeId(id)}".`
  732. };
  733. }
  734. function errorSourcemapBroken(plugin) {
  735. return {
  736. code: SOURCEMAP_BROKEN,
  737. message: `Sourcemap is likely to be incorrect: a plugin (${plugin}) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help`,
  738. plugin,
  739. url: getRollupUrl(URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT)
  740. };
  741. }
  742. function errorConflictingSourcemapSources(filename) {
  743. return {
  744. code: SOURCEMAP_BROKEN,
  745. message: `Multiple conflicting contents for sourcemap source ${filename}`
  746. };
  747. }
  748. function errorInvalidSourcemapForError(error, id, column, line, pos) {
  749. return {
  750. cause: error,
  751. code: SOURCEMAP_ERROR,
  752. id,
  753. loc: {
  754. column,
  755. file: id,
  756. line
  757. },
  758. message: `Error when using sourcemap for reporting an error: ${error.message}`,
  759. pos
  760. };
  761. }
  762. function errorSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  763. return {
  764. code: SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  765. exporter: id,
  766. message: `Module "${relativeId(id)}" that is marked with \`syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}\` needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  767. ? `an explicit export named "${syntheticNamedExportsOption}"`
  768. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  769. };
  770. }
  771. function errorThisIsUndefined() {
  772. return {
  773. code: THIS_IS_UNDEFINED,
  774. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  775. url: getRollupUrl(URL_THIS_IS_UNDEFINED)
  776. };
  777. }
  778. function errorUnexpectedNamedImport(id, imported, isReexport) {
  779. const importType = isReexport ? 'reexport' : 'import';
  780. return {
  781. code: UNEXPECTED_NAMED_IMPORT,
  782. exporter: id,
  783. message: `The named export "${imported}" was ${importType}ed from the external module "${relativeId(id)}" even though its interop type is "defaultOnly". Either remove or change this ${importType} or change the value of the "output.interop" option.`,
  784. url: getRollupUrl(URL_OUTPUT_INTEROP)
  785. };
  786. }
  787. function errorUnexpectedNamespaceReexport(id) {
  788. return {
  789. code: UNEXPECTED_NAMED_IMPORT,
  790. exporter: id,
  791. message: `There was a namespace "*" reexport from the external module "${relativeId(id)}" even though its interop type is "defaultOnly". This will be ignored as namespace reexports only reexport named exports. If this is not intended, either remove or change this reexport or change the value of the "output.interop" option.`,
  792. url: getRollupUrl(URL_OUTPUT_INTEROP)
  793. };
  794. }
  795. function errorUnknownOption(optionType, unknownOptions, validOptions) {
  796. return {
  797. code: UNKNOWN_OPTION,
  798. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.join(', ')}`
  799. };
  800. }
  801. function errorEntryCannotBeExternal(unresolvedId) {
  802. return {
  803. code: UNRESOLVED_ENTRY,
  804. message: `Entry module "${relativeId(unresolvedId)}" cannot be external.`
  805. };
  806. }
  807. function errorUnresolvedEntry(unresolvedId) {
  808. return {
  809. code: UNRESOLVED_ENTRY,
  810. message: `Could not resolve entry module "${relativeId(unresolvedId)}".`
  811. };
  812. }
  813. function errorUnresolvedImport(source, importer) {
  814. return {
  815. code: UNRESOLVED_IMPORT,
  816. exporter: source,
  817. id: importer,
  818. message: `Could not resolve "${source}" from "${relativeId(importer)}"`
  819. };
  820. }
  821. function errorUnresolvedImportTreatedAsExternal(source, importer) {
  822. return {
  823. code: UNRESOLVED_IMPORT,
  824. exporter: source,
  825. id: importer,
  826. message: `"${source}" is imported by "${relativeId(importer)}", but could not be resolved – treating it as an external dependency.`,
  827. url: getRollupUrl(URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY)
  828. };
  829. }
  830. function errorUnusedExternalImports(externalId, names, importers) {
  831. return {
  832. code: UNUSED_EXTERNAL_IMPORT,
  833. exporter: externalId,
  834. ids: importers,
  835. message: `${printQuotedStringList(names, [
  836. 'is',
  837. 'are'
  838. ])} imported from external module "${externalId}" but never used in ${printQuotedStringList(importers.map(importer => relativeId(importer)))}.`,
  839. names
  840. };
  841. }
  842. function errorFailedValidation(message) {
  843. return {
  844. code: VALIDATION_ERROR,
  845. message
  846. };
  847. }
  848. function warnDeprecation(deprecation, urlSnippet, activeDeprecation, options, plugin) {
  849. warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, options.onwarn, options.strictDeprecations, plugin);
  850. }
  851. function warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, warn, strictDeprecations, plugin) {
  852. if (activeDeprecation || strictDeprecations) {
  853. const warning = errorDeprecation(deprecation, urlSnippet, plugin);
  854. if (strictDeprecations) {
  855. return error(warning);
  856. }
  857. warn(warning);
  858. }
  859. }
  860. const defaultOnWarn = warning => console.warn(warning.message || warning);
  861. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  862. const validOptionSet = new Set(validOptions);
  863. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  864. if (unknownOptions.length > 0) {
  865. warn(errorUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  866. }
  867. }
  868. const treeshakePresets = {
  869. recommended: {
  870. annotations: true,
  871. correctVarValueBeforeDeclaration: false,
  872. manualPureFunctions: EMPTY_ARRAY,
  873. moduleSideEffects: () => true,
  874. propertyReadSideEffects: true,
  875. tryCatchDeoptimization: true,
  876. unknownGlobalSideEffects: false
  877. },
  878. safest: {
  879. annotations: true,
  880. correctVarValueBeforeDeclaration: true,
  881. manualPureFunctions: EMPTY_ARRAY,
  882. moduleSideEffects: () => true,
  883. propertyReadSideEffects: true,
  884. tryCatchDeoptimization: true,
  885. unknownGlobalSideEffects: true
  886. },
  887. smallest: {
  888. annotations: true,
  889. correctVarValueBeforeDeclaration: false,
  890. manualPureFunctions: EMPTY_ARRAY,
  891. moduleSideEffects: () => false,
  892. propertyReadSideEffects: false,
  893. tryCatchDeoptimization: false,
  894. unknownGlobalSideEffects: false
  895. }
  896. };
  897. const generatedCodePresets = {
  898. es2015: {
  899. arrowFunctions: true,
  900. constBindings: true,
  901. objectShorthand: true,
  902. reservedNamesAsProps: true,
  903. symbols: true
  904. },
  905. es5: {
  906. arrowFunctions: false,
  907. constBindings: false,
  908. objectShorthand: false,
  909. reservedNamesAsProps: true,
  910. symbols: false
  911. }
  912. };
  913. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  914. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  915. if (typeof value === 'string') {
  916. const preset = presets[value];
  917. if (preset) {
  918. return preset;
  919. }
  920. error(errorInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  921. }
  922. return objectifyOption(value);
  923. };
  924. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  925. const presetName = value?.preset;
  926. if (presetName) {
  927. const preset = presets[presetName];
  928. if (preset) {
  929. return { ...preset, ...value };
  930. }
  931. else {
  932. error(errorInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  933. }
  934. }
  935. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  936. };
  937. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  938. const commandAliases = {
  939. c: 'config',
  940. d: 'dir',
  941. e: 'external',
  942. f: 'format',
  943. g: 'globals',
  944. h: 'help',
  945. i: 'input',
  946. m: 'sourcemap',
  947. n: 'name',
  948. o: 'file',
  949. p: 'plugin',
  950. v: 'version',
  951. w: 'watch'
  952. };
  953. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  954. async function mergeOptions(config, rawCommandOptions = EMPTY_COMMAND_OPTIONS, defaultOnWarnHandler = defaultOnWarn) {
  955. const command = getCommandOptions(rawCommandOptions);
  956. const inputOptions = await mergeInputOptions(config, command, defaultOnWarnHandler);
  957. const warn = inputOptions.onwarn;
  958. if (command.output) {
  959. Object.assign(command, command.output);
  960. }
  961. const outputOptionsArray = ensureArray$1(config.output);
  962. if (outputOptionsArray.length === 0)
  963. outputOptionsArray.push({});
  964. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, warn)));
  965. warnUnknownOptions(command, [
  966. ...Object.keys(inputOptions),
  967. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  968. ...Object.keys(commandAliases),
  969. 'bundleConfigAsCjs',
  970. 'config',
  971. 'environment',
  972. 'plugin',
  973. 'silent',
  974. 'failAfterWarnings',
  975. 'stdin',
  976. 'waitForBundleInput',
  977. 'configPlugin'
  978. ], 'CLI flags', warn, /^_$|output$|config/);
  979. inputOptions.output = outputOptions;
  980. return inputOptions;
  981. }
  982. function getCommandOptions(rawCommandOptions) {
  983. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  984. ? rawCommandOptions.external.split(',')
  985. : [];
  986. return {
  987. ...rawCommandOptions,
  988. external,
  989. globals: typeof rawCommandOptions.globals === 'string'
  990. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  991. const [id, variableName] = globalDefinition.split(':');
  992. globals[id] = variableName;
  993. if (!external.includes(id)) {
  994. external.push(id);
  995. }
  996. return globals;
  997. }, Object.create(null))
  998. : undefined
  999. };
  1000. }
  1001. async function mergeInputOptions(config, overrides, defaultOnWarnHandler) {
  1002. const getOption = (name) => overrides[name] ?? config[name];
  1003. const inputOptions = {
  1004. acorn: getOption('acorn'),
  1005. acornInjectPlugins: config.acornInjectPlugins,
  1006. cache: config.cache,
  1007. context: getOption('context'),
  1008. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  1009. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  1010. external: getExternal(config, overrides),
  1011. inlineDynamicImports: getOption('inlineDynamicImports'),
  1012. input: getOption('input') || [],
  1013. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  1014. manualChunks: getOption('manualChunks'),
  1015. maxParallelFileOps: getOption('maxParallelFileOps'),
  1016. maxParallelFileReads: getOption('maxParallelFileReads'),
  1017. moduleContext: getOption('moduleContext'),
  1018. onwarn: getOnWarn(config, defaultOnWarnHandler),
  1019. perf: getOption('perf'),
  1020. plugins: await normalizePluginOption(config.plugins),
  1021. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  1022. preserveModules: getOption('preserveModules'),
  1023. preserveSymlinks: getOption('preserveSymlinks'),
  1024. shimMissingExports: getOption('shimMissingExports'),
  1025. strictDeprecations: getOption('strictDeprecations'),
  1026. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ')),
  1027. watch: getWatch(config, overrides)
  1028. };
  1029. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', inputOptions.onwarn, /^output$/);
  1030. return inputOptions;
  1031. }
  1032. const getExternal = (config, overrides) => {
  1033. const configExternal = config.external;
  1034. return typeof configExternal === 'function'
  1035. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  1036. : [...ensureArray$1(configExternal), ...overrides.external];
  1037. };
  1038. const getOnWarn = (config, defaultOnWarnHandler) => config.onwarn ? warning => config.onwarn(warning, defaultOnWarnHandler) : defaultOnWarnHandler;
  1039. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  1040. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  1041. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  1042. if (commandOption !== undefined) {
  1043. return commandOption && { ...configOption, ...commandOption };
  1044. }
  1045. return configOption;
  1046. };
  1047. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  1048. const isWatchEnabled = (optionValue) => {
  1049. if (Array.isArray(optionValue)) {
  1050. return optionValue.reduce((result, value) => (typeof value === 'boolean' ? value : result), false);
  1051. }
  1052. return optionValue === true;
  1053. };
  1054. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  1055. if (!optionValue) {
  1056. return optionValue;
  1057. }
  1058. if (Array.isArray(optionValue)) {
  1059. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  1060. }
  1061. return objectifyValue(optionValue);
  1062. };
  1063. async function mergeOutputOptions(config, overrides, warn) {
  1064. const getOption = (name) => overrides[name] ?? config[name];
  1065. const outputOptions = {
  1066. amd: getObjectOption(config, overrides, 'amd'),
  1067. assetFileNames: getOption('assetFileNames'),
  1068. banner: getOption('banner'),
  1069. chunkFileNames: getOption('chunkFileNames'),
  1070. compact: getOption('compact'),
  1071. dir: getOption('dir'),
  1072. dynamicImportFunction: getOption('dynamicImportFunction'),
  1073. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  1074. entryFileNames: getOption('entryFileNames'),
  1075. esModule: getOption('esModule'),
  1076. experimentalDeepDynamicChunkOptimization: getOption('experimentalDeepDynamicChunkOptimization'),
  1077. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  1078. exports: getOption('exports'),
  1079. extend: getOption('extend'),
  1080. externalImportAssertions: getOption('externalImportAssertions'),
  1081. externalLiveBindings: getOption('externalLiveBindings'),
  1082. file: getOption('file'),
  1083. footer: getOption('footer'),
  1084. format: getOption('format'),
  1085. freeze: getOption('freeze'),
  1086. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '')),
  1087. globals: getOption('globals'),
  1088. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  1089. indent: getOption('indent'),
  1090. inlineDynamicImports: getOption('inlineDynamicImports'),
  1091. interop: getOption('interop'),
  1092. intro: getOption('intro'),
  1093. manualChunks: getOption('manualChunks'),
  1094. minifyInternalExports: getOption('minifyInternalExports'),
  1095. name: getOption('name'),
  1096. namespaceToStringTag: getOption('namespaceToStringTag'),
  1097. noConflict: getOption('noConflict'),
  1098. outro: getOption('outro'),
  1099. paths: getOption('paths'),
  1100. plugins: await normalizePluginOption(config.plugins),
  1101. preferConst: getOption('preferConst'),
  1102. preserveModules: getOption('preserveModules'),
  1103. preserveModulesRoot: getOption('preserveModulesRoot'),
  1104. sanitizeFileName: getOption('sanitizeFileName'),
  1105. sourcemap: getOption('sourcemap'),
  1106. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  1107. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  1108. sourcemapFile: getOption('sourcemapFile'),
  1109. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  1110. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  1111. strict: getOption('strict'),
  1112. systemNullSetters: getOption('systemNullSetters'),
  1113. validate: getOption('validate')
  1114. };
  1115. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', warn);
  1116. return outputOptions;
  1117. }
  1118. const {
  1119. env = {},
  1120. argv = [],
  1121. platform = "",
  1122. } = typeof process === "undefined" ? {} : process;
  1123. const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
  1124. const isForced = "FORCE_COLOR" in env || argv.includes("--color");
  1125. const isWindows = platform === "win32";
  1126. const isDumbTerminal = env.TERM === "dumb";
  1127. const isCompatibleTerminal =
  1128. tty__namespace && tty__namespace.isatty && tty__namespace.isatty(1) && env.TERM && !isDumbTerminal;
  1129. const isCI =
  1130. "CI" in env &&
  1131. ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
  1132. const isColorSupported =
  1133. !isDisabled &&
  1134. (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);
  1135. const replaceClose = (
  1136. index,
  1137. string,
  1138. close,
  1139. replace,
  1140. head = string.substring(0, index) + replace,
  1141. tail = string.substring(index + close.length),
  1142. next = tail.indexOf(close)
  1143. ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
  1144. const clearBleed = (index, string, open, close, replace) =>
  1145. index < 0
  1146. ? open + string + close
  1147. : open + replaceClose(index, string, close, replace) + close;
  1148. const filterEmpty =
  1149. (open, close, replace = open, at = open.length + 1) =>
  1150. (string) =>
  1151. string || !(string === "" || string === undefined)
  1152. ? clearBleed(
  1153. ("" + string).indexOf(close, at),
  1154. string,
  1155. open,
  1156. close,
  1157. replace
  1158. )
  1159. : "";
  1160. const init = (open, close, replace) =>
  1161. filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
  1162. const colors = {
  1163. reset: init(0, 0),
  1164. bold: init(1, 22, "\x1b[22m\x1b[1m"),
  1165. dim: init(2, 22, "\x1b[22m\x1b[2m"),
  1166. italic: init(3, 23),
  1167. underline: init(4, 24),
  1168. inverse: init(7, 27),
  1169. hidden: init(8, 28),
  1170. strikethrough: init(9, 29),
  1171. black: init(30, 39),
  1172. red: init(31, 39),
  1173. green: init(32, 39),
  1174. yellow: init(33, 39),
  1175. blue: init(34, 39),
  1176. magenta: init(35, 39),
  1177. cyan: init(36, 39),
  1178. white: init(37, 39),
  1179. gray: init(90, 39),
  1180. bgBlack: init(40, 49),
  1181. bgRed: init(41, 49),
  1182. bgGreen: init(42, 49),
  1183. bgYellow: init(43, 49),
  1184. bgBlue: init(44, 49),
  1185. bgMagenta: init(45, 49),
  1186. bgCyan: init(46, 49),
  1187. bgWhite: init(47, 49),
  1188. blackBright: init(90, 39),
  1189. redBright: init(91, 39),
  1190. greenBright: init(92, 39),
  1191. yellowBright: init(93, 39),
  1192. blueBright: init(94, 39),
  1193. magentaBright: init(95, 39),
  1194. cyanBright: init(96, 39),
  1195. whiteBright: init(97, 39),
  1196. bgBlackBright: init(100, 49),
  1197. bgRedBright: init(101, 49),
  1198. bgGreenBright: init(102, 49),
  1199. bgYellowBright: init(103, 49),
  1200. bgBlueBright: init(104, 49),
  1201. bgMagentaBright: init(105, 49),
  1202. bgCyanBright: init(106, 49),
  1203. bgWhiteBright: init(107, 49),
  1204. };
  1205. const createColors = ({ useColor = isColorSupported } = {}) =>
  1206. useColor
  1207. ? colors
  1208. : Object.keys(colors).reduce(
  1209. (colors, key) => ({ ...colors, [key]: String }),
  1210. {}
  1211. );
  1212. createColors();
  1213. // @see https://no-color.org
  1214. // @see https://www.npmjs.com/package/chalk
  1215. const { bold, cyan, dim, gray, green, red, underline, yellow } = createColors({
  1216. useColor: process$1.env.FORCE_COLOR !== '0' && !process$1.env.NO_COLOR
  1217. });
  1218. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  1219. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  1220. function handleError(error, recover = false) {
  1221. const name = error.name || error.cause?.name;
  1222. const nameSection = name ? `${name}: ` : '';
  1223. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  1224. const message = `${pluginSection}${nameSection}${error.message}`;
  1225. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  1226. if (error.url) {
  1227. outputLines.push(cyan(error.url));
  1228. }
  1229. if (error.loc) {
  1230. outputLines.push(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  1231. }
  1232. else if (error.id) {
  1233. outputLines.push(relativeId(error.id));
  1234. }
  1235. if (error.frame) {
  1236. outputLines.push(dim(error.frame));
  1237. }
  1238. if (error.stack) {
  1239. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  1240. }
  1241. outputLines.push('', '');
  1242. stderr(outputLines.join('\n'));
  1243. // eslint-disable-next-line unicorn/no-process-exit
  1244. if (!recover)
  1245. process$1.exit(1);
  1246. }
  1247. const comma = ','.charCodeAt(0);
  1248. const semicolon = ';'.charCodeAt(0);
  1249. const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  1250. const intToChar = new Uint8Array(64); // 64 possible chars.
  1251. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  1252. for (let i = 0; i < chars$1.length; i++) {
  1253. const c = chars$1.charCodeAt(i);
  1254. intToChar[i] = c;
  1255. charToInt[c] = i;
  1256. }
  1257. // Provide a fallback for older environments.
  1258. const td = typeof TextDecoder !== 'undefined'
  1259. ? /* #__PURE__ */ new TextDecoder()
  1260. : typeof Buffer !== 'undefined'
  1261. ? {
  1262. decode(buf) {
  1263. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  1264. return out.toString();
  1265. },
  1266. }
  1267. : {
  1268. decode(buf) {
  1269. let out = '';
  1270. for (let i = 0; i < buf.length; i++) {
  1271. out += String.fromCharCode(buf[i]);
  1272. }
  1273. return out;
  1274. },
  1275. };
  1276. function decode(mappings) {
  1277. const state = new Int32Array(5);
  1278. const decoded = [];
  1279. let index = 0;
  1280. do {
  1281. const semi = indexOf(mappings, index);
  1282. const line = [];
  1283. let sorted = true;
  1284. let lastCol = 0;
  1285. state[0] = 0;
  1286. for (let i = index; i < semi; i++) {
  1287. let seg;
  1288. i = decodeInteger(mappings, i, state, 0); // genColumn
  1289. const col = state[0];
  1290. if (col < lastCol)
  1291. sorted = false;
  1292. lastCol = col;
  1293. if (hasMoreVlq(mappings, i, semi)) {
  1294. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  1295. i = decodeInteger(mappings, i, state, 2); // sourceLine
  1296. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  1297. if (hasMoreVlq(mappings, i, semi)) {
  1298. i = decodeInteger(mappings, i, state, 4); // namesIndex
  1299. seg = [col, state[1], state[2], state[3], state[4]];
  1300. }
  1301. else {
  1302. seg = [col, state[1], state[2], state[3]];
  1303. }
  1304. }
  1305. else {
  1306. seg = [col];
  1307. }
  1308. line.push(seg);
  1309. }
  1310. if (!sorted)
  1311. sort(line);
  1312. decoded.push(line);
  1313. index = semi + 1;
  1314. } while (index <= mappings.length);
  1315. return decoded;
  1316. }
  1317. function indexOf(mappings, index) {
  1318. const idx = mappings.indexOf(';', index);
  1319. return idx === -1 ? mappings.length : idx;
  1320. }
  1321. function decodeInteger(mappings, pos, state, j) {
  1322. let value = 0;
  1323. let shift = 0;
  1324. let integer = 0;
  1325. do {
  1326. const c = mappings.charCodeAt(pos++);
  1327. integer = charToInt[c];
  1328. value |= (integer & 31) << shift;
  1329. shift += 5;
  1330. } while (integer & 32);
  1331. const shouldNegate = value & 1;
  1332. value >>>= 1;
  1333. if (shouldNegate) {
  1334. value = -0x80000000 | -value;
  1335. }
  1336. state[j] += value;
  1337. return pos;
  1338. }
  1339. function hasMoreVlq(mappings, i, length) {
  1340. if (i >= length)
  1341. return false;
  1342. return mappings.charCodeAt(i) !== comma;
  1343. }
  1344. function sort(line) {
  1345. line.sort(sortComparator);
  1346. }
  1347. function sortComparator(a, b) {
  1348. return a[0] - b[0];
  1349. }
  1350. function encode(decoded) {
  1351. const state = new Int32Array(5);
  1352. const bufLength = 1024 * 16;
  1353. const subLength = bufLength - 36;
  1354. const buf = new Uint8Array(bufLength);
  1355. const sub = buf.subarray(0, subLength);
  1356. let pos = 0;
  1357. let out = '';
  1358. for (let i = 0; i < decoded.length; i++) {
  1359. const line = decoded[i];
  1360. if (i > 0) {
  1361. if (pos === bufLength) {
  1362. out += td.decode(buf);
  1363. pos = 0;
  1364. }
  1365. buf[pos++] = semicolon;
  1366. }
  1367. if (line.length === 0)
  1368. continue;
  1369. state[0] = 0;
  1370. for (let j = 0; j < line.length; j++) {
  1371. const segment = line[j];
  1372. // We can push up to 5 ints, each int can take at most 7 chars, and we
  1373. // may push a comma.
  1374. if (pos > subLength) {
  1375. out += td.decode(sub);
  1376. buf.copyWithin(0, subLength, pos);
  1377. pos -= subLength;
  1378. }
  1379. if (j > 0)
  1380. buf[pos++] = comma;
  1381. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  1382. if (segment.length === 1)
  1383. continue;
  1384. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  1385. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  1386. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  1387. if (segment.length === 4)
  1388. continue;
  1389. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  1390. }
  1391. }
  1392. return out + td.decode(buf.subarray(0, pos));
  1393. }
  1394. function encodeInteger(buf, pos, state, segment, j) {
  1395. const next = segment[j];
  1396. let num = next - state[j];
  1397. state[j] = next;
  1398. num = num < 0 ? (-num << 1) | 1 : num << 1;
  1399. do {
  1400. let clamped = num & 0b011111;
  1401. num >>>= 5;
  1402. if (num > 0)
  1403. clamped |= 0b100000;
  1404. buf[pos++] = intToChar[clamped];
  1405. } while (num > 0);
  1406. return pos;
  1407. }
  1408. class BitSet {
  1409. constructor(arg) {
  1410. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  1411. }
  1412. add(n) {
  1413. this.bits[n >> 5] |= 1 << (n & 31);
  1414. }
  1415. has(n) {
  1416. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  1417. }
  1418. }
  1419. let Chunk$1 = class Chunk {
  1420. constructor(start, end, content) {
  1421. this.start = start;
  1422. this.end = end;
  1423. this.original = content;
  1424. this.intro = '';
  1425. this.outro = '';
  1426. this.content = content;
  1427. this.storeName = false;
  1428. this.edited = false;
  1429. {
  1430. this.previous = null;
  1431. this.next = null;
  1432. }
  1433. }
  1434. appendLeft(content) {
  1435. this.outro += content;
  1436. }
  1437. appendRight(content) {
  1438. this.intro = this.intro + content;
  1439. }
  1440. clone() {
  1441. const chunk = new Chunk(this.start, this.end, this.original);
  1442. chunk.intro = this.intro;
  1443. chunk.outro = this.outro;
  1444. chunk.content = this.content;
  1445. chunk.storeName = this.storeName;
  1446. chunk.edited = this.edited;
  1447. return chunk;
  1448. }
  1449. contains(index) {
  1450. return this.start < index && index < this.end;
  1451. }
  1452. eachNext(fn) {
  1453. let chunk = this;
  1454. while (chunk) {
  1455. fn(chunk);
  1456. chunk = chunk.next;
  1457. }
  1458. }
  1459. eachPrevious(fn) {
  1460. let chunk = this;
  1461. while (chunk) {
  1462. fn(chunk);
  1463. chunk = chunk.previous;
  1464. }
  1465. }
  1466. edit(content, storeName, contentOnly) {
  1467. this.content = content;
  1468. if (!contentOnly) {
  1469. this.intro = '';
  1470. this.outro = '';
  1471. }
  1472. this.storeName = storeName;
  1473. this.edited = true;
  1474. return this;
  1475. }
  1476. prependLeft(content) {
  1477. this.outro = content + this.outro;
  1478. }
  1479. prependRight(content) {
  1480. this.intro = content + this.intro;
  1481. }
  1482. split(index) {
  1483. const sliceIndex = index - this.start;
  1484. const originalBefore = this.original.slice(0, sliceIndex);
  1485. const originalAfter = this.original.slice(sliceIndex);
  1486. this.original = originalBefore;
  1487. const newChunk = new Chunk(index, this.end, originalAfter);
  1488. newChunk.outro = this.outro;
  1489. this.outro = '';
  1490. this.end = index;
  1491. if (this.edited) {
  1492. // TODO is this block necessary?...
  1493. newChunk.edit('', false);
  1494. this.content = '';
  1495. } else {
  1496. this.content = originalBefore;
  1497. }
  1498. newChunk.next = this.next;
  1499. if (newChunk.next) newChunk.next.previous = newChunk;
  1500. newChunk.previous = this;
  1501. this.next = newChunk;
  1502. return newChunk;
  1503. }
  1504. toString() {
  1505. return this.intro + this.content + this.outro;
  1506. }
  1507. trimEnd(rx) {
  1508. this.outro = this.outro.replace(rx, '');
  1509. if (this.outro.length) return true;
  1510. const trimmed = this.content.replace(rx, '');
  1511. if (trimmed.length) {
  1512. if (trimmed !== this.content) {
  1513. this.split(this.start + trimmed.length).edit('', undefined, true);
  1514. }
  1515. return true;
  1516. } else {
  1517. this.edit('', undefined, true);
  1518. this.intro = this.intro.replace(rx, '');
  1519. if (this.intro.length) return true;
  1520. }
  1521. }
  1522. trimStart(rx) {
  1523. this.intro = this.intro.replace(rx, '');
  1524. if (this.intro.length) return true;
  1525. const trimmed = this.content.replace(rx, '');
  1526. if (trimmed.length) {
  1527. if (trimmed !== this.content) {
  1528. this.split(this.end - trimmed.length);
  1529. this.edit('', undefined, true);
  1530. }
  1531. return true;
  1532. } else {
  1533. this.edit('', undefined, true);
  1534. this.outro = this.outro.replace(rx, '');
  1535. if (this.outro.length) return true;
  1536. }
  1537. }
  1538. };
  1539. function getBtoa () {
  1540. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  1541. return (str) => window.btoa(unescape(encodeURIComponent(str)));
  1542. } else if (typeof Buffer === 'function') {
  1543. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  1544. } else {
  1545. return () => {
  1546. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  1547. };
  1548. }
  1549. }
  1550. const btoa = /*#__PURE__*/ getBtoa();
  1551. class SourceMap {
  1552. constructor(properties) {
  1553. this.version = 3;
  1554. this.file = properties.file;
  1555. this.sources = properties.sources;
  1556. this.sourcesContent = properties.sourcesContent;
  1557. this.names = properties.names;
  1558. this.mappings = encode(properties.mappings);
  1559. if (typeof properties.x_google_ignoreList !== 'undefined') {
  1560. this.x_google_ignoreList = properties.x_google_ignoreList;
  1561. }
  1562. }
  1563. toString() {
  1564. return JSON.stringify(this);
  1565. }
  1566. toUrl() {
  1567. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  1568. }
  1569. }
  1570. function guessIndent(code) {
  1571. const lines = code.split('\n');
  1572. const tabbed = lines.filter((line) => /^\t+/.test(line));
  1573. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  1574. if (tabbed.length === 0 && spaced.length === 0) {
  1575. return null;
  1576. }
  1577. // More lines tabbed than spaced? Assume tabs, and
  1578. // default to tabs in the case of a tie (or nothing
  1579. // to go on)
  1580. if (tabbed.length >= spaced.length) {
  1581. return '\t';
  1582. }
  1583. // Otherwise, we need to guess the multiple
  1584. const min = spaced.reduce((previous, current) => {
  1585. const numSpaces = /^ +/.exec(current)[0].length;
  1586. return Math.min(numSpaces, previous);
  1587. }, Infinity);
  1588. return new Array(min + 1).join(' ');
  1589. }
  1590. function getRelativePath(from, to) {
  1591. const fromParts = from.split(/[/\\]/);
  1592. const toParts = to.split(/[/\\]/);
  1593. fromParts.pop(); // get dirname
  1594. while (fromParts[0] === toParts[0]) {
  1595. fromParts.shift();
  1596. toParts.shift();
  1597. }
  1598. if (fromParts.length) {
  1599. let i = fromParts.length;
  1600. while (i--) fromParts[i] = '..';
  1601. }
  1602. return fromParts.concat(toParts).join('/');
  1603. }
  1604. const toString$1 = Object.prototype.toString;
  1605. function isObject$1(thing) {
  1606. return toString$1.call(thing) === '[object Object]';
  1607. }
  1608. function getLocator(source) {
  1609. const originalLines = source.split('\n');
  1610. const lineOffsets = [];
  1611. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  1612. lineOffsets.push(pos);
  1613. pos += originalLines[i].length + 1;
  1614. }
  1615. return function locate(index) {
  1616. let i = 0;
  1617. let j = lineOffsets.length;
  1618. while (i < j) {
  1619. const m = (i + j) >> 1;
  1620. if (index < lineOffsets[m]) {
  1621. j = m;
  1622. } else {
  1623. i = m + 1;
  1624. }
  1625. }
  1626. const line = i - 1;
  1627. const column = index - lineOffsets[line];
  1628. return { line, column };
  1629. };
  1630. }
  1631. class Mappings {
  1632. constructor(hires) {
  1633. this.hires = hires;
  1634. this.generatedCodeLine = 0;
  1635. this.generatedCodeColumn = 0;
  1636. this.raw = [];
  1637. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  1638. this.pending = null;
  1639. }
  1640. addEdit(sourceIndex, content, loc, nameIndex) {
  1641. if (content.length) {
  1642. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  1643. if (nameIndex >= 0) {
  1644. segment.push(nameIndex);
  1645. }
  1646. this.rawSegments.push(segment);
  1647. } else if (this.pending) {
  1648. this.rawSegments.push(this.pending);
  1649. }
  1650. this.advance(content);
  1651. this.pending = null;
  1652. }
  1653. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  1654. let originalCharIndex = chunk.start;
  1655. let first = true;
  1656. while (originalCharIndex < chunk.end) {
  1657. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  1658. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  1659. }
  1660. if (original[originalCharIndex] === '\n') {
  1661. loc.line += 1;
  1662. loc.column = 0;
  1663. this.generatedCodeLine += 1;
  1664. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1665. this.generatedCodeColumn = 0;
  1666. first = true;
  1667. } else {
  1668. loc.column += 1;
  1669. this.generatedCodeColumn += 1;
  1670. first = false;
  1671. }
  1672. originalCharIndex += 1;
  1673. }
  1674. this.pending = null;
  1675. }
  1676. advance(str) {
  1677. if (!str) return;
  1678. const lines = str.split('\n');
  1679. if (lines.length > 1) {
  1680. for (let i = 0; i < lines.length - 1; i++) {
  1681. this.generatedCodeLine++;
  1682. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1683. }
  1684. this.generatedCodeColumn = 0;
  1685. }
  1686. this.generatedCodeColumn += lines[lines.length - 1].length;
  1687. }
  1688. }
  1689. const n = '\n';
  1690. const warned = {
  1691. insertLeft: false,
  1692. insertRight: false,
  1693. storeName: false,
  1694. };
  1695. class MagicString {
  1696. constructor(string, options = {}) {
  1697. const chunk = new Chunk$1(0, string.length, string);
  1698. Object.defineProperties(this, {
  1699. original: { writable: true, value: string },
  1700. outro: { writable: true, value: '' },
  1701. intro: { writable: true, value: '' },
  1702. firstChunk: { writable: true, value: chunk },
  1703. lastChunk: { writable: true, value: chunk },
  1704. lastSearchedChunk: { writable: true, value: chunk },
  1705. byStart: { writable: true, value: {} },
  1706. byEnd: { writable: true, value: {} },
  1707. filename: { writable: true, value: options.filename },
  1708. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  1709. sourcemapLocations: { writable: true, value: new BitSet() },
  1710. storedNames: { writable: true, value: {} },
  1711. indentStr: { writable: true, value: undefined },
  1712. });
  1713. this.byStart[0] = chunk;
  1714. this.byEnd[string.length] = chunk;
  1715. }
  1716. addSourcemapLocation(char) {
  1717. this.sourcemapLocations.add(char);
  1718. }
  1719. append(content) {
  1720. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  1721. this.outro += content;
  1722. return this;
  1723. }
  1724. appendLeft(index, content) {
  1725. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1726. this._split(index);
  1727. const chunk = this.byEnd[index];
  1728. if (chunk) {
  1729. chunk.appendLeft(content);
  1730. } else {
  1731. this.intro += content;
  1732. }
  1733. return this;
  1734. }
  1735. appendRight(index, content) {
  1736. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1737. this._split(index);
  1738. const chunk = this.byStart[index];
  1739. if (chunk) {
  1740. chunk.appendRight(content);
  1741. } else {
  1742. this.outro += content;
  1743. }
  1744. return this;
  1745. }
  1746. clone() {
  1747. const cloned = new MagicString(this.original, { filename: this.filename });
  1748. let originalChunk = this.firstChunk;
  1749. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  1750. while (originalChunk) {
  1751. cloned.byStart[clonedChunk.start] = clonedChunk;
  1752. cloned.byEnd[clonedChunk.end] = clonedChunk;
  1753. const nextOriginalChunk = originalChunk.next;
  1754. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  1755. if (nextClonedChunk) {
  1756. clonedChunk.next = nextClonedChunk;
  1757. nextClonedChunk.previous = clonedChunk;
  1758. clonedChunk = nextClonedChunk;
  1759. }
  1760. originalChunk = nextOriginalChunk;
  1761. }
  1762. cloned.lastChunk = clonedChunk;
  1763. if (this.indentExclusionRanges) {
  1764. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  1765. }
  1766. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  1767. cloned.intro = this.intro;
  1768. cloned.outro = this.outro;
  1769. return cloned;
  1770. }
  1771. generateDecodedMap(options) {
  1772. options = options || {};
  1773. const sourceIndex = 0;
  1774. const names = Object.keys(this.storedNames);
  1775. const mappings = new Mappings(options.hires);
  1776. const locate = getLocator(this.original);
  1777. if (this.intro) {
  1778. mappings.advance(this.intro);
  1779. }
  1780. this.firstChunk.eachNext((chunk) => {
  1781. const loc = locate(chunk.start);
  1782. if (chunk.intro.length) mappings.advance(chunk.intro);
  1783. if (chunk.edited) {
  1784. mappings.addEdit(
  1785. sourceIndex,
  1786. chunk.content,
  1787. loc,
  1788. chunk.storeName ? names.indexOf(chunk.original) : -1
  1789. );
  1790. } else {
  1791. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  1792. }
  1793. if (chunk.outro.length) mappings.advance(chunk.outro);
  1794. });
  1795. return {
  1796. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1797. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  1798. sourcesContent: options.includeContent ? [this.original] : [null],
  1799. names,
  1800. mappings: mappings.raw,
  1801. };
  1802. }
  1803. generateMap(options) {
  1804. return new SourceMap(this.generateDecodedMap(options));
  1805. }
  1806. _ensureindentStr() {
  1807. if (this.indentStr === undefined) {
  1808. this.indentStr = guessIndent(this.original);
  1809. }
  1810. }
  1811. _getRawIndentString() {
  1812. this._ensureindentStr();
  1813. return this.indentStr;
  1814. }
  1815. getIndentString() {
  1816. this._ensureindentStr();
  1817. return this.indentStr === null ? '\t' : this.indentStr;
  1818. }
  1819. indent(indentStr, options) {
  1820. const pattern = /^[^\r\n]/gm;
  1821. if (isObject$1(indentStr)) {
  1822. options = indentStr;
  1823. indentStr = undefined;
  1824. }
  1825. if (indentStr === undefined) {
  1826. this._ensureindentStr();
  1827. indentStr = this.indentStr || '\t';
  1828. }
  1829. if (indentStr === '') return this; // noop
  1830. options = options || {};
  1831. // Process exclusion ranges
  1832. const isExcluded = {};
  1833. if (options.exclude) {
  1834. const exclusions =
  1835. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  1836. exclusions.forEach((exclusion) => {
  1837. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  1838. isExcluded[i] = true;
  1839. }
  1840. });
  1841. }
  1842. let shouldIndentNextCharacter = options.indentStart !== false;
  1843. const replacer = (match) => {
  1844. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  1845. shouldIndentNextCharacter = true;
  1846. return match;
  1847. };
  1848. this.intro = this.intro.replace(pattern, replacer);
  1849. let charIndex = 0;
  1850. let chunk = this.firstChunk;
  1851. while (chunk) {
  1852. const end = chunk.end;
  1853. if (chunk.edited) {
  1854. if (!isExcluded[charIndex]) {
  1855. chunk.content = chunk.content.replace(pattern, replacer);
  1856. if (chunk.content.length) {
  1857. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  1858. }
  1859. }
  1860. } else {
  1861. charIndex = chunk.start;
  1862. while (charIndex < end) {
  1863. if (!isExcluded[charIndex]) {
  1864. const char = this.original[charIndex];
  1865. if (char === '\n') {
  1866. shouldIndentNextCharacter = true;
  1867. } else if (char !== '\r' && shouldIndentNextCharacter) {
  1868. shouldIndentNextCharacter = false;
  1869. if (charIndex === chunk.start) {
  1870. chunk.prependRight(indentStr);
  1871. } else {
  1872. this._splitChunk(chunk, charIndex);
  1873. chunk = chunk.next;
  1874. chunk.prependRight(indentStr);
  1875. }
  1876. }
  1877. }
  1878. charIndex += 1;
  1879. }
  1880. }
  1881. charIndex = chunk.end;
  1882. chunk = chunk.next;
  1883. }
  1884. this.outro = this.outro.replace(pattern, replacer);
  1885. return this;
  1886. }
  1887. insert() {
  1888. throw new Error(
  1889. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  1890. );
  1891. }
  1892. insertLeft(index, content) {
  1893. if (!warned.insertLeft) {
  1894. console.warn(
  1895. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  1896. ); // eslint-disable-line no-console
  1897. warned.insertLeft = true;
  1898. }
  1899. return this.appendLeft(index, content);
  1900. }
  1901. insertRight(index, content) {
  1902. if (!warned.insertRight) {
  1903. console.warn(
  1904. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  1905. ); // eslint-disable-line no-console
  1906. warned.insertRight = true;
  1907. }
  1908. return this.prependRight(index, content);
  1909. }
  1910. move(start, end, index) {
  1911. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  1912. this._split(start);
  1913. this._split(end);
  1914. this._split(index);
  1915. const first = this.byStart[start];
  1916. const last = this.byEnd[end];
  1917. const oldLeft = first.previous;
  1918. const oldRight = last.next;
  1919. const newRight = this.byStart[index];
  1920. if (!newRight && last === this.lastChunk) return this;
  1921. const newLeft = newRight ? newRight.previous : this.lastChunk;
  1922. if (oldLeft) oldLeft.next = oldRight;
  1923. if (oldRight) oldRight.previous = oldLeft;
  1924. if (newLeft) newLeft.next = first;
  1925. if (newRight) newRight.previous = last;
  1926. if (!first.previous) this.firstChunk = last.next;
  1927. if (!last.next) {
  1928. this.lastChunk = first.previous;
  1929. this.lastChunk.next = null;
  1930. }
  1931. first.previous = newLeft;
  1932. last.next = newRight || null;
  1933. if (!newLeft) this.firstChunk = first;
  1934. if (!newRight) this.lastChunk = last;
  1935. return this;
  1936. }
  1937. overwrite(start, end, content, options) {
  1938. options = options || {};
  1939. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  1940. }
  1941. update(start, end, content, options) {
  1942. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  1943. while (start < 0) start += this.original.length;
  1944. while (end < 0) end += this.original.length;
  1945. if (end > this.original.length) throw new Error('end is out of bounds');
  1946. if (start === end)
  1947. throw new Error(
  1948. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  1949. );
  1950. this._split(start);
  1951. this._split(end);
  1952. if (options === true) {
  1953. if (!warned.storeName) {
  1954. console.warn(
  1955. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  1956. ); // eslint-disable-line no-console
  1957. warned.storeName = true;
  1958. }
  1959. options = { storeName: true };
  1960. }
  1961. const storeName = options !== undefined ? options.storeName : false;
  1962. const overwrite = options !== undefined ? options.overwrite : false;
  1963. if (storeName) {
  1964. const original = this.original.slice(start, end);
  1965. Object.defineProperty(this.storedNames, original, {
  1966. writable: true,
  1967. value: true,
  1968. enumerable: true,
  1969. });
  1970. }
  1971. const first = this.byStart[start];
  1972. const last = this.byEnd[end];
  1973. if (first) {
  1974. let chunk = first;
  1975. while (chunk !== last) {
  1976. if (chunk.next !== this.byStart[chunk.end]) {
  1977. throw new Error('Cannot overwrite across a split point');
  1978. }
  1979. chunk = chunk.next;
  1980. chunk.edit('', false);
  1981. }
  1982. first.edit(content, storeName, !overwrite);
  1983. } else {
  1984. // must be inserting at the end
  1985. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  1986. // TODO last chunk in the array may not be the last chunk, if it's moved...
  1987. last.next = newChunk;
  1988. newChunk.previous = last;
  1989. }
  1990. return this;
  1991. }
  1992. prepend(content) {
  1993. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  1994. this.intro = content + this.intro;
  1995. return this;
  1996. }
  1997. prependLeft(index, content) {
  1998. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1999. this._split(index);
  2000. const chunk = this.byEnd[index];
  2001. if (chunk) {
  2002. chunk.prependLeft(content);
  2003. } else {
  2004. this.intro = content + this.intro;
  2005. }
  2006. return this;
  2007. }
  2008. prependRight(index, content) {
  2009. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2010. this._split(index);
  2011. const chunk = this.byStart[index];
  2012. if (chunk) {
  2013. chunk.prependRight(content);
  2014. } else {
  2015. this.outro = content + this.outro;
  2016. }
  2017. return this;
  2018. }
  2019. remove(start, end) {
  2020. while (start < 0) start += this.original.length;
  2021. while (end < 0) end += this.original.length;
  2022. if (start === end) return this;
  2023. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  2024. if (start > end) throw new Error('end must be greater than start');
  2025. this._split(start);
  2026. this._split(end);
  2027. let chunk = this.byStart[start];
  2028. while (chunk) {
  2029. chunk.intro = '';
  2030. chunk.outro = '';
  2031. chunk.edit('');
  2032. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  2033. }
  2034. return this;
  2035. }
  2036. lastChar() {
  2037. if (this.outro.length) return this.outro[this.outro.length - 1];
  2038. let chunk = this.lastChunk;
  2039. do {
  2040. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  2041. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  2042. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  2043. } while ((chunk = chunk.previous));
  2044. if (this.intro.length) return this.intro[this.intro.length - 1];
  2045. return '';
  2046. }
  2047. lastLine() {
  2048. let lineIndex = this.outro.lastIndexOf(n);
  2049. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  2050. let lineStr = this.outro;
  2051. let chunk = this.lastChunk;
  2052. do {
  2053. if (chunk.outro.length > 0) {
  2054. lineIndex = chunk.outro.lastIndexOf(n);
  2055. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  2056. lineStr = chunk.outro + lineStr;
  2057. }
  2058. if (chunk.content.length > 0) {
  2059. lineIndex = chunk.content.lastIndexOf(n);
  2060. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  2061. lineStr = chunk.content + lineStr;
  2062. }
  2063. if (chunk.intro.length > 0) {
  2064. lineIndex = chunk.intro.lastIndexOf(n);
  2065. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  2066. lineStr = chunk.intro + lineStr;
  2067. }
  2068. } while ((chunk = chunk.previous));
  2069. lineIndex = this.intro.lastIndexOf(n);
  2070. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  2071. return this.intro + lineStr;
  2072. }
  2073. slice(start = 0, end = this.original.length) {
  2074. while (start < 0) start += this.original.length;
  2075. while (end < 0) end += this.original.length;
  2076. let result = '';
  2077. // find start chunk
  2078. let chunk = this.firstChunk;
  2079. while (chunk && (chunk.start > start || chunk.end <= start)) {
  2080. // found end chunk before start
  2081. if (chunk.start < end && chunk.end >= end) {
  2082. return result;
  2083. }
  2084. chunk = chunk.next;
  2085. }
  2086. if (chunk && chunk.edited && chunk.start !== start)
  2087. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  2088. const startChunk = chunk;
  2089. while (chunk) {
  2090. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  2091. result += chunk.intro;
  2092. }
  2093. const containsEnd = chunk.start < end && chunk.end >= end;
  2094. if (containsEnd && chunk.edited && chunk.end !== end)
  2095. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  2096. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  2097. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  2098. result += chunk.content.slice(sliceStart, sliceEnd);
  2099. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  2100. result += chunk.outro;
  2101. }
  2102. if (containsEnd) {
  2103. break;
  2104. }
  2105. chunk = chunk.next;
  2106. }
  2107. return result;
  2108. }
  2109. // TODO deprecate this? not really very useful
  2110. snip(start, end) {
  2111. const clone = this.clone();
  2112. clone.remove(0, start);
  2113. clone.remove(end, clone.original.length);
  2114. return clone;
  2115. }
  2116. _split(index) {
  2117. if (this.byStart[index] || this.byEnd[index]) return;
  2118. let chunk = this.lastSearchedChunk;
  2119. const searchForward = index > chunk.end;
  2120. while (chunk) {
  2121. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  2122. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  2123. }
  2124. }
  2125. _splitChunk(chunk, index) {
  2126. if (chunk.edited && chunk.content.length) {
  2127. // zero-length edited chunks are a special case (overlapping replacements)
  2128. const loc = getLocator(this.original)(index);
  2129. throw new Error(
  2130. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
  2131. );
  2132. }
  2133. const newChunk = chunk.split(index);
  2134. this.byEnd[index] = chunk;
  2135. this.byStart[index] = newChunk;
  2136. this.byEnd[newChunk.end] = newChunk;
  2137. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  2138. this.lastSearchedChunk = chunk;
  2139. return true;
  2140. }
  2141. toString() {
  2142. let str = this.intro;
  2143. let chunk = this.firstChunk;
  2144. while (chunk) {
  2145. str += chunk.toString();
  2146. chunk = chunk.next;
  2147. }
  2148. return str + this.outro;
  2149. }
  2150. isEmpty() {
  2151. let chunk = this.firstChunk;
  2152. do {
  2153. if (
  2154. (chunk.intro.length && chunk.intro.trim()) ||
  2155. (chunk.content.length && chunk.content.trim()) ||
  2156. (chunk.outro.length && chunk.outro.trim())
  2157. )
  2158. return false;
  2159. } while ((chunk = chunk.next));
  2160. return true;
  2161. }
  2162. length() {
  2163. let chunk = this.firstChunk;
  2164. let length = 0;
  2165. do {
  2166. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  2167. } while ((chunk = chunk.next));
  2168. return length;
  2169. }
  2170. trimLines() {
  2171. return this.trim('[\\r\\n]');
  2172. }
  2173. trim(charType) {
  2174. return this.trimStart(charType).trimEnd(charType);
  2175. }
  2176. trimEndAborted(charType) {
  2177. const rx = new RegExp((charType || '\\s') + '+$');
  2178. this.outro = this.outro.replace(rx, '');
  2179. if (this.outro.length) return true;
  2180. let chunk = this.lastChunk;
  2181. do {
  2182. const end = chunk.end;
  2183. const aborted = chunk.trimEnd(rx);
  2184. // if chunk was trimmed, we have a new lastChunk
  2185. if (chunk.end !== end) {
  2186. if (this.lastChunk === chunk) {
  2187. this.lastChunk = chunk.next;
  2188. }
  2189. this.byEnd[chunk.end] = chunk;
  2190. this.byStart[chunk.next.start] = chunk.next;
  2191. this.byEnd[chunk.next.end] = chunk.next;
  2192. }
  2193. if (aborted) return true;
  2194. chunk = chunk.previous;
  2195. } while (chunk);
  2196. return false;
  2197. }
  2198. trimEnd(charType) {
  2199. this.trimEndAborted(charType);
  2200. return this;
  2201. }
  2202. trimStartAborted(charType) {
  2203. const rx = new RegExp('^' + (charType || '\\s') + '+');
  2204. this.intro = this.intro.replace(rx, '');
  2205. if (this.intro.length) return true;
  2206. let chunk = this.firstChunk;
  2207. do {
  2208. const end = chunk.end;
  2209. const aborted = chunk.trimStart(rx);
  2210. if (chunk.end !== end) {
  2211. // special case...
  2212. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  2213. this.byEnd[chunk.end] = chunk;
  2214. this.byStart[chunk.next.start] = chunk.next;
  2215. this.byEnd[chunk.next.end] = chunk.next;
  2216. }
  2217. if (aborted) return true;
  2218. chunk = chunk.next;
  2219. } while (chunk);
  2220. return false;
  2221. }
  2222. trimStart(charType) {
  2223. this.trimStartAborted(charType);
  2224. return this;
  2225. }
  2226. hasChanged() {
  2227. return this.original !== this.toString();
  2228. }
  2229. _replaceRegexp(searchValue, replacement) {
  2230. function getReplacement(match, str) {
  2231. if (typeof replacement === 'string') {
  2232. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  2233. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  2234. if (i === '$') return '$';
  2235. if (i === '&') return match[0];
  2236. const num = +i;
  2237. if (num < match.length) return match[+i];
  2238. return `$${i}`;
  2239. });
  2240. } else {
  2241. return replacement(...match, match.index, str, match.groups);
  2242. }
  2243. }
  2244. function matchAll(re, str) {
  2245. let match;
  2246. const matches = [];
  2247. while ((match = re.exec(str))) {
  2248. matches.push(match);
  2249. }
  2250. return matches;
  2251. }
  2252. if (searchValue.global) {
  2253. const matches = matchAll(searchValue, this.original);
  2254. matches.forEach((match) => {
  2255. if (match.index != null)
  2256. this.overwrite(
  2257. match.index,
  2258. match.index + match[0].length,
  2259. getReplacement(match, this.original)
  2260. );
  2261. });
  2262. } else {
  2263. const match = this.original.match(searchValue);
  2264. if (match && match.index != null)
  2265. this.overwrite(
  2266. match.index,
  2267. match.index + match[0].length,
  2268. getReplacement(match, this.original)
  2269. );
  2270. }
  2271. return this;
  2272. }
  2273. _replaceString(string, replacement) {
  2274. const { original } = this;
  2275. const index = original.indexOf(string);
  2276. if (index !== -1) {
  2277. this.overwrite(index, index + string.length, replacement);
  2278. }
  2279. return this;
  2280. }
  2281. replace(searchValue, replacement) {
  2282. if (typeof searchValue === 'string') {
  2283. return this._replaceString(searchValue, replacement);
  2284. }
  2285. return this._replaceRegexp(searchValue, replacement);
  2286. }
  2287. _replaceAllString(string, replacement) {
  2288. const { original } = this;
  2289. const stringLength = string.length;
  2290. for (
  2291. let index = original.indexOf(string);
  2292. index !== -1;
  2293. index = original.indexOf(string, index + stringLength)
  2294. ) {
  2295. this.overwrite(index, index + stringLength, replacement);
  2296. }
  2297. return this;
  2298. }
  2299. replaceAll(searchValue, replacement) {
  2300. if (typeof searchValue === 'string') {
  2301. return this._replaceAllString(searchValue, replacement);
  2302. }
  2303. if (!searchValue.global) {
  2304. throw new TypeError(
  2305. 'MagicString.prototype.replaceAll called with a non-global RegExp argument'
  2306. );
  2307. }
  2308. return this._replaceRegexp(searchValue, replacement);
  2309. }
  2310. }
  2311. const hasOwnProp = Object.prototype.hasOwnProperty;
  2312. let Bundle$1 = class Bundle {
  2313. constructor(options = {}) {
  2314. this.intro = options.intro || '';
  2315. this.separator = options.separator !== undefined ? options.separator : '\n';
  2316. this.sources = [];
  2317. this.uniqueSources = [];
  2318. this.uniqueSourceIndexByFilename = {};
  2319. }
  2320. addSource(source) {
  2321. if (source instanceof MagicString) {
  2322. return this.addSource({
  2323. content: source,
  2324. filename: source.filename,
  2325. separator: this.separator,
  2326. });
  2327. }
  2328. if (!isObject$1(source) || !source.content) {
  2329. throw new Error(
  2330. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'
  2331. );
  2332. }
  2333. ['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {
  2334. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  2335. });
  2336. if (source.separator === undefined) {
  2337. // TODO there's a bunch of this sort of thing, needs cleaning up
  2338. source.separator = this.separator;
  2339. }
  2340. if (source.filename) {
  2341. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  2342. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  2343. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  2344. } else {
  2345. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  2346. if (source.content.original !== uniqueSource.content) {
  2347. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  2348. }
  2349. }
  2350. }
  2351. this.sources.push(source);
  2352. return this;
  2353. }
  2354. append(str, options) {
  2355. this.addSource({
  2356. content: new MagicString(str),
  2357. separator: (options && options.separator) || '',
  2358. });
  2359. return this;
  2360. }
  2361. clone() {
  2362. const bundle = new Bundle({
  2363. intro: this.intro,
  2364. separator: this.separator,
  2365. });
  2366. this.sources.forEach((source) => {
  2367. bundle.addSource({
  2368. filename: source.filename,
  2369. content: source.content.clone(),
  2370. separator: source.separator,
  2371. });
  2372. });
  2373. return bundle;
  2374. }
  2375. generateDecodedMap(options = {}) {
  2376. const names = [];
  2377. this.sources.forEach((source) => {
  2378. Object.keys(source.content.storedNames).forEach((name) => {
  2379. if (!~names.indexOf(name)) names.push(name);
  2380. });
  2381. });
  2382. const mappings = new Mappings(options.hires);
  2383. if (this.intro) {
  2384. mappings.advance(this.intro);
  2385. }
  2386. this.sources.forEach((source, i) => {
  2387. if (i > 0) {
  2388. mappings.advance(this.separator);
  2389. }
  2390. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  2391. const magicString = source.content;
  2392. const locate = getLocator(magicString.original);
  2393. if (magicString.intro) {
  2394. mappings.advance(magicString.intro);
  2395. }
  2396. magicString.firstChunk.eachNext((chunk) => {
  2397. const loc = locate(chunk.start);
  2398. if (chunk.intro.length) mappings.advance(chunk.intro);
  2399. if (source.filename) {
  2400. if (chunk.edited) {
  2401. mappings.addEdit(
  2402. sourceIndex,
  2403. chunk.content,
  2404. loc,
  2405. chunk.storeName ? names.indexOf(chunk.original) : -1
  2406. );
  2407. } else {
  2408. mappings.addUneditedChunk(
  2409. sourceIndex,
  2410. chunk,
  2411. magicString.original,
  2412. loc,
  2413. magicString.sourcemapLocations
  2414. );
  2415. }
  2416. } else {
  2417. mappings.advance(chunk.content);
  2418. }
  2419. if (chunk.outro.length) mappings.advance(chunk.outro);
  2420. });
  2421. if (magicString.outro) {
  2422. mappings.advance(magicString.outro);
  2423. }
  2424. });
  2425. return {
  2426. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  2427. sources: this.uniqueSources.map((source) => {
  2428. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  2429. }),
  2430. sourcesContent: this.uniqueSources.map((source) => {
  2431. return options.includeContent ? source.content : null;
  2432. }),
  2433. names,
  2434. mappings: mappings.raw,
  2435. };
  2436. }
  2437. generateMap(options) {
  2438. return new SourceMap(this.generateDecodedMap(options));
  2439. }
  2440. getIndentString() {
  2441. const indentStringCounts = {};
  2442. this.sources.forEach((source) => {
  2443. const indentStr = source.content._getRawIndentString();
  2444. if (indentStr === null) return;
  2445. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  2446. indentStringCounts[indentStr] += 1;
  2447. });
  2448. return (
  2449. Object.keys(indentStringCounts).sort((a, b) => {
  2450. return indentStringCounts[a] - indentStringCounts[b];
  2451. })[0] || '\t'
  2452. );
  2453. }
  2454. indent(indentStr) {
  2455. if (!arguments.length) {
  2456. indentStr = this.getIndentString();
  2457. }
  2458. if (indentStr === '') return this; // noop
  2459. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  2460. this.sources.forEach((source, i) => {
  2461. const separator = source.separator !== undefined ? source.separator : this.separator;
  2462. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  2463. source.content.indent(indentStr, {
  2464. exclude: source.indentExclusionRanges,
  2465. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  2466. });
  2467. trailingNewline = source.content.lastChar() === '\n';
  2468. });
  2469. if (this.intro) {
  2470. this.intro =
  2471. indentStr +
  2472. this.intro.replace(/^[^\n]/gm, (match, index) => {
  2473. return index > 0 ? indentStr + match : match;
  2474. });
  2475. }
  2476. return this;
  2477. }
  2478. prepend(str) {
  2479. this.intro = str + this.intro;
  2480. return this;
  2481. }
  2482. toString() {
  2483. const body = this.sources
  2484. .map((source, i) => {
  2485. const separator = source.separator !== undefined ? source.separator : this.separator;
  2486. const str = (i > 0 ? separator : '') + source.content.toString();
  2487. return str;
  2488. })
  2489. .join('');
  2490. return this.intro + body;
  2491. }
  2492. isEmpty() {
  2493. if (this.intro.length && this.intro.trim()) return false;
  2494. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  2495. return true;
  2496. }
  2497. length() {
  2498. return this.sources.reduce(
  2499. (length, source) => length + source.content.length(),
  2500. this.intro.length
  2501. );
  2502. }
  2503. trimLines() {
  2504. return this.trim('[\\r\\n]');
  2505. }
  2506. trim(charType) {
  2507. return this.trimStart(charType).trimEnd(charType);
  2508. }
  2509. trimStart(charType) {
  2510. const rx = new RegExp('^' + (charType || '\\s') + '+');
  2511. this.intro = this.intro.replace(rx, '');
  2512. if (!this.intro) {
  2513. let source;
  2514. let i = 0;
  2515. do {
  2516. source = this.sources[i++];
  2517. if (!source) {
  2518. break;
  2519. }
  2520. } while (!source.content.trimStartAborted(charType));
  2521. }
  2522. return this;
  2523. }
  2524. trimEnd(charType) {
  2525. const rx = new RegExp((charType || '\\s') + '+$');
  2526. let source;
  2527. let i = this.sources.length - 1;
  2528. do {
  2529. source = this.sources[i--];
  2530. if (!source) {
  2531. this.intro = this.intro.replace(rx, '');
  2532. break;
  2533. }
  2534. } while (!source.content.trimEndAborted(charType));
  2535. return this;
  2536. }
  2537. };
  2538. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  2539. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  2540. const backSlashRegEx = /\\/g;
  2541. function escapeId(id) {
  2542. if (!needsEscapeRegEx.test(id))
  2543. return id;
  2544. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  2545. }
  2546. class ExternalChunk {
  2547. constructor(module, options, inputBase) {
  2548. this.options = options;
  2549. this.inputBase = inputBase;
  2550. this.defaultVariableName = '';
  2551. this.namespaceVariableName = '';
  2552. this.variableName = '';
  2553. this.fileName = null;
  2554. this.importAssertions = null;
  2555. this.id = module.id;
  2556. this.moduleInfo = module.info;
  2557. this.renormalizeRenderPath = module.renormalizeRenderPath;
  2558. this.suggestedVariableName = module.suggestedVariableName;
  2559. }
  2560. getFileName() {
  2561. if (this.fileName) {
  2562. return this.fileName;
  2563. }
  2564. const { paths } = this.options;
  2565. return (this.fileName =
  2566. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  2567. (this.renormalizeRenderPath ? normalize(node_path.relative(this.inputBase, this.id)) : this.id));
  2568. }
  2569. getImportAssertions(snippets) {
  2570. return (this.importAssertions || (this.importAssertions = formatAssertions(this.options.format === 'es' &&
  2571. this.options.externalImportAssertions &&
  2572. this.moduleInfo.assertions, snippets)));
  2573. }
  2574. getImportPath(importer) {
  2575. return escapeId(this.renormalizeRenderPath
  2576. ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  2577. : this.getFileName());
  2578. }
  2579. }
  2580. function formatAssertions(assertions, { getObject }) {
  2581. if (!assertions) {
  2582. return null;
  2583. }
  2584. const assertionEntries = Object.entries(assertions).map(([key, value]) => [key, `'${value}'`]);
  2585. if (assertionEntries.length > 0) {
  2586. return getObject(assertionEntries, { lineBreakIndent: null });
  2587. }
  2588. return null;
  2589. }
  2590. function getOrCreate(map, key, init) {
  2591. const existing = map.get(key);
  2592. if (existing !== undefined) {
  2593. return existing;
  2594. }
  2595. const value = init();
  2596. map.set(key, value);
  2597. return value;
  2598. }
  2599. function getNewSet() {
  2600. return new Set();
  2601. }
  2602. function getNewArray() {
  2603. return [];
  2604. }
  2605. const UnknownKey = Symbol('Unknown Key');
  2606. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  2607. const UnknownInteger = Symbol('Unknown Integer');
  2608. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  2609. const EMPTY_PATH = [];
  2610. const UNKNOWN_PATH = [UnknownKey];
  2611. // For deoptimizations, this means we are modifying an unknown property but did
  2612. // not lose track of the object or are creating a setter/getter;
  2613. // For assignment effects it means we do not check for setter/getter effects
  2614. // but only if something is mutated that is included, which is relevant for
  2615. // Object.defineProperty
  2616. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  2617. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  2618. const EntitiesKey = Symbol('Entities');
  2619. class PathTracker {
  2620. constructor() {
  2621. this.entityPaths = Object.create(null, {
  2622. [EntitiesKey]: { value: new Set() }
  2623. });
  2624. }
  2625. trackEntityAtPathAndGetIfTracked(path, entity) {
  2626. const trackedEntities = this.getEntities(path);
  2627. if (trackedEntities.has(entity))
  2628. return true;
  2629. trackedEntities.add(entity);
  2630. return false;
  2631. }
  2632. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  2633. const trackedEntities = this.getEntities(path);
  2634. if (trackedEntities.has(entity))
  2635. return returnIfTracked;
  2636. trackedEntities.add(entity);
  2637. const result = onUntracked();
  2638. trackedEntities.delete(entity);
  2639. return result;
  2640. }
  2641. getEntities(path) {
  2642. let currentPaths = this.entityPaths;
  2643. for (const pathSegment of path) {
  2644. currentPaths = currentPaths[pathSegment] =
  2645. currentPaths[pathSegment] ||
  2646. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  2647. }
  2648. return currentPaths[EntitiesKey];
  2649. }
  2650. }
  2651. const SHARED_RECURSION_TRACKER = new PathTracker();
  2652. class DiscriminatedPathTracker {
  2653. constructor() {
  2654. this.entityPaths = Object.create(null, {
  2655. [EntitiesKey]: { value: new Map() }
  2656. });
  2657. }
  2658. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  2659. let currentPaths = this.entityPaths;
  2660. for (const pathSegment of path) {
  2661. currentPaths = currentPaths[pathSegment] =
  2662. currentPaths[pathSegment] ||
  2663. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  2664. }
  2665. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  2666. if (trackedEntities.has(entity))
  2667. return true;
  2668. trackedEntities.add(entity);
  2669. return false;
  2670. }
  2671. }
  2672. const UnknownValue = Symbol('Unknown Value');
  2673. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  2674. class ExpressionEntity {
  2675. constructor() {
  2676. this.included = false;
  2677. }
  2678. deoptimizePath(_path) { }
  2679. deoptimizeThisOnInteractionAtPath({ thisArg }, _path, _recursionTracker) {
  2680. thisArg.deoptimizePath(UNKNOWN_PATH);
  2681. }
  2682. /**
  2683. * If possible it returns a stringifyable literal value for this node that can be used
  2684. * for inlining or comparing values.
  2685. * Otherwise, it should return UnknownValue.
  2686. */
  2687. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  2688. return UnknownValue;
  2689. }
  2690. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  2691. return UNKNOWN_RETURN_EXPRESSION;
  2692. }
  2693. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  2694. return true;
  2695. }
  2696. include(_context, _includeChildrenRecursively, _options) {
  2697. this.included = true;
  2698. }
  2699. includeCallArguments(context, parameters) {
  2700. for (const argument of parameters) {
  2701. argument.include(context, false);
  2702. }
  2703. }
  2704. shouldBeIncluded(_context) {
  2705. return true;
  2706. }
  2707. }
  2708. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  2709. })();
  2710. const UNKNOWN_RETURN_EXPRESSION = [
  2711. UNKNOWN_EXPRESSION,
  2712. false
  2713. ];
  2714. const INTERACTION_ACCESSED = 0;
  2715. const INTERACTION_ASSIGNED = 1;
  2716. const INTERACTION_CALLED = 2;
  2717. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  2718. thisArg: null,
  2719. type: INTERACTION_ACCESSED
  2720. };
  2721. const UNKNOWN_ARG = [UNKNOWN_EXPRESSION];
  2722. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  2723. args: UNKNOWN_ARG,
  2724. thisArg: null,
  2725. type: INTERACTION_ASSIGNED
  2726. };
  2727. const NO_ARGS = [];
  2728. // While this is technically a call without arguments, we can compare against
  2729. // this reference in places where precise values or thisArg would make a
  2730. // difference
  2731. const NODE_INTERACTION_UNKNOWN_CALL = {
  2732. args: NO_ARGS,
  2733. thisArg: null,
  2734. type: INTERACTION_CALLED,
  2735. withNew: false
  2736. };
  2737. class Variable extends ExpressionEntity {
  2738. constructor(name) {
  2739. super();
  2740. this.name = name;
  2741. this.alwaysRendered = false;
  2742. this.forbiddenNames = null;
  2743. this.initReached = false;
  2744. this.isId = false;
  2745. this.isReassigned = false;
  2746. this.kind = null;
  2747. this.renderBaseName = null;
  2748. this.renderName = null;
  2749. }
  2750. /**
  2751. * Binds identifiers that reference this variable to this variable.
  2752. * Necessary to be able to change variable names.
  2753. */
  2754. addReference(_identifier) { }
  2755. /**
  2756. * Prevent this variable from being renamed to this name to avoid name
  2757. * collisions
  2758. */
  2759. forbidName(name) {
  2760. (this.forbiddenNames || (this.forbiddenNames = new Set())).add(name);
  2761. }
  2762. getBaseVariableName() {
  2763. return this.renderBaseName || this.renderName || this.name;
  2764. }
  2765. getName(getPropertyAccess, useOriginalName) {
  2766. if (useOriginalName?.(this)) {
  2767. return this.name;
  2768. }
  2769. const name = this.renderName || this.name;
  2770. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  2771. }
  2772. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  2773. return type !== INTERACTION_ACCESSED || path.length > 0;
  2774. }
  2775. /**
  2776. * Marks this variable as being part of the bundle, which is usually the case when one of
  2777. * its identifiers becomes part of the bundle. Returns true if it has not been included
  2778. * previously.
  2779. * Once a variable is included, it should take care all its declarations are included.
  2780. */
  2781. include() {
  2782. this.included = true;
  2783. }
  2784. markCalledFromTryStatement() { }
  2785. setRenderNames(baseName, name) {
  2786. this.renderBaseName = baseName;
  2787. this.renderName = name;
  2788. }
  2789. }
  2790. class ExternalVariable extends Variable {
  2791. constructor(module, name) {
  2792. super(name);
  2793. this.referenced = false;
  2794. this.module = module;
  2795. this.isNamespace = name === '*';
  2796. }
  2797. addReference(identifier) {
  2798. this.referenced = true;
  2799. if (this.name === 'default' || this.name === '*') {
  2800. this.module.suggestName(identifier.name);
  2801. }
  2802. }
  2803. hasEffectsOnInteractionAtPath(path, { type }) {
  2804. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  2805. }
  2806. include() {
  2807. if (!this.included) {
  2808. this.included = true;
  2809. this.module.used = true;
  2810. }
  2811. }
  2812. }
  2813. const RESERVED_NAMES = new Set([
  2814. 'await',
  2815. 'break',
  2816. 'case',
  2817. 'catch',
  2818. 'class',
  2819. 'const',
  2820. 'continue',
  2821. 'debugger',
  2822. 'default',
  2823. 'delete',
  2824. 'do',
  2825. 'else',
  2826. 'enum',
  2827. 'eval',
  2828. 'export',
  2829. 'extends',
  2830. 'false',
  2831. 'finally',
  2832. 'for',
  2833. 'function',
  2834. 'if',
  2835. 'implements',
  2836. 'import',
  2837. 'in',
  2838. 'instanceof',
  2839. 'interface',
  2840. 'let',
  2841. 'NaN',
  2842. 'new',
  2843. 'null',
  2844. 'package',
  2845. 'private',
  2846. 'protected',
  2847. 'public',
  2848. 'return',
  2849. 'static',
  2850. 'super',
  2851. 'switch',
  2852. 'this',
  2853. 'throw',
  2854. 'true',
  2855. 'try',
  2856. 'typeof',
  2857. 'undefined',
  2858. 'var',
  2859. 'void',
  2860. 'while',
  2861. 'with',
  2862. 'yield'
  2863. ]);
  2864. const RESERVED_NAMES$1 = RESERVED_NAMES;
  2865. const illegalCharacters = /[^\w$]/g;
  2866. const startsWithDigit = (value) => /\d/.test(value[0]);
  2867. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES$1.has(value) || value === 'arguments';
  2868. function isLegal(value) {
  2869. if (needsEscape(value)) {
  2870. return false;
  2871. }
  2872. return !illegalCharacters.test(value);
  2873. }
  2874. function makeLegal(value) {
  2875. value = value
  2876. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  2877. .replace(illegalCharacters, '_');
  2878. if (needsEscape(value))
  2879. value = `_${value}`;
  2880. return value || '_';
  2881. }
  2882. class ExternalModule {
  2883. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, assertions) {
  2884. this.options = options;
  2885. this.id = id;
  2886. this.renormalizeRenderPath = renormalizeRenderPath;
  2887. this.dynamicImporters = [];
  2888. this.execIndex = Infinity;
  2889. this.exportedVariables = new Map();
  2890. this.importers = [];
  2891. this.reexported = false;
  2892. this.used = false;
  2893. this.declarations = new Map();
  2894. this.mostCommonSuggestion = 0;
  2895. this.nameSuggestions = new Map();
  2896. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  2897. const { importers, dynamicImporters } = this;
  2898. const info = (this.info = {
  2899. assertions,
  2900. ast: null,
  2901. code: null,
  2902. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2903. dynamicallyImportedIds: EMPTY_ARRAY,
  2904. get dynamicImporters() {
  2905. return dynamicImporters.sort();
  2906. },
  2907. exportedBindings: null,
  2908. exports: null,
  2909. hasDefaultExport: null,
  2910. get hasModuleSideEffects() {
  2911. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options);
  2912. return info.moduleSideEffects;
  2913. },
  2914. id,
  2915. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2916. implicitlyLoadedBefore: EMPTY_ARRAY,
  2917. importedIdResolutions: EMPTY_ARRAY,
  2918. importedIds: EMPTY_ARRAY,
  2919. get importers() {
  2920. return importers.sort();
  2921. },
  2922. isEntry: false,
  2923. isExternal: true,
  2924. isIncluded: null,
  2925. meta,
  2926. moduleSideEffects,
  2927. syntheticNamedExports: false
  2928. });
  2929. // Hide the deprecated key so that it only warns when accessed explicitly
  2930. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  2931. enumerable: false
  2932. });
  2933. }
  2934. getVariableForExportName(name) {
  2935. const declaration = this.declarations.get(name);
  2936. if (declaration)
  2937. return [declaration];
  2938. const externalVariable = new ExternalVariable(this, name);
  2939. this.declarations.set(name, externalVariable);
  2940. this.exportedVariables.set(externalVariable, name);
  2941. return [externalVariable];
  2942. }
  2943. suggestName(name) {
  2944. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  2945. this.nameSuggestions.set(name, value);
  2946. if (value > this.mostCommonSuggestion) {
  2947. this.mostCommonSuggestion = value;
  2948. this.suggestedVariableName = name;
  2949. }
  2950. }
  2951. warnUnusedImports() {
  2952. const unused = [...this.declarations]
  2953. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2954. .map(([name]) => name);
  2955. if (unused.length === 0)
  2956. return;
  2957. const importersSet = new Set();
  2958. for (const name of unused) {
  2959. for (const importer of this.declarations.get(name).module.importers) {
  2960. importersSet.add(importer);
  2961. }
  2962. }
  2963. const importersArray = [...importersSet];
  2964. this.options.onwarn(errorUnusedExternalImports(this.id, unused, importersArray));
  2965. }
  2966. }
  2967. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  2968. function getDefaultExportFromCjs (x) {
  2969. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2970. }
  2971. function getAugmentedNamespace(n) {
  2972. if (n.__esModule) return n;
  2973. var f = n.default;
  2974. if (typeof f == "function") {
  2975. var a = function a () {
  2976. if (this instanceof a) {
  2977. var args = [null];
  2978. args.push.apply(args, arguments);
  2979. var Ctor = Function.bind.apply(f, args);
  2980. return new Ctor();
  2981. }
  2982. return f.apply(this, arguments);
  2983. };
  2984. a.prototype = f.prototype;
  2985. } else a = {};
  2986. Object.defineProperty(a, '__esModule', {value: true});
  2987. Object.keys(n).forEach(function (k) {
  2988. var d = Object.getOwnPropertyDescriptor(n, k);
  2989. Object.defineProperty(a, k, d.get ? d : {
  2990. enumerable: true,
  2991. get: function () {
  2992. return n[k];
  2993. }
  2994. });
  2995. });
  2996. return a;
  2997. }
  2998. exports.picomatchExports = {};
  2999. var picomatch$1 = {
  3000. get exports(){ return exports.picomatchExports; },
  3001. set exports(v){ exports.picomatchExports = v; },
  3002. };
  3003. var utils$3 = {};
  3004. const path$1 = require$$0$1;
  3005. const WIN_SLASH = '\\\\/';
  3006. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  3007. /**
  3008. * Posix glob regex
  3009. */
  3010. const DOT_LITERAL = '\\.';
  3011. const PLUS_LITERAL = '\\+';
  3012. const QMARK_LITERAL = '\\?';
  3013. const SLASH_LITERAL = '\\/';
  3014. const ONE_CHAR = '(?=.)';
  3015. const QMARK = '[^/]';
  3016. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  3017. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  3018. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  3019. const NO_DOT = `(?!${DOT_LITERAL})`;
  3020. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  3021. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  3022. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  3023. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  3024. const STAR = `${QMARK}*?`;
  3025. const POSIX_CHARS = {
  3026. DOT_LITERAL,
  3027. PLUS_LITERAL,
  3028. QMARK_LITERAL,
  3029. SLASH_LITERAL,
  3030. ONE_CHAR,
  3031. QMARK,
  3032. END_ANCHOR,
  3033. DOTS_SLASH,
  3034. NO_DOT,
  3035. NO_DOTS,
  3036. NO_DOT_SLASH,
  3037. NO_DOTS_SLASH,
  3038. QMARK_NO_DOT,
  3039. STAR,
  3040. START_ANCHOR
  3041. };
  3042. /**
  3043. * Windows glob regex
  3044. */
  3045. const WINDOWS_CHARS = {
  3046. ...POSIX_CHARS,
  3047. SLASH_LITERAL: `[${WIN_SLASH}]`,
  3048. QMARK: WIN_NO_SLASH,
  3049. STAR: `${WIN_NO_SLASH}*?`,
  3050. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  3051. NO_DOT: `(?!${DOT_LITERAL})`,
  3052. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  3053. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  3054. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  3055. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  3056. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  3057. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  3058. };
  3059. /**
  3060. * POSIX Bracket Regex
  3061. */
  3062. const POSIX_REGEX_SOURCE$1 = {
  3063. alnum: 'a-zA-Z0-9',
  3064. alpha: 'a-zA-Z',
  3065. ascii: '\\x00-\\x7F',
  3066. blank: ' \\t',
  3067. cntrl: '\\x00-\\x1F\\x7F',
  3068. digit: '0-9',
  3069. graph: '\\x21-\\x7E',
  3070. lower: 'a-z',
  3071. print: '\\x20-\\x7E ',
  3072. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  3073. space: ' \\t\\r\\n\\v\\f',
  3074. upper: 'A-Z',
  3075. word: 'A-Za-z0-9_',
  3076. xdigit: 'A-Fa-f0-9'
  3077. };
  3078. var constants$2 = {
  3079. MAX_LENGTH: 1024 * 64,
  3080. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  3081. // regular expressions
  3082. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  3083. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  3084. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  3085. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  3086. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  3087. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  3088. // Replace globs with equivalent patterns to reduce parsing time.
  3089. REPLACEMENTS: {
  3090. '***': '*',
  3091. '**/**': '**',
  3092. '**/**/**': '**'
  3093. },
  3094. // Digits
  3095. CHAR_0: 48, /* 0 */
  3096. CHAR_9: 57, /* 9 */
  3097. // Alphabet chars.
  3098. CHAR_UPPERCASE_A: 65, /* A */
  3099. CHAR_LOWERCASE_A: 97, /* a */
  3100. CHAR_UPPERCASE_Z: 90, /* Z */
  3101. CHAR_LOWERCASE_Z: 122, /* z */
  3102. CHAR_LEFT_PARENTHESES: 40, /* ( */
  3103. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  3104. CHAR_ASTERISK: 42, /* * */
  3105. // Non-alphabetic chars.
  3106. CHAR_AMPERSAND: 38, /* & */
  3107. CHAR_AT: 64, /* @ */
  3108. CHAR_BACKWARD_SLASH: 92, /* \ */
  3109. CHAR_CARRIAGE_RETURN: 13, /* \r */
  3110. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  3111. CHAR_COLON: 58, /* : */
  3112. CHAR_COMMA: 44, /* , */
  3113. CHAR_DOT: 46, /* . */
  3114. CHAR_DOUBLE_QUOTE: 34, /* " */
  3115. CHAR_EQUAL: 61, /* = */
  3116. CHAR_EXCLAMATION_MARK: 33, /* ! */
  3117. CHAR_FORM_FEED: 12, /* \f */
  3118. CHAR_FORWARD_SLASH: 47, /* / */
  3119. CHAR_GRAVE_ACCENT: 96, /* ` */
  3120. CHAR_HASH: 35, /* # */
  3121. CHAR_HYPHEN_MINUS: 45, /* - */
  3122. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  3123. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  3124. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  3125. CHAR_LINE_FEED: 10, /* \n */
  3126. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  3127. CHAR_PERCENT: 37, /* % */
  3128. CHAR_PLUS: 43, /* + */
  3129. CHAR_QUESTION_MARK: 63, /* ? */
  3130. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  3131. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  3132. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  3133. CHAR_SEMICOLON: 59, /* ; */
  3134. CHAR_SINGLE_QUOTE: 39, /* ' */
  3135. CHAR_SPACE: 32, /* */
  3136. CHAR_TAB: 9, /* \t */
  3137. CHAR_UNDERSCORE: 95, /* _ */
  3138. CHAR_VERTICAL_LINE: 124, /* | */
  3139. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  3140. SEP: path$1.sep,
  3141. /**
  3142. * Create EXTGLOB_CHARS
  3143. */
  3144. extglobChars(chars) {
  3145. return {
  3146. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  3147. '?': { type: 'qmark', open: '(?:', close: ')?' },
  3148. '+': { type: 'plus', open: '(?:', close: ')+' },
  3149. '*': { type: 'star', open: '(?:', close: ')*' },
  3150. '@': { type: 'at', open: '(?:', close: ')' }
  3151. };
  3152. },
  3153. /**
  3154. * Create GLOB_CHARS
  3155. */
  3156. globChars(win32) {
  3157. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  3158. }
  3159. };
  3160. (function (exports) {
  3161. const path = require$$0$1;
  3162. const win32 = process.platform === 'win32';
  3163. const {
  3164. REGEX_BACKSLASH,
  3165. REGEX_REMOVE_BACKSLASH,
  3166. REGEX_SPECIAL_CHARS,
  3167. REGEX_SPECIAL_CHARS_GLOBAL
  3168. } = constants$2;
  3169. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  3170. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  3171. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  3172. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  3173. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  3174. exports.removeBackslashes = str => {
  3175. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  3176. return match === '\\' ? '' : match;
  3177. });
  3178. };
  3179. exports.supportsLookbehinds = () => {
  3180. const segs = process.version.slice(1).split('.').map(Number);
  3181. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  3182. return true;
  3183. }
  3184. return false;
  3185. };
  3186. exports.isWindows = options => {
  3187. if (options && typeof options.windows === 'boolean') {
  3188. return options.windows;
  3189. }
  3190. return win32 === true || path.sep === '\\';
  3191. };
  3192. exports.escapeLast = (input, char, lastIdx) => {
  3193. const idx = input.lastIndexOf(char, lastIdx);
  3194. if (idx === -1) return input;
  3195. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  3196. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  3197. };
  3198. exports.removePrefix = (input, state = {}) => {
  3199. let output = input;
  3200. if (output.startsWith('./')) {
  3201. output = output.slice(2);
  3202. state.prefix = './';
  3203. }
  3204. return output;
  3205. };
  3206. exports.wrapOutput = (input, state = {}, options = {}) => {
  3207. const prepend = options.contains ? '' : '^';
  3208. const append = options.contains ? '' : '$';
  3209. let output = `${prepend}(?:${input})${append}`;
  3210. if (state.negated === true) {
  3211. output = `(?:^(?!${output}).*$)`;
  3212. }
  3213. return output;
  3214. };
  3215. } (utils$3));
  3216. const utils$2 = utils$3;
  3217. const {
  3218. CHAR_ASTERISK, /* * */
  3219. CHAR_AT, /* @ */
  3220. CHAR_BACKWARD_SLASH, /* \ */
  3221. CHAR_COMMA, /* , */
  3222. CHAR_DOT, /* . */
  3223. CHAR_EXCLAMATION_MARK, /* ! */
  3224. CHAR_FORWARD_SLASH, /* / */
  3225. CHAR_LEFT_CURLY_BRACE, /* { */
  3226. CHAR_LEFT_PARENTHESES, /* ( */
  3227. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  3228. CHAR_PLUS, /* + */
  3229. CHAR_QUESTION_MARK, /* ? */
  3230. CHAR_RIGHT_CURLY_BRACE, /* } */
  3231. CHAR_RIGHT_PARENTHESES, /* ) */
  3232. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  3233. } = constants$2;
  3234. const isPathSeparator = code => {
  3235. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  3236. };
  3237. const depth = token => {
  3238. if (token.isPrefix !== true) {
  3239. token.depth = token.isGlobstar ? Infinity : 1;
  3240. }
  3241. };
  3242. /**
  3243. * Quickly scans a glob pattern and returns an object with a handful of
  3244. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  3245. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  3246. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  3247. *
  3248. * ```js
  3249. * const pm = require('picomatch');
  3250. * console.log(pm.scan('foo/bar/*.js'));
  3251. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  3252. * ```
  3253. * @param {String} `str`
  3254. * @param {Object} `options`
  3255. * @return {Object} Returns an object with tokens and regex source string.
  3256. * @api public
  3257. */
  3258. const scan$1 = (input, options) => {
  3259. const opts = options || {};
  3260. const length = input.length - 1;
  3261. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  3262. const slashes = [];
  3263. const tokens = [];
  3264. const parts = [];
  3265. let str = input;
  3266. let index = -1;
  3267. let start = 0;
  3268. let lastIndex = 0;
  3269. let isBrace = false;
  3270. let isBracket = false;
  3271. let isGlob = false;
  3272. let isExtglob = false;
  3273. let isGlobstar = false;
  3274. let braceEscaped = false;
  3275. let backslashes = false;
  3276. let negated = false;
  3277. let negatedExtglob = false;
  3278. let finished = false;
  3279. let braces = 0;
  3280. let prev;
  3281. let code;
  3282. let token = { value: '', depth: 0, isGlob: false };
  3283. const eos = () => index >= length;
  3284. const peek = () => str.charCodeAt(index + 1);
  3285. const advance = () => {
  3286. prev = code;
  3287. return str.charCodeAt(++index);
  3288. };
  3289. while (index < length) {
  3290. code = advance();
  3291. let next;
  3292. if (code === CHAR_BACKWARD_SLASH) {
  3293. backslashes = token.backslashes = true;
  3294. code = advance();
  3295. if (code === CHAR_LEFT_CURLY_BRACE) {
  3296. braceEscaped = true;
  3297. }
  3298. continue;
  3299. }
  3300. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  3301. braces++;
  3302. while (eos() !== true && (code = advance())) {
  3303. if (code === CHAR_BACKWARD_SLASH) {
  3304. backslashes = token.backslashes = true;
  3305. advance();
  3306. continue;
  3307. }
  3308. if (code === CHAR_LEFT_CURLY_BRACE) {
  3309. braces++;
  3310. continue;
  3311. }
  3312. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  3313. isBrace = token.isBrace = true;
  3314. isGlob = token.isGlob = true;
  3315. finished = true;
  3316. if (scanToEnd === true) {
  3317. continue;
  3318. }
  3319. break;
  3320. }
  3321. if (braceEscaped !== true && code === CHAR_COMMA) {
  3322. isBrace = token.isBrace = true;
  3323. isGlob = token.isGlob = true;
  3324. finished = true;
  3325. if (scanToEnd === true) {
  3326. continue;
  3327. }
  3328. break;
  3329. }
  3330. if (code === CHAR_RIGHT_CURLY_BRACE) {
  3331. braces--;
  3332. if (braces === 0) {
  3333. braceEscaped = false;
  3334. isBrace = token.isBrace = true;
  3335. finished = true;
  3336. break;
  3337. }
  3338. }
  3339. }
  3340. if (scanToEnd === true) {
  3341. continue;
  3342. }
  3343. break;
  3344. }
  3345. if (code === CHAR_FORWARD_SLASH) {
  3346. slashes.push(index);
  3347. tokens.push(token);
  3348. token = { value: '', depth: 0, isGlob: false };
  3349. if (finished === true) continue;
  3350. if (prev === CHAR_DOT && index === (start + 1)) {
  3351. start += 2;
  3352. continue;
  3353. }
  3354. lastIndex = index + 1;
  3355. continue;
  3356. }
  3357. if (opts.noext !== true) {
  3358. const isExtglobChar = code === CHAR_PLUS
  3359. || code === CHAR_AT
  3360. || code === CHAR_ASTERISK
  3361. || code === CHAR_QUESTION_MARK
  3362. || code === CHAR_EXCLAMATION_MARK;
  3363. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  3364. isGlob = token.isGlob = true;
  3365. isExtglob = token.isExtglob = true;
  3366. finished = true;
  3367. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  3368. negatedExtglob = true;
  3369. }
  3370. if (scanToEnd === true) {
  3371. while (eos() !== true && (code = advance())) {
  3372. if (code === CHAR_BACKWARD_SLASH) {
  3373. backslashes = token.backslashes = true;
  3374. code = advance();
  3375. continue;
  3376. }
  3377. if (code === CHAR_RIGHT_PARENTHESES) {
  3378. isGlob = token.isGlob = true;
  3379. finished = true;
  3380. break;
  3381. }
  3382. }
  3383. continue;
  3384. }
  3385. break;
  3386. }
  3387. }
  3388. if (code === CHAR_ASTERISK) {
  3389. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  3390. isGlob = token.isGlob = true;
  3391. finished = true;
  3392. if (scanToEnd === true) {
  3393. continue;
  3394. }
  3395. break;
  3396. }
  3397. if (code === CHAR_QUESTION_MARK) {
  3398. isGlob = token.isGlob = true;
  3399. finished = true;
  3400. if (scanToEnd === true) {
  3401. continue;
  3402. }
  3403. break;
  3404. }
  3405. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  3406. while (eos() !== true && (next = advance())) {
  3407. if (next === CHAR_BACKWARD_SLASH) {
  3408. backslashes = token.backslashes = true;
  3409. advance();
  3410. continue;
  3411. }
  3412. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  3413. isBracket = token.isBracket = true;
  3414. isGlob = token.isGlob = true;
  3415. finished = true;
  3416. break;
  3417. }
  3418. }
  3419. if (scanToEnd === true) {
  3420. continue;
  3421. }
  3422. break;
  3423. }
  3424. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  3425. negated = token.negated = true;
  3426. start++;
  3427. continue;
  3428. }
  3429. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  3430. isGlob = token.isGlob = true;
  3431. if (scanToEnd === true) {
  3432. while (eos() !== true && (code = advance())) {
  3433. if (code === CHAR_LEFT_PARENTHESES) {
  3434. backslashes = token.backslashes = true;
  3435. code = advance();
  3436. continue;
  3437. }
  3438. if (code === CHAR_RIGHT_PARENTHESES) {
  3439. finished = true;
  3440. break;
  3441. }
  3442. }
  3443. continue;
  3444. }
  3445. break;
  3446. }
  3447. if (isGlob === true) {
  3448. finished = true;
  3449. if (scanToEnd === true) {
  3450. continue;
  3451. }
  3452. break;
  3453. }
  3454. }
  3455. if (opts.noext === true) {
  3456. isExtglob = false;
  3457. isGlob = false;
  3458. }
  3459. let base = str;
  3460. let prefix = '';
  3461. let glob = '';
  3462. if (start > 0) {
  3463. prefix = str.slice(0, start);
  3464. str = str.slice(start);
  3465. lastIndex -= start;
  3466. }
  3467. if (base && isGlob === true && lastIndex > 0) {
  3468. base = str.slice(0, lastIndex);
  3469. glob = str.slice(lastIndex);
  3470. } else if (isGlob === true) {
  3471. base = '';
  3472. glob = str;
  3473. } else {
  3474. base = str;
  3475. }
  3476. if (base && base !== '' && base !== '/' && base !== str) {
  3477. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  3478. base = base.slice(0, -1);
  3479. }
  3480. }
  3481. if (opts.unescape === true) {
  3482. if (glob) glob = utils$2.removeBackslashes(glob);
  3483. if (base && backslashes === true) {
  3484. base = utils$2.removeBackslashes(base);
  3485. }
  3486. }
  3487. const state = {
  3488. prefix,
  3489. input,
  3490. start,
  3491. base,
  3492. glob,
  3493. isBrace,
  3494. isBracket,
  3495. isGlob,
  3496. isExtglob,
  3497. isGlobstar,
  3498. negated,
  3499. negatedExtglob
  3500. };
  3501. if (opts.tokens === true) {
  3502. state.maxDepth = 0;
  3503. if (!isPathSeparator(code)) {
  3504. tokens.push(token);
  3505. }
  3506. state.tokens = tokens;
  3507. }
  3508. if (opts.parts === true || opts.tokens === true) {
  3509. let prevIndex;
  3510. for (let idx = 0; idx < slashes.length; idx++) {
  3511. const n = prevIndex ? prevIndex + 1 : start;
  3512. const i = slashes[idx];
  3513. const value = input.slice(n, i);
  3514. if (opts.tokens) {
  3515. if (idx === 0 && start !== 0) {
  3516. tokens[idx].isPrefix = true;
  3517. tokens[idx].value = prefix;
  3518. } else {
  3519. tokens[idx].value = value;
  3520. }
  3521. depth(tokens[idx]);
  3522. state.maxDepth += tokens[idx].depth;
  3523. }
  3524. if (idx !== 0 || value !== '') {
  3525. parts.push(value);
  3526. }
  3527. prevIndex = i;
  3528. }
  3529. if (prevIndex && prevIndex + 1 < input.length) {
  3530. const value = input.slice(prevIndex + 1);
  3531. parts.push(value);
  3532. if (opts.tokens) {
  3533. tokens[tokens.length - 1].value = value;
  3534. depth(tokens[tokens.length - 1]);
  3535. state.maxDepth += tokens[tokens.length - 1].depth;
  3536. }
  3537. }
  3538. state.slashes = slashes;
  3539. state.parts = parts;
  3540. }
  3541. return state;
  3542. };
  3543. var scan_1 = scan$1;
  3544. const constants$1 = constants$2;
  3545. const utils$1 = utils$3;
  3546. /**
  3547. * Constants
  3548. */
  3549. const {
  3550. MAX_LENGTH,
  3551. POSIX_REGEX_SOURCE,
  3552. REGEX_NON_SPECIAL_CHARS,
  3553. REGEX_SPECIAL_CHARS_BACKREF,
  3554. REPLACEMENTS
  3555. } = constants$1;
  3556. /**
  3557. * Helpers
  3558. */
  3559. const expandRange = (args, options) => {
  3560. if (typeof options.expandRange === 'function') {
  3561. return options.expandRange(...args, options);
  3562. }
  3563. args.sort();
  3564. const value = `[${args.join('-')}]`;
  3565. return value;
  3566. };
  3567. /**
  3568. * Create the message for a syntax error
  3569. */
  3570. const syntaxError = (type, char) => {
  3571. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  3572. };
  3573. /**
  3574. * Parse the given input string.
  3575. * @param {String} input
  3576. * @param {Object} options
  3577. * @return {Object}
  3578. */
  3579. const parse$2 = (input, options) => {
  3580. if (typeof input !== 'string') {
  3581. throw new TypeError('Expected a string');
  3582. }
  3583. input = REPLACEMENTS[input] || input;
  3584. const opts = { ...options };
  3585. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3586. let len = input.length;
  3587. if (len > max) {
  3588. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3589. }
  3590. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  3591. const tokens = [bos];
  3592. const capture = opts.capture ? '' : '?:';
  3593. const win32 = utils$1.isWindows(options);
  3594. // create constants based on platform, for windows or posix
  3595. const PLATFORM_CHARS = constants$1.globChars(win32);
  3596. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  3597. const {
  3598. DOT_LITERAL,
  3599. PLUS_LITERAL,
  3600. SLASH_LITERAL,
  3601. ONE_CHAR,
  3602. DOTS_SLASH,
  3603. NO_DOT,
  3604. NO_DOT_SLASH,
  3605. NO_DOTS_SLASH,
  3606. QMARK,
  3607. QMARK_NO_DOT,
  3608. STAR,
  3609. START_ANCHOR
  3610. } = PLATFORM_CHARS;
  3611. const globstar = opts => {
  3612. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3613. };
  3614. const nodot = opts.dot ? '' : NO_DOT;
  3615. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  3616. let star = opts.bash === true ? globstar(opts) : STAR;
  3617. if (opts.capture) {
  3618. star = `(${star})`;
  3619. }
  3620. // minimatch options support
  3621. if (typeof opts.noext === 'boolean') {
  3622. opts.noextglob = opts.noext;
  3623. }
  3624. const state = {
  3625. input,
  3626. index: -1,
  3627. start: 0,
  3628. dot: opts.dot === true,
  3629. consumed: '',
  3630. output: '',
  3631. prefix: '',
  3632. backtrack: false,
  3633. negated: false,
  3634. brackets: 0,
  3635. braces: 0,
  3636. parens: 0,
  3637. quotes: 0,
  3638. globstar: false,
  3639. tokens
  3640. };
  3641. input = utils$1.removePrefix(input, state);
  3642. len = input.length;
  3643. const extglobs = [];
  3644. const braces = [];
  3645. const stack = [];
  3646. let prev = bos;
  3647. let value;
  3648. /**
  3649. * Tokenizing helpers
  3650. */
  3651. const eos = () => state.index === len - 1;
  3652. const peek = state.peek = (n = 1) => input[state.index + n];
  3653. const advance = state.advance = () => input[++state.index] || '';
  3654. const remaining = () => input.slice(state.index + 1);
  3655. const consume = (value = '', num = 0) => {
  3656. state.consumed += value;
  3657. state.index += num;
  3658. };
  3659. const append = token => {
  3660. state.output += token.output != null ? token.output : token.value;
  3661. consume(token.value);
  3662. };
  3663. const negate = () => {
  3664. let count = 1;
  3665. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  3666. advance();
  3667. state.start++;
  3668. count++;
  3669. }
  3670. if (count % 2 === 0) {
  3671. return false;
  3672. }
  3673. state.negated = true;
  3674. state.start++;
  3675. return true;
  3676. };
  3677. const increment = type => {
  3678. state[type]++;
  3679. stack.push(type);
  3680. };
  3681. const decrement = type => {
  3682. state[type]--;
  3683. stack.pop();
  3684. };
  3685. /**
  3686. * Push tokens onto the tokens array. This helper speeds up
  3687. * tokenizing by 1) helping us avoid backtracking as much as possible,
  3688. * and 2) helping us avoid creating extra tokens when consecutive
  3689. * characters are plain text. This improves performance and simplifies
  3690. * lookbehinds.
  3691. */
  3692. const push = tok => {
  3693. if (prev.type === 'globstar') {
  3694. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  3695. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  3696. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  3697. state.output = state.output.slice(0, -prev.output.length);
  3698. prev.type = 'star';
  3699. prev.value = '*';
  3700. prev.output = star;
  3701. state.output += prev.output;
  3702. }
  3703. }
  3704. if (extglobs.length && tok.type !== 'paren') {
  3705. extglobs[extglobs.length - 1].inner += tok.value;
  3706. }
  3707. if (tok.value || tok.output) append(tok);
  3708. if (prev && prev.type === 'text' && tok.type === 'text') {
  3709. prev.value += tok.value;
  3710. prev.output = (prev.output || '') + tok.value;
  3711. return;
  3712. }
  3713. tok.prev = prev;
  3714. tokens.push(tok);
  3715. prev = tok;
  3716. };
  3717. const extglobOpen = (type, value) => {
  3718. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  3719. token.prev = prev;
  3720. token.parens = state.parens;
  3721. token.output = state.output;
  3722. const output = (opts.capture ? '(' : '') + token.open;
  3723. increment('parens');
  3724. push({ type, value, output: state.output ? '' : ONE_CHAR });
  3725. push({ type: 'paren', extglob: true, value: advance(), output });
  3726. extglobs.push(token);
  3727. };
  3728. const extglobClose = token => {
  3729. let output = token.close + (opts.capture ? ')' : '');
  3730. let rest;
  3731. if (token.type === 'negate') {
  3732. let extglobStar = star;
  3733. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  3734. extglobStar = globstar(opts);
  3735. }
  3736. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  3737. output = token.close = `)$))${extglobStar}`;
  3738. }
  3739. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  3740. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  3741. // In this case, we need to parse the string and use it in the output of the original pattern.
  3742. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  3743. //
  3744. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  3745. const expression = parse$2(rest, { ...options, fastpaths: false }).output;
  3746. output = token.close = `)${expression})${extglobStar})`;
  3747. }
  3748. if (token.prev.type === 'bos') {
  3749. state.negatedExtglob = true;
  3750. }
  3751. }
  3752. push({ type: 'paren', extglob: true, value, output });
  3753. decrement('parens');
  3754. };
  3755. /**
  3756. * Fast paths
  3757. */
  3758. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  3759. let backslashes = false;
  3760. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  3761. if (first === '\\') {
  3762. backslashes = true;
  3763. return m;
  3764. }
  3765. if (first === '?') {
  3766. if (esc) {
  3767. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  3768. }
  3769. if (index === 0) {
  3770. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  3771. }
  3772. return QMARK.repeat(chars.length);
  3773. }
  3774. if (first === '.') {
  3775. return DOT_LITERAL.repeat(chars.length);
  3776. }
  3777. if (first === '*') {
  3778. if (esc) {
  3779. return esc + first + (rest ? star : '');
  3780. }
  3781. return star;
  3782. }
  3783. return esc ? m : `\\${m}`;
  3784. });
  3785. if (backslashes === true) {
  3786. if (opts.unescape === true) {
  3787. output = output.replace(/\\/g, '');
  3788. } else {
  3789. output = output.replace(/\\+/g, m => {
  3790. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  3791. });
  3792. }
  3793. }
  3794. if (output === input && opts.contains === true) {
  3795. state.output = input;
  3796. return state;
  3797. }
  3798. state.output = utils$1.wrapOutput(output, state, options);
  3799. return state;
  3800. }
  3801. /**
  3802. * Tokenize input until we reach end-of-string
  3803. */
  3804. while (!eos()) {
  3805. value = advance();
  3806. if (value === '\u0000') {
  3807. continue;
  3808. }
  3809. /**
  3810. * Escaped characters
  3811. */
  3812. if (value === '\\') {
  3813. const next = peek();
  3814. if (next === '/' && opts.bash !== true) {
  3815. continue;
  3816. }
  3817. if (next === '.' || next === ';') {
  3818. continue;
  3819. }
  3820. if (!next) {
  3821. value += '\\';
  3822. push({ type: 'text', value });
  3823. continue;
  3824. }
  3825. // collapse slashes to reduce potential for exploits
  3826. const match = /^\\+/.exec(remaining());
  3827. let slashes = 0;
  3828. if (match && match[0].length > 2) {
  3829. slashes = match[0].length;
  3830. state.index += slashes;
  3831. if (slashes % 2 !== 0) {
  3832. value += '\\';
  3833. }
  3834. }
  3835. if (opts.unescape === true) {
  3836. value = advance();
  3837. } else {
  3838. value += advance();
  3839. }
  3840. if (state.brackets === 0) {
  3841. push({ type: 'text', value });
  3842. continue;
  3843. }
  3844. }
  3845. /**
  3846. * If we're inside a regex character class, continue
  3847. * until we reach the closing bracket.
  3848. */
  3849. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  3850. if (opts.posix !== false && value === ':') {
  3851. const inner = prev.value.slice(1);
  3852. if (inner.includes('[')) {
  3853. prev.posix = true;
  3854. if (inner.includes(':')) {
  3855. const idx = prev.value.lastIndexOf('[');
  3856. const pre = prev.value.slice(0, idx);
  3857. const rest = prev.value.slice(idx + 2);
  3858. const posix = POSIX_REGEX_SOURCE[rest];
  3859. if (posix) {
  3860. prev.value = pre + posix;
  3861. state.backtrack = true;
  3862. advance();
  3863. if (!bos.output && tokens.indexOf(prev) === 1) {
  3864. bos.output = ONE_CHAR;
  3865. }
  3866. continue;
  3867. }
  3868. }
  3869. }
  3870. }
  3871. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  3872. value = `\\${value}`;
  3873. }
  3874. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  3875. value = `\\${value}`;
  3876. }
  3877. if (opts.posix === true && value === '!' && prev.value === '[') {
  3878. value = '^';
  3879. }
  3880. prev.value += value;
  3881. append({ value });
  3882. continue;
  3883. }
  3884. /**
  3885. * If we're inside a quoted string, continue
  3886. * until we reach the closing double quote.
  3887. */
  3888. if (state.quotes === 1 && value !== '"') {
  3889. value = utils$1.escapeRegex(value);
  3890. prev.value += value;
  3891. append({ value });
  3892. continue;
  3893. }
  3894. /**
  3895. * Double quotes
  3896. */
  3897. if (value === '"') {
  3898. state.quotes = state.quotes === 1 ? 0 : 1;
  3899. if (opts.keepQuotes === true) {
  3900. push({ type: 'text', value });
  3901. }
  3902. continue;
  3903. }
  3904. /**
  3905. * Parentheses
  3906. */
  3907. if (value === '(') {
  3908. increment('parens');
  3909. push({ type: 'paren', value });
  3910. continue;
  3911. }
  3912. if (value === ')') {
  3913. if (state.parens === 0 && opts.strictBrackets === true) {
  3914. throw new SyntaxError(syntaxError('opening', '('));
  3915. }
  3916. const extglob = extglobs[extglobs.length - 1];
  3917. if (extglob && state.parens === extglob.parens + 1) {
  3918. extglobClose(extglobs.pop());
  3919. continue;
  3920. }
  3921. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  3922. decrement('parens');
  3923. continue;
  3924. }
  3925. /**
  3926. * Square brackets
  3927. */
  3928. if (value === '[') {
  3929. if (opts.nobracket === true || !remaining().includes(']')) {
  3930. if (opts.nobracket !== true && opts.strictBrackets === true) {
  3931. throw new SyntaxError(syntaxError('closing', ']'));
  3932. }
  3933. value = `\\${value}`;
  3934. } else {
  3935. increment('brackets');
  3936. }
  3937. push({ type: 'bracket', value });
  3938. continue;
  3939. }
  3940. if (value === ']') {
  3941. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  3942. push({ type: 'text', value, output: `\\${value}` });
  3943. continue;
  3944. }
  3945. if (state.brackets === 0) {
  3946. if (opts.strictBrackets === true) {
  3947. throw new SyntaxError(syntaxError('opening', '['));
  3948. }
  3949. push({ type: 'text', value, output: `\\${value}` });
  3950. continue;
  3951. }
  3952. decrement('brackets');
  3953. const prevValue = prev.value.slice(1);
  3954. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  3955. value = `/${value}`;
  3956. }
  3957. prev.value += value;
  3958. append({ value });
  3959. // when literal brackets are explicitly disabled
  3960. // assume we should match with a regex character class
  3961. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  3962. continue;
  3963. }
  3964. const escaped = utils$1.escapeRegex(prev.value);
  3965. state.output = state.output.slice(0, -prev.value.length);
  3966. // when literal brackets are explicitly enabled
  3967. // assume we should escape the brackets to match literal characters
  3968. if (opts.literalBrackets === true) {
  3969. state.output += escaped;
  3970. prev.value = escaped;
  3971. continue;
  3972. }
  3973. // when the user specifies nothing, try to match both
  3974. prev.value = `(${capture}${escaped}|${prev.value})`;
  3975. state.output += prev.value;
  3976. continue;
  3977. }
  3978. /**
  3979. * Braces
  3980. */
  3981. if (value === '{' && opts.nobrace !== true) {
  3982. increment('braces');
  3983. const open = {
  3984. type: 'brace',
  3985. value,
  3986. output: '(',
  3987. outputIndex: state.output.length,
  3988. tokensIndex: state.tokens.length
  3989. };
  3990. braces.push(open);
  3991. push(open);
  3992. continue;
  3993. }
  3994. if (value === '}') {
  3995. const brace = braces[braces.length - 1];
  3996. if (opts.nobrace === true || !brace) {
  3997. push({ type: 'text', value, output: value });
  3998. continue;
  3999. }
  4000. let output = ')';
  4001. if (brace.dots === true) {
  4002. const arr = tokens.slice();
  4003. const range = [];
  4004. for (let i = arr.length - 1; i >= 0; i--) {
  4005. tokens.pop();
  4006. if (arr[i].type === 'brace') {
  4007. break;
  4008. }
  4009. if (arr[i].type !== 'dots') {
  4010. range.unshift(arr[i].value);
  4011. }
  4012. }
  4013. output = expandRange(range, opts);
  4014. state.backtrack = true;
  4015. }
  4016. if (brace.comma !== true && brace.dots !== true) {
  4017. const out = state.output.slice(0, brace.outputIndex);
  4018. const toks = state.tokens.slice(brace.tokensIndex);
  4019. brace.value = brace.output = '\\{';
  4020. value = output = '\\}';
  4021. state.output = out;
  4022. for (const t of toks) {
  4023. state.output += (t.output || t.value);
  4024. }
  4025. }
  4026. push({ type: 'brace', value, output });
  4027. decrement('braces');
  4028. braces.pop();
  4029. continue;
  4030. }
  4031. /**
  4032. * Pipes
  4033. */
  4034. if (value === '|') {
  4035. if (extglobs.length > 0) {
  4036. extglobs[extglobs.length - 1].conditions++;
  4037. }
  4038. push({ type: 'text', value });
  4039. continue;
  4040. }
  4041. /**
  4042. * Commas
  4043. */
  4044. if (value === ',') {
  4045. let output = value;
  4046. const brace = braces[braces.length - 1];
  4047. if (brace && stack[stack.length - 1] === 'braces') {
  4048. brace.comma = true;
  4049. output = '|';
  4050. }
  4051. push({ type: 'comma', value, output });
  4052. continue;
  4053. }
  4054. /**
  4055. * Slashes
  4056. */
  4057. if (value === '/') {
  4058. // if the beginning of the glob is "./", advance the start
  4059. // to the current index, and don't add the "./" characters
  4060. // to the state. This greatly simplifies lookbehinds when
  4061. // checking for BOS characters like "!" and "." (not "./")
  4062. if (prev.type === 'dot' && state.index === state.start + 1) {
  4063. state.start = state.index + 1;
  4064. state.consumed = '';
  4065. state.output = '';
  4066. tokens.pop();
  4067. prev = bos; // reset "prev" to the first token
  4068. continue;
  4069. }
  4070. push({ type: 'slash', value, output: SLASH_LITERAL });
  4071. continue;
  4072. }
  4073. /**
  4074. * Dots
  4075. */
  4076. if (value === '.') {
  4077. if (state.braces > 0 && prev.type === 'dot') {
  4078. if (prev.value === '.') prev.output = DOT_LITERAL;
  4079. const brace = braces[braces.length - 1];
  4080. prev.type = 'dots';
  4081. prev.output += value;
  4082. prev.value += value;
  4083. brace.dots = true;
  4084. continue;
  4085. }
  4086. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  4087. push({ type: 'text', value, output: DOT_LITERAL });
  4088. continue;
  4089. }
  4090. push({ type: 'dot', value, output: DOT_LITERAL });
  4091. continue;
  4092. }
  4093. /**
  4094. * Question marks
  4095. */
  4096. if (value === '?') {
  4097. const isGroup = prev && prev.value === '(';
  4098. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  4099. extglobOpen('qmark', value);
  4100. continue;
  4101. }
  4102. if (prev && prev.type === 'paren') {
  4103. const next = peek();
  4104. let output = value;
  4105. if (next === '<' && !utils$1.supportsLookbehinds()) {
  4106. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  4107. }
  4108. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  4109. output = `\\${value}`;
  4110. }
  4111. push({ type: 'text', value, output });
  4112. continue;
  4113. }
  4114. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  4115. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  4116. continue;
  4117. }
  4118. push({ type: 'qmark', value, output: QMARK });
  4119. continue;
  4120. }
  4121. /**
  4122. * Exclamation
  4123. */
  4124. if (value === '!') {
  4125. if (opts.noextglob !== true && peek() === '(') {
  4126. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  4127. extglobOpen('negate', value);
  4128. continue;
  4129. }
  4130. }
  4131. if (opts.nonegate !== true && state.index === 0) {
  4132. negate();
  4133. continue;
  4134. }
  4135. }
  4136. /**
  4137. * Plus
  4138. */
  4139. if (value === '+') {
  4140. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  4141. extglobOpen('plus', value);
  4142. continue;
  4143. }
  4144. if ((prev && prev.value === '(') || opts.regex === false) {
  4145. push({ type: 'plus', value, output: PLUS_LITERAL });
  4146. continue;
  4147. }
  4148. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  4149. push({ type: 'plus', value });
  4150. continue;
  4151. }
  4152. push({ type: 'plus', value: PLUS_LITERAL });
  4153. continue;
  4154. }
  4155. /**
  4156. * Plain text
  4157. */
  4158. if (value === '@') {
  4159. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  4160. push({ type: 'at', extglob: true, value, output: '' });
  4161. continue;
  4162. }
  4163. push({ type: 'text', value });
  4164. continue;
  4165. }
  4166. /**
  4167. * Plain text
  4168. */
  4169. if (value !== '*') {
  4170. if (value === '$' || value === '^') {
  4171. value = `\\${value}`;
  4172. }
  4173. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  4174. if (match) {
  4175. value += match[0];
  4176. state.index += match[0].length;
  4177. }
  4178. push({ type: 'text', value });
  4179. continue;
  4180. }
  4181. /**
  4182. * Stars
  4183. */
  4184. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  4185. prev.type = 'star';
  4186. prev.star = true;
  4187. prev.value += value;
  4188. prev.output = star;
  4189. state.backtrack = true;
  4190. state.globstar = true;
  4191. consume(value);
  4192. continue;
  4193. }
  4194. let rest = remaining();
  4195. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  4196. extglobOpen('star', value);
  4197. continue;
  4198. }
  4199. if (prev.type === 'star') {
  4200. if (opts.noglobstar === true) {
  4201. consume(value);
  4202. continue;
  4203. }
  4204. const prior = prev.prev;
  4205. const before = prior.prev;
  4206. const isStart = prior.type === 'slash' || prior.type === 'bos';
  4207. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  4208. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  4209. push({ type: 'star', value, output: '' });
  4210. continue;
  4211. }
  4212. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  4213. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  4214. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  4215. push({ type: 'star', value, output: '' });
  4216. continue;
  4217. }
  4218. // strip consecutive `/**/`
  4219. while (rest.slice(0, 3) === '/**') {
  4220. const after = input[state.index + 4];
  4221. if (after && after !== '/') {
  4222. break;
  4223. }
  4224. rest = rest.slice(3);
  4225. consume('/**', 3);
  4226. }
  4227. if (prior.type === 'bos' && eos()) {
  4228. prev.type = 'globstar';
  4229. prev.value += value;
  4230. prev.output = globstar(opts);
  4231. state.output = prev.output;
  4232. state.globstar = true;
  4233. consume(value);
  4234. continue;
  4235. }
  4236. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  4237. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  4238. prior.output = `(?:${prior.output}`;
  4239. prev.type = 'globstar';
  4240. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  4241. prev.value += value;
  4242. state.globstar = true;
  4243. state.output += prior.output + prev.output;
  4244. consume(value);
  4245. continue;
  4246. }
  4247. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  4248. const end = rest[1] !== void 0 ? '|$' : '';
  4249. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  4250. prior.output = `(?:${prior.output}`;
  4251. prev.type = 'globstar';
  4252. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  4253. prev.value += value;
  4254. state.output += prior.output + prev.output;
  4255. state.globstar = true;
  4256. consume(value + advance());
  4257. push({ type: 'slash', value: '/', output: '' });
  4258. continue;
  4259. }
  4260. if (prior.type === 'bos' && rest[0] === '/') {
  4261. prev.type = 'globstar';
  4262. prev.value += value;
  4263. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  4264. state.output = prev.output;
  4265. state.globstar = true;
  4266. consume(value + advance());
  4267. push({ type: 'slash', value: '/', output: '' });
  4268. continue;
  4269. }
  4270. // remove single star from output
  4271. state.output = state.output.slice(0, -prev.output.length);
  4272. // reset previous token to globstar
  4273. prev.type = 'globstar';
  4274. prev.output = globstar(opts);
  4275. prev.value += value;
  4276. // reset output with globstar
  4277. state.output += prev.output;
  4278. state.globstar = true;
  4279. consume(value);
  4280. continue;
  4281. }
  4282. const token = { type: 'star', value, output: star };
  4283. if (opts.bash === true) {
  4284. token.output = '.*?';
  4285. if (prev.type === 'bos' || prev.type === 'slash') {
  4286. token.output = nodot + token.output;
  4287. }
  4288. push(token);
  4289. continue;
  4290. }
  4291. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  4292. token.output = value;
  4293. push(token);
  4294. continue;
  4295. }
  4296. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  4297. if (prev.type === 'dot') {
  4298. state.output += NO_DOT_SLASH;
  4299. prev.output += NO_DOT_SLASH;
  4300. } else if (opts.dot === true) {
  4301. state.output += NO_DOTS_SLASH;
  4302. prev.output += NO_DOTS_SLASH;
  4303. } else {
  4304. state.output += nodot;
  4305. prev.output += nodot;
  4306. }
  4307. if (peek() !== '*') {
  4308. state.output += ONE_CHAR;
  4309. prev.output += ONE_CHAR;
  4310. }
  4311. }
  4312. push(token);
  4313. }
  4314. while (state.brackets > 0) {
  4315. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  4316. state.output = utils$1.escapeLast(state.output, '[');
  4317. decrement('brackets');
  4318. }
  4319. while (state.parens > 0) {
  4320. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  4321. state.output = utils$1.escapeLast(state.output, '(');
  4322. decrement('parens');
  4323. }
  4324. while (state.braces > 0) {
  4325. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  4326. state.output = utils$1.escapeLast(state.output, '{');
  4327. decrement('braces');
  4328. }
  4329. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  4330. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  4331. }
  4332. // rebuild the output if we had to backtrack at any point
  4333. if (state.backtrack === true) {
  4334. state.output = '';
  4335. for (const token of state.tokens) {
  4336. state.output += token.output != null ? token.output : token.value;
  4337. if (token.suffix) {
  4338. state.output += token.suffix;
  4339. }
  4340. }
  4341. }
  4342. return state;
  4343. };
  4344. /**
  4345. * Fast paths for creating regular expressions for common glob patterns.
  4346. * This can significantly speed up processing and has very little downside
  4347. * impact when none of the fast paths match.
  4348. */
  4349. parse$2.fastpaths = (input, options) => {
  4350. const opts = { ...options };
  4351. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  4352. const len = input.length;
  4353. if (len > max) {
  4354. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  4355. }
  4356. input = REPLACEMENTS[input] || input;
  4357. const win32 = utils$1.isWindows(options);
  4358. // create constants based on platform, for windows or posix
  4359. const {
  4360. DOT_LITERAL,
  4361. SLASH_LITERAL,
  4362. ONE_CHAR,
  4363. DOTS_SLASH,
  4364. NO_DOT,
  4365. NO_DOTS,
  4366. NO_DOTS_SLASH,
  4367. STAR,
  4368. START_ANCHOR
  4369. } = constants$1.globChars(win32);
  4370. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  4371. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  4372. const capture = opts.capture ? '' : '?:';
  4373. const state = { negated: false, prefix: '' };
  4374. let star = opts.bash === true ? '.*?' : STAR;
  4375. if (opts.capture) {
  4376. star = `(${star})`;
  4377. }
  4378. const globstar = opts => {
  4379. if (opts.noglobstar === true) return star;
  4380. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  4381. };
  4382. const create = str => {
  4383. switch (str) {
  4384. case '*':
  4385. return `${nodot}${ONE_CHAR}${star}`;
  4386. case '.*':
  4387. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  4388. case '*.*':
  4389. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  4390. case '*/*':
  4391. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  4392. case '**':
  4393. return nodot + globstar(opts);
  4394. case '**/*':
  4395. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  4396. case '**/*.*':
  4397. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  4398. case '**/.*':
  4399. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  4400. default: {
  4401. const match = /^(.*?)\.(\w+)$/.exec(str);
  4402. if (!match) return;
  4403. const source = create(match[1]);
  4404. if (!source) return;
  4405. return source + DOT_LITERAL + match[2];
  4406. }
  4407. }
  4408. };
  4409. const output = utils$1.removePrefix(input, state);
  4410. let source = create(output);
  4411. if (source && opts.strictSlashes !== true) {
  4412. source += `${SLASH_LITERAL}?`;
  4413. }
  4414. return source;
  4415. };
  4416. var parse_1 = parse$2;
  4417. const path = require$$0$1;
  4418. const scan = scan_1;
  4419. const parse$1 = parse_1;
  4420. const utils = utils$3;
  4421. const constants = constants$2;
  4422. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  4423. /**
  4424. * Creates a matcher function from one or more glob patterns. The
  4425. * returned function takes a string to match as its first argument,
  4426. * and returns true if the string is a match. The returned matcher
  4427. * function also takes a boolean as the second argument that, when true,
  4428. * returns an object with additional information.
  4429. *
  4430. * ```js
  4431. * const picomatch = require('picomatch');
  4432. * // picomatch(glob[, options]);
  4433. *
  4434. * const isMatch = picomatch('*.!(*a)');
  4435. * console.log(isMatch('a.a')); //=> false
  4436. * console.log(isMatch('a.b')); //=> true
  4437. * ```
  4438. * @name picomatch
  4439. * @param {String|Array} `globs` One or more glob patterns.
  4440. * @param {Object=} `options`
  4441. * @return {Function=} Returns a matcher function.
  4442. * @api public
  4443. */
  4444. const picomatch = (glob, options, returnState = false) => {
  4445. if (Array.isArray(glob)) {
  4446. const fns = glob.map(input => picomatch(input, options, returnState));
  4447. const arrayMatcher = str => {
  4448. for (const isMatch of fns) {
  4449. const state = isMatch(str);
  4450. if (state) return state;
  4451. }
  4452. return false;
  4453. };
  4454. return arrayMatcher;
  4455. }
  4456. const isState = isObject(glob) && glob.tokens && glob.input;
  4457. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  4458. throw new TypeError('Expected pattern to be a non-empty string');
  4459. }
  4460. const opts = options || {};
  4461. const posix = utils.isWindows(options);
  4462. const regex = isState
  4463. ? picomatch.compileRe(glob, options)
  4464. : picomatch.makeRe(glob, options, false, true);
  4465. const state = regex.state;
  4466. delete regex.state;
  4467. let isIgnored = () => false;
  4468. if (opts.ignore) {
  4469. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  4470. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  4471. }
  4472. const matcher = (input, returnObject = false) => {
  4473. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  4474. const result = { glob, state, regex, posix, input, output, match, isMatch };
  4475. if (typeof opts.onResult === 'function') {
  4476. opts.onResult(result);
  4477. }
  4478. if (isMatch === false) {
  4479. result.isMatch = false;
  4480. return returnObject ? result : false;
  4481. }
  4482. if (isIgnored(input)) {
  4483. if (typeof opts.onIgnore === 'function') {
  4484. opts.onIgnore(result);
  4485. }
  4486. result.isMatch = false;
  4487. return returnObject ? result : false;
  4488. }
  4489. if (typeof opts.onMatch === 'function') {
  4490. opts.onMatch(result);
  4491. }
  4492. return returnObject ? result : true;
  4493. };
  4494. if (returnState) {
  4495. matcher.state = state;
  4496. }
  4497. return matcher;
  4498. };
  4499. /**
  4500. * Test `input` with the given `regex`. This is used by the main
  4501. * `picomatch()` function to test the input string.
  4502. *
  4503. * ```js
  4504. * const picomatch = require('picomatch');
  4505. * // picomatch.test(input, regex[, options]);
  4506. *
  4507. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  4508. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  4509. * ```
  4510. * @param {String} `input` String to test.
  4511. * @param {RegExp} `regex`
  4512. * @return {Object} Returns an object with matching info.
  4513. * @api public
  4514. */
  4515. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  4516. if (typeof input !== 'string') {
  4517. throw new TypeError('Expected input to be a string');
  4518. }
  4519. if (input === '') {
  4520. return { isMatch: false, output: '' };
  4521. }
  4522. const opts = options || {};
  4523. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  4524. let match = input === glob;
  4525. let output = (match && format) ? format(input) : input;
  4526. if (match === false) {
  4527. output = format ? format(input) : input;
  4528. match = output === glob;
  4529. }
  4530. if (match === false || opts.capture === true) {
  4531. if (opts.matchBase === true || opts.basename === true) {
  4532. match = picomatch.matchBase(input, regex, options, posix);
  4533. } else {
  4534. match = regex.exec(output);
  4535. }
  4536. }
  4537. return { isMatch: Boolean(match), match, output };
  4538. };
  4539. /**
  4540. * Match the basename of a filepath.
  4541. *
  4542. * ```js
  4543. * const picomatch = require('picomatch');
  4544. * // picomatch.matchBase(input, glob[, options]);
  4545. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  4546. * ```
  4547. * @param {String} `input` String to test.
  4548. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  4549. * @return {Boolean}
  4550. * @api public
  4551. */
  4552. picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  4553. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  4554. return regex.test(path.basename(input));
  4555. };
  4556. /**
  4557. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  4558. *
  4559. * ```js
  4560. * const picomatch = require('picomatch');
  4561. * // picomatch.isMatch(string, patterns[, options]);
  4562. *
  4563. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  4564. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  4565. * ```
  4566. * @param {String|Array} str The string to test.
  4567. * @param {String|Array} patterns One or more glob patterns to use for matching.
  4568. * @param {Object} [options] See available [options](#options).
  4569. * @return {Boolean} Returns true if any patterns match `str`
  4570. * @api public
  4571. */
  4572. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  4573. /**
  4574. * Parse a glob pattern to create the source string for a regular
  4575. * expression.
  4576. *
  4577. * ```js
  4578. * const picomatch = require('picomatch');
  4579. * const result = picomatch.parse(pattern[, options]);
  4580. * ```
  4581. * @param {String} `pattern`
  4582. * @param {Object} `options`
  4583. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  4584. * @api public
  4585. */
  4586. picomatch.parse = (pattern, options) => {
  4587. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  4588. return parse$1(pattern, { ...options, fastpaths: false });
  4589. };
  4590. /**
  4591. * Scan a glob pattern to separate the pattern into segments.
  4592. *
  4593. * ```js
  4594. * const picomatch = require('picomatch');
  4595. * // picomatch.scan(input[, options]);
  4596. *
  4597. * const result = picomatch.scan('!./foo/*.js');
  4598. * console.log(result);
  4599. * { prefix: '!./',
  4600. * input: '!./foo/*.js',
  4601. * start: 3,
  4602. * base: 'foo',
  4603. * glob: '*.js',
  4604. * isBrace: false,
  4605. * isBracket: false,
  4606. * isGlob: true,
  4607. * isExtglob: false,
  4608. * isGlobstar: false,
  4609. * negated: true }
  4610. * ```
  4611. * @param {String} `input` Glob pattern to scan.
  4612. * @param {Object} `options`
  4613. * @return {Object} Returns an object with
  4614. * @api public
  4615. */
  4616. picomatch.scan = (input, options) => scan(input, options);
  4617. /**
  4618. * Compile a regular expression from the `state` object returned by the
  4619. * [parse()](#parse) method.
  4620. *
  4621. * @param {Object} `state`
  4622. * @param {Object} `options`
  4623. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  4624. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  4625. * @return {RegExp}
  4626. * @api public
  4627. */
  4628. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  4629. if (returnOutput === true) {
  4630. return state.output;
  4631. }
  4632. const opts = options || {};
  4633. const prepend = opts.contains ? '' : '^';
  4634. const append = opts.contains ? '' : '$';
  4635. let source = `${prepend}(?:${state.output})${append}`;
  4636. if (state && state.negated === true) {
  4637. source = `^(?!${source}).*$`;
  4638. }
  4639. const regex = picomatch.toRegex(source, options);
  4640. if (returnState === true) {
  4641. regex.state = state;
  4642. }
  4643. return regex;
  4644. };
  4645. /**
  4646. * Create a regular expression from a parsed glob pattern.
  4647. *
  4648. * ```js
  4649. * const picomatch = require('picomatch');
  4650. * const state = picomatch.parse('*.js');
  4651. * // picomatch.compileRe(state[, options]);
  4652. *
  4653. * console.log(picomatch.compileRe(state));
  4654. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  4655. * ```
  4656. * @param {String} `state` The object returned from the `.parse` method.
  4657. * @param {Object} `options`
  4658. * @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.
  4659. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  4660. * @return {RegExp} Returns a regex created from the given pattern.
  4661. * @api public
  4662. */
  4663. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  4664. if (!input || typeof input !== 'string') {
  4665. throw new TypeError('Expected a non-empty string');
  4666. }
  4667. let parsed = { negated: false, fastpaths: true };
  4668. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  4669. parsed.output = parse$1.fastpaths(input, options);
  4670. }
  4671. if (!parsed.output) {
  4672. parsed = parse$1(input, options);
  4673. }
  4674. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  4675. };
  4676. /**
  4677. * Create a regular expression from the given regex source string.
  4678. *
  4679. * ```js
  4680. * const picomatch = require('picomatch');
  4681. * // picomatch.toRegex(source[, options]);
  4682. *
  4683. * const { output } = picomatch.parse('*.js');
  4684. * console.log(picomatch.toRegex(output));
  4685. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  4686. * ```
  4687. * @param {String} `source` Regular expression source string.
  4688. * @param {Object} `options`
  4689. * @return {RegExp}
  4690. * @api public
  4691. */
  4692. picomatch.toRegex = (source, options) => {
  4693. try {
  4694. const opts = options || {};
  4695. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  4696. } catch (err) {
  4697. if (options && options.debug === true) throw err;
  4698. return /$^/;
  4699. }
  4700. };
  4701. /**
  4702. * Picomatch constants.
  4703. * @return {Object}
  4704. */
  4705. picomatch.constants = constants;
  4706. /**
  4707. * Expose "picomatch"
  4708. */
  4709. var picomatch_1 = picomatch;
  4710. (function (module) {
  4711. module.exports = picomatch_1;
  4712. } (picomatch$1));
  4713. const pm = /*@__PURE__*/getDefaultExportFromCjs(exports.picomatchExports);
  4714. const extractors = {
  4715. ArrayPattern(names, param) {
  4716. for (const element of param.elements) {
  4717. if (element)
  4718. extractors[element.type](names, element);
  4719. }
  4720. },
  4721. AssignmentPattern(names, param) {
  4722. extractors[param.left.type](names, param.left);
  4723. },
  4724. Identifier(names, param) {
  4725. names.push(param.name);
  4726. },
  4727. MemberExpression() { },
  4728. ObjectPattern(names, param) {
  4729. for (const prop of param.properties) {
  4730. // @ts-ignore Typescript reports that this is not a valid type
  4731. if (prop.type === 'RestElement') {
  4732. extractors.RestElement(names, prop);
  4733. }
  4734. else {
  4735. extractors[prop.value.type](names, prop.value);
  4736. }
  4737. }
  4738. },
  4739. RestElement(names, param) {
  4740. extractors[param.argument.type](names, param.argument);
  4741. }
  4742. };
  4743. const extractAssignedNames = function extractAssignedNames(param) {
  4744. const names = [];
  4745. extractors[param.type](names, param);
  4746. return names;
  4747. };
  4748. // Helper since Typescript can't detect readonly arrays with Array.isArray
  4749. function isArray$1(arg) {
  4750. return Array.isArray(arg);
  4751. }
  4752. function ensureArray(thing) {
  4753. if (isArray$1(thing))
  4754. return thing;
  4755. if (thing == null)
  4756. return [];
  4757. return [thing];
  4758. }
  4759. const normalizePath = function normalizePath(filename) {
  4760. return filename.split(require$$0$1.win32.sep).join(require$$0$1.posix.sep);
  4761. };
  4762. function getMatcherString(id, resolutionBase) {
  4763. if (resolutionBase === false || require$$0$1.isAbsolute(id) || id.startsWith('*')) {
  4764. return normalizePath(id);
  4765. }
  4766. // resolve('') is valid and will default to process.cwd()
  4767. const basePath = normalizePath(require$$0$1.resolve(resolutionBase || ''))
  4768. // escape all possible (posix + win) path characters that might interfere with regex
  4769. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  4770. // Note that we use posix.join because:
  4771. // 1. the basePath has been normalized to use /
  4772. // 2. the incoming glob (id) matcher, also uses /
  4773. // otherwise Node will force backslash (\) on windows
  4774. return require$$0$1.posix.join(basePath, normalizePath(id));
  4775. }
  4776. const createFilter = function createFilter(include, exclude, options) {
  4777. const resolutionBase = options && options.resolve;
  4778. const getMatcher = (id) => id instanceof RegExp
  4779. ? id
  4780. : {
  4781. test: (what) => {
  4782. // this refactor is a tad overly verbose but makes for easy debugging
  4783. const pattern = getMatcherString(id, resolutionBase);
  4784. const fn = pm(pattern, { dot: true });
  4785. const result = fn(what);
  4786. return result;
  4787. }
  4788. };
  4789. const includeMatchers = ensureArray(include).map(getMatcher);
  4790. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  4791. return function result(id) {
  4792. if (typeof id !== 'string')
  4793. return false;
  4794. if (/\0/.test(id))
  4795. return false;
  4796. const pathId = normalizePath(id);
  4797. for (let i = 0; i < excludeMatchers.length; ++i) {
  4798. const matcher = excludeMatchers[i];
  4799. if (matcher.test(pathId))
  4800. return false;
  4801. }
  4802. for (let i = 0; i < includeMatchers.length; ++i) {
  4803. const matcher = includeMatchers[i];
  4804. if (matcher.test(pathId))
  4805. return true;
  4806. }
  4807. return !includeMatchers.length;
  4808. };
  4809. };
  4810. const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
  4811. 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';
  4812. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins}`.split(' '));
  4813. forbiddenIdentifiers.add('');
  4814. const BROKEN_FLOW_NONE = 0;
  4815. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  4816. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  4817. function createInclusionContext() {
  4818. return {
  4819. brokenFlow: BROKEN_FLOW_NONE,
  4820. includedCallArguments: new Set(),
  4821. includedLabels: new Set()
  4822. };
  4823. }
  4824. function createHasEffectsContext() {
  4825. return {
  4826. accessed: new PathTracker(),
  4827. assigned: new PathTracker(),
  4828. brokenFlow: BROKEN_FLOW_NONE,
  4829. called: new DiscriminatedPathTracker(),
  4830. ignore: {
  4831. breaks: false,
  4832. continues: false,
  4833. labels: new Set(),
  4834. returnYield: false,
  4835. this: false
  4836. },
  4837. includedLabels: new Set(),
  4838. instantiated: new DiscriminatedPathTracker(),
  4839. replacedVariableInits: new Map()
  4840. };
  4841. }
  4842. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  4843. return Object.create(inheritedDescriptions, memberDescriptions);
  4844. }
  4845. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  4846. getLiteralValueAtPath() {
  4847. return undefined;
  4848. }
  4849. })();
  4850. const returnsUnknown = {
  4851. value: {
  4852. hasEffectsWhenCalled: null,
  4853. returns: UNKNOWN_EXPRESSION
  4854. }
  4855. };
  4856. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  4857. getReturnExpressionWhenCalledAtPath(path) {
  4858. if (path.length === 1) {
  4859. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  4860. }
  4861. return UNKNOWN_RETURN_EXPRESSION;
  4862. }
  4863. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4864. if (interaction.type === INTERACTION_ACCESSED) {
  4865. return path.length > 1;
  4866. }
  4867. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4868. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  4869. }
  4870. return true;
  4871. }
  4872. })();
  4873. const returnsBoolean = {
  4874. value: {
  4875. hasEffectsWhenCalled: null,
  4876. returns: UNKNOWN_LITERAL_BOOLEAN
  4877. }
  4878. };
  4879. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  4880. getReturnExpressionWhenCalledAtPath(path) {
  4881. if (path.length === 1) {
  4882. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  4883. }
  4884. return UNKNOWN_RETURN_EXPRESSION;
  4885. }
  4886. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4887. if (interaction.type === INTERACTION_ACCESSED) {
  4888. return path.length > 1;
  4889. }
  4890. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4891. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  4892. }
  4893. return true;
  4894. }
  4895. })();
  4896. const returnsNumber = {
  4897. value: {
  4898. hasEffectsWhenCalled: null,
  4899. returns: UNKNOWN_LITERAL_NUMBER
  4900. }
  4901. };
  4902. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  4903. getReturnExpressionWhenCalledAtPath(path) {
  4904. if (path.length === 1) {
  4905. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  4906. }
  4907. return UNKNOWN_RETURN_EXPRESSION;
  4908. }
  4909. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4910. if (interaction.type === INTERACTION_ACCESSED) {
  4911. return path.length > 1;
  4912. }
  4913. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4914. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  4915. }
  4916. return true;
  4917. }
  4918. })();
  4919. const returnsString = {
  4920. value: {
  4921. hasEffectsWhenCalled: null,
  4922. returns: UNKNOWN_LITERAL_STRING
  4923. }
  4924. };
  4925. const stringReplace = {
  4926. value: {
  4927. hasEffectsWhenCalled({ args }, context) {
  4928. const argument1 = args[1];
  4929. return (args.length < 2 ||
  4930. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  4931. deoptimizeCache() { }
  4932. }) === 'symbol' &&
  4933. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  4934. },
  4935. returns: UNKNOWN_LITERAL_STRING
  4936. }
  4937. };
  4938. const objectMembers = assembleMemberDescriptions({
  4939. hasOwnProperty: returnsBoolean,
  4940. isPrototypeOf: returnsBoolean,
  4941. propertyIsEnumerable: returnsBoolean,
  4942. toLocaleString: returnsString,
  4943. toString: returnsString,
  4944. valueOf: returnsUnknown
  4945. });
  4946. const literalBooleanMembers = assembleMemberDescriptions({
  4947. valueOf: returnsBoolean
  4948. }, objectMembers);
  4949. const literalNumberMembers = assembleMemberDescriptions({
  4950. toExponential: returnsString,
  4951. toFixed: returnsString,
  4952. toLocaleString: returnsString,
  4953. toPrecision: returnsString,
  4954. valueOf: returnsNumber
  4955. }, objectMembers);
  4956. /**
  4957. * RegExp are stateful when they have the global or sticky flags set.
  4958. * But if we actually don't use them, the side effect does not matter.
  4959. * the check logic in `hasEffectsOnInteractionAtPath`.
  4960. */
  4961. const literalRegExpMembers = assembleMemberDescriptions({
  4962. exec: returnsUnknown,
  4963. test: returnsBoolean
  4964. }, objectMembers);
  4965. const literalStringMembers = assembleMemberDescriptions({
  4966. anchor: returnsString,
  4967. at: returnsUnknown,
  4968. big: returnsString,
  4969. blink: returnsString,
  4970. bold: returnsString,
  4971. charAt: returnsString,
  4972. charCodeAt: returnsNumber,
  4973. codePointAt: returnsUnknown,
  4974. concat: returnsString,
  4975. endsWith: returnsBoolean,
  4976. fixed: returnsString,
  4977. fontcolor: returnsString,
  4978. fontsize: returnsString,
  4979. includes: returnsBoolean,
  4980. indexOf: returnsNumber,
  4981. italics: returnsString,
  4982. lastIndexOf: returnsNumber,
  4983. link: returnsString,
  4984. localeCompare: returnsNumber,
  4985. match: returnsUnknown,
  4986. matchAll: returnsUnknown,
  4987. normalize: returnsString,
  4988. padEnd: returnsString,
  4989. padStart: returnsString,
  4990. repeat: returnsString,
  4991. replace: stringReplace,
  4992. replaceAll: stringReplace,
  4993. search: returnsNumber,
  4994. slice: returnsString,
  4995. small: returnsString,
  4996. split: returnsUnknown,
  4997. startsWith: returnsBoolean,
  4998. strike: returnsString,
  4999. sub: returnsString,
  5000. substr: returnsString,
  5001. substring: returnsString,
  5002. sup: returnsString,
  5003. toLocaleLowerCase: returnsString,
  5004. toLocaleUpperCase: returnsString,
  5005. toLowerCase: returnsString,
  5006. toString: returnsString,
  5007. toUpperCase: returnsString,
  5008. trim: returnsString,
  5009. trimEnd: returnsString,
  5010. trimLeft: returnsString,
  5011. trimRight: returnsString,
  5012. trimStart: returnsString,
  5013. valueOf: returnsString
  5014. }, objectMembers);
  5015. function getLiteralMembersForValue(value) {
  5016. if (value instanceof RegExp) {
  5017. return literalRegExpMembers;
  5018. }
  5019. switch (typeof value) {
  5020. case 'boolean': {
  5021. return literalBooleanMembers;
  5022. }
  5023. case 'number': {
  5024. return literalNumberMembers;
  5025. }
  5026. case 'string': {
  5027. return literalStringMembers;
  5028. }
  5029. }
  5030. return Object.create(null);
  5031. }
  5032. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  5033. if (typeof memberName !== 'string' || !members[memberName]) {
  5034. return true;
  5035. }
  5036. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  5037. }
  5038. function getMemberReturnExpressionWhenCalled(members, memberName) {
  5039. if (typeof memberName !== 'string' || !members[memberName])
  5040. return UNKNOWN_RETURN_EXPRESSION;
  5041. return [members[memberName].returns, false];
  5042. }
  5043. // AST walker module for Mozilla Parser API compatible trees
  5044. function skipThrough(node, st, c) { c(node, st); }
  5045. function ignore(_node, _st, _c) {}
  5046. // Node walkers.
  5047. var base$1 = {};
  5048. base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {
  5049. for (var i = 0, list = node.body; i < list.length; i += 1)
  5050. {
  5051. var stmt = list[i];
  5052. c(stmt, st, "Statement");
  5053. }
  5054. };
  5055. base$1.Statement = skipThrough;
  5056. base$1.EmptyStatement = ignore;
  5057. base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
  5058. function (node, st, c) { return c(node.expression, st, "Expression"); };
  5059. base$1.IfStatement = function (node, st, c) {
  5060. c(node.test, st, "Expression");
  5061. c(node.consequent, st, "Statement");
  5062. if (node.alternate) { c(node.alternate, st, "Statement"); }
  5063. };
  5064. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  5065. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  5066. base$1.WithStatement = function (node, st, c) {
  5067. c(node.object, st, "Expression");
  5068. c(node.body, st, "Statement");
  5069. };
  5070. base$1.SwitchStatement = function (node, st, c) {
  5071. c(node.discriminant, st, "Expression");
  5072. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  5073. var cs = list$1[i$1];
  5074. if (cs.test) { c(cs.test, st, "Expression"); }
  5075. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  5076. {
  5077. var cons = list[i];
  5078. c(cons, st, "Statement");
  5079. }
  5080. }
  5081. };
  5082. base$1.SwitchCase = function (node, st, c) {
  5083. if (node.test) { c(node.test, st, "Expression"); }
  5084. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  5085. {
  5086. var cons = list[i];
  5087. c(cons, st, "Statement");
  5088. }
  5089. };
  5090. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  5091. if (node.argument) { c(node.argument, st, "Expression"); }
  5092. };
  5093. base$1.ThrowStatement = base$1.SpreadElement =
  5094. function (node, st, c) { return c(node.argument, st, "Expression"); };
  5095. base$1.TryStatement = function (node, st, c) {
  5096. c(node.block, st, "Statement");
  5097. if (node.handler) { c(node.handler, st); }
  5098. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  5099. };
  5100. base$1.CatchClause = function (node, st, c) {
  5101. if (node.param) { c(node.param, st, "Pattern"); }
  5102. c(node.body, st, "Statement");
  5103. };
  5104. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  5105. c(node.test, st, "Expression");
  5106. c(node.body, st, "Statement");
  5107. };
  5108. base$1.ForStatement = function (node, st, c) {
  5109. if (node.init) { c(node.init, st, "ForInit"); }
  5110. if (node.test) { c(node.test, st, "Expression"); }
  5111. if (node.update) { c(node.update, st, "Expression"); }
  5112. c(node.body, st, "Statement");
  5113. };
  5114. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  5115. c(node.left, st, "ForInit");
  5116. c(node.right, st, "Expression");
  5117. c(node.body, st, "Statement");
  5118. };
  5119. base$1.ForInit = function (node, st, c) {
  5120. if (node.type === "VariableDeclaration") { c(node, st); }
  5121. else { c(node, st, "Expression"); }
  5122. };
  5123. base$1.DebuggerStatement = ignore;
  5124. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  5125. base$1.VariableDeclaration = function (node, st, c) {
  5126. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  5127. {
  5128. var decl = list[i];
  5129. c(decl, st);
  5130. }
  5131. };
  5132. base$1.VariableDeclarator = function (node, st, c) {
  5133. c(node.id, st, "Pattern");
  5134. if (node.init) { c(node.init, st, "Expression"); }
  5135. };
  5136. base$1.Function = function (node, st, c) {
  5137. if (node.id) { c(node.id, st, "Pattern"); }
  5138. for (var i = 0, list = node.params; i < list.length; i += 1)
  5139. {
  5140. var param = list[i];
  5141. c(param, st, "Pattern");
  5142. }
  5143. c(node.body, st, node.expression ? "Expression" : "Statement");
  5144. };
  5145. base$1.Pattern = function (node, st, c) {
  5146. if (node.type === "Identifier")
  5147. { c(node, st, "VariablePattern"); }
  5148. else if (node.type === "MemberExpression")
  5149. { c(node, st, "MemberPattern"); }
  5150. else
  5151. { c(node, st); }
  5152. };
  5153. base$1.VariablePattern = ignore;
  5154. base$1.MemberPattern = skipThrough;
  5155. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  5156. base$1.ArrayPattern = function (node, st, c) {
  5157. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  5158. var elt = list[i];
  5159. if (elt) { c(elt, st, "Pattern"); }
  5160. }
  5161. };
  5162. base$1.ObjectPattern = function (node, st, c) {
  5163. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  5164. var prop = list[i];
  5165. if (prop.type === "Property") {
  5166. if (prop.computed) { c(prop.key, st, "Expression"); }
  5167. c(prop.value, st, "Pattern");
  5168. } else if (prop.type === "RestElement") {
  5169. c(prop.argument, st, "Pattern");
  5170. }
  5171. }
  5172. };
  5173. base$1.Expression = skipThrough;
  5174. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  5175. base$1.ArrayExpression = function (node, st, c) {
  5176. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  5177. var elt = list[i];
  5178. if (elt) { c(elt, st, "Expression"); }
  5179. }
  5180. };
  5181. base$1.ObjectExpression = function (node, st, c) {
  5182. for (var i = 0, list = node.properties; i < list.length; i += 1)
  5183. {
  5184. var prop = list[i];
  5185. c(prop, st);
  5186. }
  5187. };
  5188. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  5189. base$1.SequenceExpression = function (node, st, c) {
  5190. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  5191. {
  5192. var expr = list[i];
  5193. c(expr, st, "Expression");
  5194. }
  5195. };
  5196. base$1.TemplateLiteral = function (node, st, c) {
  5197. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  5198. {
  5199. var quasi = list[i];
  5200. c(quasi, st);
  5201. }
  5202. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  5203. {
  5204. var expr = list$1[i$1];
  5205. c(expr, st, "Expression");
  5206. }
  5207. };
  5208. base$1.TemplateElement = ignore;
  5209. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  5210. c(node.argument, st, "Expression");
  5211. };
  5212. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  5213. c(node.left, st, "Expression");
  5214. c(node.right, st, "Expression");
  5215. };
  5216. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  5217. c(node.left, st, "Pattern");
  5218. c(node.right, st, "Expression");
  5219. };
  5220. base$1.ConditionalExpression = function (node, st, c) {
  5221. c(node.test, st, "Expression");
  5222. c(node.consequent, st, "Expression");
  5223. c(node.alternate, st, "Expression");
  5224. };
  5225. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  5226. c(node.callee, st, "Expression");
  5227. if (node.arguments)
  5228. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  5229. {
  5230. var arg = list[i];
  5231. c(arg, st, "Expression");
  5232. } }
  5233. };
  5234. base$1.MemberExpression = function (node, st, c) {
  5235. c(node.object, st, "Expression");
  5236. if (node.computed) { c(node.property, st, "Expression"); }
  5237. };
  5238. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  5239. if (node.declaration)
  5240. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  5241. if (node.source) { c(node.source, st, "Expression"); }
  5242. };
  5243. base$1.ExportAllDeclaration = function (node, st, c) {
  5244. if (node.exported)
  5245. { c(node.exported, st); }
  5246. c(node.source, st, "Expression");
  5247. };
  5248. base$1.ImportDeclaration = function (node, st, c) {
  5249. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  5250. {
  5251. var spec = list[i];
  5252. c(spec, st);
  5253. }
  5254. c(node.source, st, "Expression");
  5255. };
  5256. base$1.ImportExpression = function (node, st, c) {
  5257. c(node.source, st, "Expression");
  5258. };
  5259. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
  5260. base$1.TaggedTemplateExpression = function (node, st, c) {
  5261. c(node.tag, st, "Expression");
  5262. c(node.quasi, st, "Expression");
  5263. };
  5264. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  5265. base$1.Class = function (node, st, c) {
  5266. if (node.id) { c(node.id, st, "Pattern"); }
  5267. if (node.superClass) { c(node.superClass, st, "Expression"); }
  5268. c(node.body, st);
  5269. };
  5270. base$1.ClassBody = function (node, st, c) {
  5271. for (var i = 0, list = node.body; i < list.length; i += 1)
  5272. {
  5273. var elt = list[i];
  5274. c(elt, st);
  5275. }
  5276. };
  5277. base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
  5278. if (node.computed) { c(node.key, st, "Expression"); }
  5279. if (node.value) { c(node.value, st, "Expression"); }
  5280. };
  5281. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  5282. const BinaryExpression$1 = 'BinaryExpression';
  5283. const BlockStatement$1 = 'BlockStatement';
  5284. const CallExpression$1 = 'CallExpression';
  5285. const ChainExpression$1 = 'ChainExpression';
  5286. const ConditionalExpression$1 = 'ConditionalExpression';
  5287. const ExpressionStatement$1 = 'ExpressionStatement';
  5288. const Identifier$1 = 'Identifier';
  5289. const LogicalExpression$1 = 'LogicalExpression';
  5290. const NewExpression$1 = 'NewExpression';
  5291. const Program$1 = 'Program';
  5292. const Property$1 = 'Property';
  5293. const ReturnStatement$1 = 'ReturnStatement';
  5294. const SequenceExpression$1 = 'SequenceExpression';
  5295. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  5296. // this for an actual sourceMappingURL
  5297. let SOURCEMAPPING_URL = 'sourceMa';
  5298. SOURCEMAPPING_URL += 'ppingURL';
  5299. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  5300. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
  5301. const ANNOTATION_KEY = '_rollupAnnotations';
  5302. const INVALID_COMMENT_KEY = '_rollupRemoved';
  5303. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  5304. const { annotations, code } = state;
  5305. // eslint-disable-next-line unicorn/consistent-destructuring
  5306. let comment = annotations[state.annotationIndex];
  5307. while (comment && node.start >= comment.end) {
  5308. markPureNode(node, comment, code);
  5309. comment = annotations[++state.annotationIndex];
  5310. }
  5311. if (comment && comment.end <= node.end) {
  5312. base$1[type](node, state, handlePureAnnotationsOfNode);
  5313. // eslint-disable-next-line unicorn/consistent-destructuring
  5314. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  5315. ++state.annotationIndex;
  5316. annotateNode(node, comment, false);
  5317. }
  5318. }
  5319. }
  5320. const neitherWithespaceNorBrackets = /[^\s(]/g;
  5321. const noWhitespace = /\S/g;
  5322. function markPureNode(node, comment, code) {
  5323. const annotatedNodes = [];
  5324. let invalidAnnotation;
  5325. const codeInBetween = code.slice(comment.end, node.start);
  5326. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  5327. const parentStart = node.start;
  5328. while (true) {
  5329. annotatedNodes.push(node);
  5330. switch (node.type) {
  5331. case ExpressionStatement$1:
  5332. case ChainExpression$1: {
  5333. node = node.expression;
  5334. continue;
  5335. }
  5336. case SequenceExpression$1: {
  5337. // if there are parentheses, the annotation would apply to the entire expression
  5338. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  5339. node = node.expressions[0];
  5340. continue;
  5341. }
  5342. invalidAnnotation = true;
  5343. break;
  5344. }
  5345. case ConditionalExpression$1: {
  5346. // if there are parentheses, the annotation would apply to the entire expression
  5347. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  5348. node = node.test;
  5349. continue;
  5350. }
  5351. invalidAnnotation = true;
  5352. break;
  5353. }
  5354. case LogicalExpression$1:
  5355. case BinaryExpression$1: {
  5356. // if there are parentheses, the annotation would apply to the entire expression
  5357. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  5358. node = node.left;
  5359. continue;
  5360. }
  5361. invalidAnnotation = true;
  5362. break;
  5363. }
  5364. case CallExpression$1:
  5365. case NewExpression$1: {
  5366. break;
  5367. }
  5368. default: {
  5369. invalidAnnotation = true;
  5370. }
  5371. }
  5372. break;
  5373. }
  5374. }
  5375. else {
  5376. invalidAnnotation = true;
  5377. }
  5378. if (invalidAnnotation) {
  5379. annotateNode(node, comment, false);
  5380. }
  5381. else {
  5382. for (const node of annotatedNodes) {
  5383. annotateNode(node, comment, true);
  5384. }
  5385. }
  5386. }
  5387. function doesNotMatchOutsideComment(code, forbiddenChars) {
  5388. let nextMatch;
  5389. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  5390. if (nextMatch[0] === '/') {
  5391. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  5392. if (charCodeAfterSlash === 42 /*"*"*/) {
  5393. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  5394. continue;
  5395. }
  5396. else if (charCodeAfterSlash === 47 /*"/"*/) {
  5397. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  5398. continue;
  5399. }
  5400. }
  5401. forbiddenChars.lastIndex = 0;
  5402. return false;
  5403. }
  5404. return true;
  5405. }
  5406. const pureCommentRegex = /[#@]__PURE__/;
  5407. function addAnnotations(comments, esTreeAst, code) {
  5408. const annotations = [];
  5409. const sourceMappingComments = [];
  5410. for (const comment of comments) {
  5411. if (pureCommentRegex.test(comment.value)) {
  5412. annotations.push(comment);
  5413. }
  5414. else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  5415. sourceMappingComments.push(comment);
  5416. }
  5417. }
  5418. for (const comment of sourceMappingComments) {
  5419. annotateNode(esTreeAst, comment, false);
  5420. }
  5421. handlePureAnnotationsOfNode(esTreeAst, {
  5422. annotationIndex: 0,
  5423. annotations,
  5424. code
  5425. });
  5426. }
  5427. function annotateNode(node, comment, valid) {
  5428. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  5429. const property = node[key];
  5430. if (property) {
  5431. property.push(comment);
  5432. }
  5433. else {
  5434. node[key] = [comment];
  5435. }
  5436. }
  5437. const keys = {
  5438. // TODO this should be removed once ImportExpression follows official ESTree
  5439. // specs with "null" as default
  5440. ImportExpression: ['arguments'],
  5441. Literal: [],
  5442. Program: ['body']
  5443. };
  5444. function getAndCreateKeys(esTreeNode) {
  5445. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  5446. return keys[esTreeNode.type];
  5447. }
  5448. const INCLUDE_PARAMETERS = 'variables';
  5449. class NodeBase extends ExpressionEntity {
  5450. constructor(esTreeNode, parent, parentScope, keepEsTreeNode = false) {
  5451. super();
  5452. /**
  5453. * Nodes can apply custom deoptimizations once they become part of the
  5454. * executed code. To do this, they must initialize this as false, implement
  5455. * applyDeoptimizations and call this from include and hasEffects if they have
  5456. * custom handlers
  5457. */
  5458. this.deoptimized = false;
  5459. // Nodes can opt-in to keep the AST if needed during the build pipeline.
  5460. // Avoid true when possible as large AST takes up memory.
  5461. this.esTreeNode = keepEsTreeNode ? esTreeNode : null;
  5462. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  5463. this.parent = parent;
  5464. this.context = parent.context;
  5465. this.createScope(parentScope);
  5466. this.parseNode(esTreeNode);
  5467. this.initialise();
  5468. this.context.magicString.addSourcemapLocation(this.start);
  5469. this.context.magicString.addSourcemapLocation(this.end);
  5470. }
  5471. addExportedVariables(_variables, _exportNamesByVariable) { }
  5472. /**
  5473. * Override this to bind assignments to variables and do any initialisations
  5474. * that require the scopes to be populated with variables.
  5475. */
  5476. bind() {
  5477. for (const key of this.keys) {
  5478. const value = this[key];
  5479. if (Array.isArray(value)) {
  5480. for (const child of value) {
  5481. child?.bind();
  5482. }
  5483. }
  5484. else if (value) {
  5485. value.bind();
  5486. }
  5487. }
  5488. }
  5489. /**
  5490. * Override if this node should receive a different scope than the parent
  5491. * scope.
  5492. */
  5493. createScope(parentScope) {
  5494. this.scope = parentScope;
  5495. }
  5496. hasEffects(context) {
  5497. if (!this.deoptimized)
  5498. this.applyDeoptimizations();
  5499. for (const key of this.keys) {
  5500. const value = this[key];
  5501. if (value === null)
  5502. continue;
  5503. if (Array.isArray(value)) {
  5504. for (const child of value) {
  5505. if (child?.hasEffects(context))
  5506. return true;
  5507. }
  5508. }
  5509. else if (value.hasEffects(context))
  5510. return true;
  5511. }
  5512. return false;
  5513. }
  5514. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  5515. return (this.hasEffects(context) ||
  5516. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  5517. }
  5518. include(context, includeChildrenRecursively, _options) {
  5519. if (!this.deoptimized)
  5520. this.applyDeoptimizations();
  5521. this.included = true;
  5522. for (const key of this.keys) {
  5523. const value = this[key];
  5524. if (value === null)
  5525. continue;
  5526. if (Array.isArray(value)) {
  5527. for (const child of value) {
  5528. child?.include(context, includeChildrenRecursively);
  5529. }
  5530. }
  5531. else {
  5532. value.include(context, includeChildrenRecursively);
  5533. }
  5534. }
  5535. }
  5536. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  5537. this.include(context, includeChildrenRecursively);
  5538. }
  5539. /**
  5540. * Override to perform special initialisation steps after the scope is
  5541. * initialised
  5542. */
  5543. initialise() { }
  5544. insertSemicolon(code) {
  5545. if (code.original[this.end - 1] !== ';') {
  5546. code.appendLeft(this.end, ';');
  5547. }
  5548. }
  5549. parseNode(esTreeNode, keepEsTreeNodeKeys) {
  5550. for (const [key, value] of Object.entries(esTreeNode)) {
  5551. // That way, we can override this function to add custom initialisation and then call super.parseNode
  5552. if (this.hasOwnProperty(key))
  5553. continue;
  5554. if (key.charCodeAt(0) === 95 /* _ */) {
  5555. if (key === ANNOTATION_KEY) {
  5556. this.annotations = value;
  5557. }
  5558. else if (key === INVALID_COMMENT_KEY) {
  5559. for (const { start, end } of value)
  5560. this.context.magicString.remove(start, end);
  5561. }
  5562. }
  5563. else if (typeof value !== 'object' || value === null) {
  5564. this[key] = value;
  5565. }
  5566. else if (Array.isArray(value)) {
  5567. this[key] = [];
  5568. for (const child of value) {
  5569. this[key].push(child === null
  5570. ? null
  5571. : new (this.context.getNodeConstructor(child.type))(child, this, this.scope, keepEsTreeNodeKeys?.includes(key)));
  5572. }
  5573. }
  5574. else {
  5575. this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope, keepEsTreeNodeKeys?.includes(key));
  5576. }
  5577. }
  5578. }
  5579. render(code, options) {
  5580. for (const key of this.keys) {
  5581. const value = this[key];
  5582. if (value === null)
  5583. continue;
  5584. if (Array.isArray(value)) {
  5585. for (const child of value) {
  5586. child?.render(code, options);
  5587. }
  5588. }
  5589. else {
  5590. value.render(code, options);
  5591. }
  5592. }
  5593. }
  5594. setAssignedValue(value) {
  5595. this.assignmentInteraction = { args: [value], thisArg: null, type: INTERACTION_ASSIGNED };
  5596. }
  5597. shouldBeIncluded(context) {
  5598. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  5599. }
  5600. /**
  5601. * Just deoptimize everything by default so that when e.g. we do not track
  5602. * something properly, it is deoptimized.
  5603. * @protected
  5604. */
  5605. applyDeoptimizations() {
  5606. this.deoptimized = true;
  5607. for (const key of this.keys) {
  5608. const value = this[key];
  5609. if (value === null)
  5610. continue;
  5611. if (Array.isArray(value)) {
  5612. for (const child of value) {
  5613. child?.deoptimizePath(UNKNOWN_PATH);
  5614. }
  5615. }
  5616. else {
  5617. value.deoptimizePath(UNKNOWN_PATH);
  5618. }
  5619. }
  5620. this.context.requestTreeshakingPass();
  5621. }
  5622. }
  5623. class SpreadElement extends NodeBase {
  5624. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5625. if (path.length > 0) {
  5626. this.argument.deoptimizeThisOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  5627. }
  5628. }
  5629. hasEffects(context) {
  5630. if (!this.deoptimized)
  5631. this.applyDeoptimizations();
  5632. const { propertyReadSideEffects } = this.context.options
  5633. .treeshake;
  5634. return (this.argument.hasEffects(context) ||
  5635. (propertyReadSideEffects &&
  5636. (propertyReadSideEffects === 'always' ||
  5637. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  5638. }
  5639. applyDeoptimizations() {
  5640. this.deoptimized = true;
  5641. // Only properties of properties of the argument could become subject to reassignment
  5642. // This will also reassign the return values of iterators
  5643. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  5644. this.context.requestTreeshakingPass();
  5645. }
  5646. }
  5647. class Method extends ExpressionEntity {
  5648. constructor(description) {
  5649. super();
  5650. this.description = description;
  5651. }
  5652. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  5653. if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  5654. thisArg.deoptimizePath(UNKNOWN_INTEGER_PATH);
  5655. }
  5656. }
  5657. getReturnExpressionWhenCalledAtPath(path, { thisArg }) {
  5658. if (path.length > 0) {
  5659. return UNKNOWN_RETURN_EXPRESSION;
  5660. }
  5661. return [
  5662. this.description.returnsPrimitive ||
  5663. (this.description.returns === 'self'
  5664. ? thisArg || UNKNOWN_EXPRESSION
  5665. : this.description.returns()),
  5666. false
  5667. ];
  5668. }
  5669. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5670. const { type } = interaction;
  5671. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  5672. return true;
  5673. }
  5674. if (type === INTERACTION_CALLED) {
  5675. const { args, thisArg } = interaction;
  5676. if (this.description.mutatesSelfAsArray === true &&
  5677. thisArg?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  5678. return true;
  5679. }
  5680. if (this.description.callsArgs) {
  5681. for (const argumentIndex of this.description.callsArgs) {
  5682. if (args[argumentIndex]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  5683. return true;
  5684. }
  5685. }
  5686. }
  5687. }
  5688. return false;
  5689. }
  5690. }
  5691. const METHOD_RETURNS_BOOLEAN = [
  5692. new Method({
  5693. callsArgs: null,
  5694. mutatesSelfAsArray: false,
  5695. returns: null,
  5696. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  5697. })
  5698. ];
  5699. const METHOD_RETURNS_STRING = [
  5700. new Method({
  5701. callsArgs: null,
  5702. mutatesSelfAsArray: false,
  5703. returns: null,
  5704. returnsPrimitive: UNKNOWN_LITERAL_STRING
  5705. })
  5706. ];
  5707. const METHOD_RETURNS_NUMBER = [
  5708. new Method({
  5709. callsArgs: null,
  5710. mutatesSelfAsArray: false,
  5711. returns: null,
  5712. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5713. })
  5714. ];
  5715. const METHOD_RETURNS_UNKNOWN = [
  5716. new Method({
  5717. callsArgs: null,
  5718. mutatesSelfAsArray: false,
  5719. returns: null,
  5720. returnsPrimitive: UNKNOWN_EXPRESSION
  5721. })
  5722. ];
  5723. const INTEGER_REG_EXP = /^\d+$/;
  5724. class ObjectEntity extends ExpressionEntity {
  5725. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  5726. // and we assume there are no setters or getters
  5727. constructor(properties, prototypeExpression, immutable = false) {
  5728. super();
  5729. this.prototypeExpression = prototypeExpression;
  5730. this.immutable = immutable;
  5731. this.allProperties = [];
  5732. this.deoptimizedPaths = Object.create(null);
  5733. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  5734. this.gettersByKey = Object.create(null);
  5735. this.hasLostTrack = false;
  5736. this.hasUnknownDeoptimizedInteger = false;
  5737. this.hasUnknownDeoptimizedProperty = false;
  5738. this.propertiesAndGettersByKey = Object.create(null);
  5739. this.propertiesAndSettersByKey = Object.create(null);
  5740. this.settersByKey = Object.create(null);
  5741. this.thisParametersToBeDeoptimized = new Set();
  5742. this.unknownIntegerProps = [];
  5743. this.unmatchableGetters = [];
  5744. this.unmatchablePropertiesAndGetters = [];
  5745. this.unmatchableSetters = [];
  5746. if (Array.isArray(properties)) {
  5747. this.buildPropertyMaps(properties);
  5748. }
  5749. else {
  5750. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  5751. for (const propertiesForKey of Object.values(properties)) {
  5752. this.allProperties.push(...propertiesForKey);
  5753. }
  5754. }
  5755. }
  5756. deoptimizeAllProperties(noAccessors) {
  5757. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  5758. if (noAccessors) {
  5759. this.hasUnknownDeoptimizedProperty = true;
  5760. }
  5761. else {
  5762. this.hasLostTrack = true;
  5763. }
  5764. if (isDeoptimized) {
  5765. return;
  5766. }
  5767. for (const properties of [
  5768. ...Object.values(this.propertiesAndGettersByKey),
  5769. ...Object.values(this.settersByKey)
  5770. ]) {
  5771. for (const property of properties) {
  5772. property.deoptimizePath(UNKNOWN_PATH);
  5773. }
  5774. }
  5775. // While the prototype itself cannot be mutated, each property can
  5776. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  5777. this.deoptimizeCachedEntities();
  5778. }
  5779. deoptimizeIntegerProperties() {
  5780. if (this.hasLostTrack ||
  5781. this.hasUnknownDeoptimizedProperty ||
  5782. this.hasUnknownDeoptimizedInteger) {
  5783. return;
  5784. }
  5785. this.hasUnknownDeoptimizedInteger = true;
  5786. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  5787. if (INTEGER_REG_EXP.test(key)) {
  5788. for (const property of propertiesAndGetters) {
  5789. property.deoptimizePath(UNKNOWN_PATH);
  5790. }
  5791. }
  5792. }
  5793. this.deoptimizeCachedIntegerEntities();
  5794. }
  5795. // Assumption: If only a specific path is deoptimized, no accessors are created
  5796. deoptimizePath(path) {
  5797. if (this.hasLostTrack || this.immutable) {
  5798. return;
  5799. }
  5800. const key = path[0];
  5801. if (path.length === 1) {
  5802. if (typeof key !== 'string') {
  5803. if (key === UnknownInteger) {
  5804. return this.deoptimizeIntegerProperties();
  5805. }
  5806. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  5807. }
  5808. if (!this.deoptimizedPaths[key]) {
  5809. this.deoptimizedPaths[key] = true;
  5810. // we only deoptimizeCache exact matches as in all other cases,
  5811. // we do not return a literal value or return expression
  5812. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  5813. if (expressionsToBeDeoptimized) {
  5814. for (const expression of expressionsToBeDeoptimized) {
  5815. expression.deoptimizeCache();
  5816. }
  5817. }
  5818. }
  5819. }
  5820. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  5821. for (const property of typeof key === 'string'
  5822. ? [
  5823. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  5824. ...(this.settersByKey[key] || this.unmatchableSetters)
  5825. ]
  5826. : this.allProperties) {
  5827. property.deoptimizePath(subPath);
  5828. }
  5829. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  5830. }
  5831. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5832. const [key, ...subPath] = path;
  5833. if (this.hasLostTrack ||
  5834. // single paths that are deoptimized will not become getters or setters
  5835. ((interaction.type === INTERACTION_CALLED || path.length > 1) &&
  5836. (this.hasUnknownDeoptimizedProperty ||
  5837. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  5838. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  5839. return;
  5840. }
  5841. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = interaction.type === INTERACTION_CALLED || path.length > 1
  5842. ? [
  5843. this.propertiesAndGettersByKey,
  5844. this.propertiesAndGettersByKey,
  5845. this.unmatchablePropertiesAndGetters
  5846. ]
  5847. : interaction.type === INTERACTION_ACCESSED
  5848. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5849. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5850. if (typeof key === 'string') {
  5851. if (propertiesForExactMatchByKey[key]) {
  5852. const properties = relevantPropertiesByKey[key];
  5853. if (properties) {
  5854. for (const property of properties) {
  5855. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5856. }
  5857. }
  5858. if (!this.immutable) {
  5859. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  5860. }
  5861. return;
  5862. }
  5863. for (const property of relevantUnmatchableProperties) {
  5864. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5865. }
  5866. if (INTEGER_REG_EXP.test(key)) {
  5867. for (const property of this.unknownIntegerProps) {
  5868. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5869. }
  5870. }
  5871. }
  5872. else {
  5873. for (const properties of [
  5874. ...Object.values(relevantPropertiesByKey),
  5875. relevantUnmatchableProperties
  5876. ]) {
  5877. for (const property of properties) {
  5878. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5879. }
  5880. }
  5881. for (const property of this.unknownIntegerProps) {
  5882. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5883. }
  5884. }
  5885. if (!this.immutable) {
  5886. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  5887. }
  5888. this.prototypeExpression?.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  5889. }
  5890. getLiteralValueAtPath(path, recursionTracker, origin) {
  5891. if (path.length === 0) {
  5892. return UnknownTruthyValue;
  5893. }
  5894. const key = path[0];
  5895. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  5896. if (expressionAtPath) {
  5897. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  5898. }
  5899. if (this.prototypeExpression) {
  5900. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  5901. }
  5902. if (path.length === 1) {
  5903. return undefined;
  5904. }
  5905. return UnknownValue;
  5906. }
  5907. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5908. if (path.length === 0) {
  5909. return UNKNOWN_RETURN_EXPRESSION;
  5910. }
  5911. const [key, ...subPath] = path;
  5912. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  5913. if (expressionAtPath) {
  5914. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  5915. }
  5916. if (this.prototypeExpression) {
  5917. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5918. }
  5919. return UNKNOWN_RETURN_EXPRESSION;
  5920. }
  5921. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5922. const [key, ...subPath] = path;
  5923. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  5924. const expressionAtPath = this.getMemberExpression(key);
  5925. if (expressionAtPath) {
  5926. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  5927. }
  5928. if (this.prototypeExpression) {
  5929. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5930. }
  5931. return true;
  5932. }
  5933. if (key === UnknownNonAccessorKey)
  5934. return false;
  5935. if (this.hasLostTrack)
  5936. return true;
  5937. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  5938. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5939. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5940. if (typeof key === 'string') {
  5941. if (propertiesAndAccessorsByKey[key]) {
  5942. const accessors = accessorsByKey[key];
  5943. if (accessors) {
  5944. for (const accessor of accessors) {
  5945. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5946. return true;
  5947. }
  5948. }
  5949. return false;
  5950. }
  5951. for (const accessor of unmatchableAccessors) {
  5952. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  5953. return true;
  5954. }
  5955. }
  5956. }
  5957. else {
  5958. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  5959. for (const accessor of accessors) {
  5960. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5961. return true;
  5962. }
  5963. }
  5964. }
  5965. if (this.prototypeExpression) {
  5966. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5967. }
  5968. return false;
  5969. }
  5970. buildPropertyMaps(properties) {
  5971. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  5972. const unmatchablePropertiesAndSetters = [];
  5973. for (let index = properties.length - 1; index >= 0; index--) {
  5974. const { key, kind, property } = properties[index];
  5975. allProperties.push(property);
  5976. if (typeof key === 'string') {
  5977. if (kind === 'set') {
  5978. if (!propertiesAndSettersByKey[key]) {
  5979. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5980. settersByKey[key] = [property, ...unmatchableSetters];
  5981. }
  5982. }
  5983. else if (kind === 'get') {
  5984. if (!propertiesAndGettersByKey[key]) {
  5985. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5986. gettersByKey[key] = [property, ...unmatchableGetters];
  5987. }
  5988. }
  5989. else {
  5990. if (!propertiesAndSettersByKey[key]) {
  5991. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5992. }
  5993. if (!propertiesAndGettersByKey[key]) {
  5994. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5995. }
  5996. }
  5997. }
  5998. else {
  5999. if (key === UnknownInteger) {
  6000. unknownIntegerProps.push(property);
  6001. continue;
  6002. }
  6003. if (kind === 'set')
  6004. unmatchableSetters.push(property);
  6005. if (kind === 'get')
  6006. unmatchableGetters.push(property);
  6007. if (kind !== 'get')
  6008. unmatchablePropertiesAndSetters.push(property);
  6009. if (kind !== 'set')
  6010. unmatchablePropertiesAndGetters.push(property);
  6011. }
  6012. }
  6013. }
  6014. deoptimizeCachedEntities() {
  6015. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  6016. for (const expression of expressionsToBeDeoptimized) {
  6017. expression.deoptimizeCache();
  6018. }
  6019. }
  6020. for (const expression of this.thisParametersToBeDeoptimized) {
  6021. expression.deoptimizePath(UNKNOWN_PATH);
  6022. }
  6023. }
  6024. deoptimizeCachedIntegerEntities() {
  6025. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  6026. if (INTEGER_REG_EXP.test(key)) {
  6027. for (const expression of expressionsToBeDeoptimized) {
  6028. expression.deoptimizeCache();
  6029. }
  6030. }
  6031. }
  6032. for (const expression of this.thisParametersToBeDeoptimized) {
  6033. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  6034. }
  6035. }
  6036. getMemberExpression(key) {
  6037. if (this.hasLostTrack ||
  6038. this.hasUnknownDeoptimizedProperty ||
  6039. typeof key !== 'string' ||
  6040. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  6041. this.deoptimizedPaths[key]) {
  6042. return UNKNOWN_EXPRESSION;
  6043. }
  6044. const properties = this.propertiesAndGettersByKey[key];
  6045. if (properties?.length === 1) {
  6046. return properties[0];
  6047. }
  6048. if (properties ||
  6049. this.unmatchablePropertiesAndGetters.length > 0 ||
  6050. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  6051. return UNKNOWN_EXPRESSION;
  6052. }
  6053. return null;
  6054. }
  6055. getMemberExpressionAndTrackDeopt(key, origin) {
  6056. if (typeof key !== 'string') {
  6057. return UNKNOWN_EXPRESSION;
  6058. }
  6059. const expression = this.getMemberExpression(key);
  6060. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  6061. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  6062. this.expressionsToBeDeoptimizedByKey[key] || []);
  6063. expressionsToBeDeoptimized.push(origin);
  6064. }
  6065. return expression;
  6066. }
  6067. }
  6068. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  6069. // This makes sure unknown properties are not handled as "undefined" but as
  6070. // "unknown" but without access side effects. An exception is done for numeric
  6071. // properties as we do not expect new builtin properties to be numbers, this
  6072. // will improve tree-shaking for out-of-bounds array properties
  6073. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  6074. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  6075. if (type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  6076. thisArg.deoptimizePath(UNKNOWN_PATH);
  6077. }
  6078. }
  6079. getLiteralValueAtPath(path) {
  6080. // We ignore number properties as we do not expect new properties to be
  6081. // numbers and also want to keep handling out-of-bound array elements as
  6082. // "undefined"
  6083. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  6084. }
  6085. hasEffectsOnInteractionAtPath(path, { type }) {
  6086. return path.length > 1 || type === INTERACTION_CALLED;
  6087. }
  6088. })();
  6089. const OBJECT_PROTOTYPE = new ObjectEntity({
  6090. __proto__: null,
  6091. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  6092. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  6093. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  6094. toLocaleString: METHOD_RETURNS_STRING,
  6095. toString: METHOD_RETURNS_STRING,
  6096. valueOf: METHOD_RETURNS_UNKNOWN
  6097. }, OBJECT_PROTOTYPE_FALLBACK, true);
  6098. const NEW_ARRAY_PROPERTIES = [
  6099. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  6100. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  6101. ];
  6102. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  6103. new Method({
  6104. callsArgs: [0],
  6105. mutatesSelfAsArray: 'deopt-only',
  6106. returns: null,
  6107. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  6108. })
  6109. ];
  6110. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  6111. new Method({
  6112. callsArgs: [0],
  6113. mutatesSelfAsArray: 'deopt-only',
  6114. returns: null,
  6115. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6116. })
  6117. ];
  6118. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  6119. new Method({
  6120. callsArgs: null,
  6121. mutatesSelfAsArray: true,
  6122. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6123. returnsPrimitive: null
  6124. })
  6125. ];
  6126. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  6127. new Method({
  6128. callsArgs: null,
  6129. mutatesSelfAsArray: 'deopt-only',
  6130. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6131. returnsPrimitive: null
  6132. })
  6133. ];
  6134. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  6135. new Method({
  6136. callsArgs: [0],
  6137. mutatesSelfAsArray: 'deopt-only',
  6138. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6139. returnsPrimitive: null
  6140. })
  6141. ];
  6142. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  6143. new Method({
  6144. callsArgs: null,
  6145. mutatesSelfAsArray: true,
  6146. returns: null,
  6147. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6148. })
  6149. ];
  6150. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  6151. new Method({
  6152. callsArgs: null,
  6153. mutatesSelfAsArray: true,
  6154. returns: null,
  6155. returnsPrimitive: UNKNOWN_EXPRESSION
  6156. })
  6157. ];
  6158. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  6159. new Method({
  6160. callsArgs: null,
  6161. mutatesSelfAsArray: 'deopt-only',
  6162. returns: null,
  6163. returnsPrimitive: UNKNOWN_EXPRESSION
  6164. })
  6165. ];
  6166. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  6167. new Method({
  6168. callsArgs: [0],
  6169. mutatesSelfAsArray: 'deopt-only',
  6170. returns: null,
  6171. returnsPrimitive: UNKNOWN_EXPRESSION
  6172. })
  6173. ];
  6174. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  6175. new Method({
  6176. callsArgs: null,
  6177. mutatesSelfAsArray: true,
  6178. returns: 'self',
  6179. returnsPrimitive: null
  6180. })
  6181. ];
  6182. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  6183. new Method({
  6184. callsArgs: [0],
  6185. mutatesSelfAsArray: true,
  6186. returns: 'self',
  6187. returnsPrimitive: null
  6188. })
  6189. ];
  6190. const ARRAY_PROTOTYPE = new ObjectEntity({
  6191. __proto__: null,
  6192. // We assume that accessors have effects as we do not track the accessed value afterwards
  6193. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  6194. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6195. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  6196. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6197. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  6198. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  6199. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6200. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6201. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  6202. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6203. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  6204. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6205. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6206. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6207. includes: METHOD_RETURNS_BOOLEAN,
  6208. indexOf: METHOD_RETURNS_NUMBER,
  6209. join: METHOD_RETURNS_STRING,
  6210. keys: METHOD_RETURNS_UNKNOWN,
  6211. lastIndexOf: METHOD_RETURNS_NUMBER,
  6212. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6213. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  6214. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  6215. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6216. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6217. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  6218. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  6219. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6220. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  6221. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  6222. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  6223. toLocaleString: METHOD_RETURNS_STRING,
  6224. toString: METHOD_RETURNS_STRING,
  6225. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  6226. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  6227. }, OBJECT_PROTOTYPE, true);
  6228. class ArrayExpression extends NodeBase {
  6229. constructor() {
  6230. super(...arguments);
  6231. this.objectEntity = null;
  6232. }
  6233. deoptimizePath(path) {
  6234. this.getObjectEntity().deoptimizePath(path);
  6235. }
  6236. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  6237. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  6238. }
  6239. getLiteralValueAtPath(path, recursionTracker, origin) {
  6240. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  6241. }
  6242. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6243. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6244. }
  6245. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6246. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  6247. }
  6248. applyDeoptimizations() {
  6249. this.deoptimized = true;
  6250. let hasSpread = false;
  6251. for (let index = 0; index < this.elements.length; index++) {
  6252. const element = this.elements[index];
  6253. if (element && (hasSpread || element instanceof SpreadElement)) {
  6254. hasSpread = true;
  6255. element.deoptimizePath(UNKNOWN_PATH);
  6256. }
  6257. }
  6258. this.context.requestTreeshakingPass();
  6259. }
  6260. getObjectEntity() {
  6261. if (this.objectEntity !== null) {
  6262. return this.objectEntity;
  6263. }
  6264. const properties = [
  6265. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  6266. ];
  6267. let hasSpread = false;
  6268. for (let index = 0; index < this.elements.length; index++) {
  6269. const element = this.elements[index];
  6270. if (hasSpread || element instanceof SpreadElement) {
  6271. if (element) {
  6272. hasSpread = true;
  6273. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  6274. }
  6275. }
  6276. else if (element) {
  6277. properties.push({ key: String(index), kind: 'init', property: element });
  6278. }
  6279. else {
  6280. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  6281. }
  6282. }
  6283. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  6284. }
  6285. }
  6286. class ArrayPattern extends NodeBase {
  6287. addExportedVariables(variables, exportNamesByVariable) {
  6288. for (const element of this.elements) {
  6289. element?.addExportedVariables(variables, exportNamesByVariable);
  6290. }
  6291. }
  6292. declare(kind) {
  6293. const variables = [];
  6294. for (const element of this.elements) {
  6295. if (element !== null) {
  6296. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  6297. }
  6298. }
  6299. return variables;
  6300. }
  6301. // Patterns can only be deoptimized at the empty path at the moment
  6302. deoptimizePath() {
  6303. for (const element of this.elements) {
  6304. element?.deoptimizePath(EMPTY_PATH);
  6305. }
  6306. }
  6307. // Patterns are only checked at the emtpy path at the moment
  6308. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  6309. for (const element of this.elements) {
  6310. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  6311. return true;
  6312. }
  6313. return false;
  6314. }
  6315. markDeclarationReached() {
  6316. for (const element of this.elements) {
  6317. element?.markDeclarationReached();
  6318. }
  6319. }
  6320. }
  6321. class LocalVariable extends Variable {
  6322. constructor(name, declarator, init, context) {
  6323. super(name);
  6324. this.calledFromTryStatement = false;
  6325. this.additionalInitializers = null;
  6326. this.expressionsToBeDeoptimized = [];
  6327. this.declarations = declarator ? [declarator] : [];
  6328. this.init = init;
  6329. this.deoptimizationTracker = context.deoptimizationTracker;
  6330. this.module = context.module;
  6331. }
  6332. addDeclaration(identifier, init) {
  6333. this.declarations.push(identifier);
  6334. const additionalInitializers = this.markInitializersForDeoptimization();
  6335. if (init !== null) {
  6336. additionalInitializers.push(init);
  6337. }
  6338. }
  6339. consolidateInitializers() {
  6340. if (this.additionalInitializers !== null) {
  6341. for (const initializer of this.additionalInitializers) {
  6342. initializer.deoptimizePath(UNKNOWN_PATH);
  6343. }
  6344. this.additionalInitializers = null;
  6345. }
  6346. }
  6347. deoptimizePath(path) {
  6348. if (this.isReassigned ||
  6349. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  6350. return;
  6351. }
  6352. if (path.length === 0) {
  6353. if (!this.isReassigned) {
  6354. this.isReassigned = true;
  6355. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6356. this.expressionsToBeDeoptimized = [];
  6357. for (const expression of expressionsToBeDeoptimized) {
  6358. expression.deoptimizeCache();
  6359. }
  6360. this.init?.deoptimizePath(UNKNOWN_PATH);
  6361. }
  6362. }
  6363. else {
  6364. this.init?.deoptimizePath(path);
  6365. }
  6366. }
  6367. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  6368. if (this.isReassigned || !this.init) {
  6369. return interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  6370. }
  6371. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  6372. }
  6373. getLiteralValueAtPath(path, recursionTracker, origin) {
  6374. if (this.isReassigned || !this.init) {
  6375. return UnknownValue;
  6376. }
  6377. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  6378. this.expressionsToBeDeoptimized.push(origin);
  6379. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  6380. }, UnknownValue);
  6381. }
  6382. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6383. if (this.isReassigned || !this.init) {
  6384. return UNKNOWN_RETURN_EXPRESSION;
  6385. }
  6386. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  6387. this.expressionsToBeDeoptimized.push(origin);
  6388. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6389. }, UNKNOWN_RETURN_EXPRESSION);
  6390. }
  6391. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6392. switch (interaction.type) {
  6393. case INTERACTION_ACCESSED: {
  6394. if (this.isReassigned)
  6395. return true;
  6396. return !!(this.init &&
  6397. !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  6398. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  6399. }
  6400. case INTERACTION_ASSIGNED: {
  6401. if (this.included)
  6402. return true;
  6403. if (path.length === 0)
  6404. return false;
  6405. if (this.isReassigned)
  6406. return true;
  6407. return !!(this.init &&
  6408. !context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  6409. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  6410. }
  6411. case INTERACTION_CALLED: {
  6412. if (this.isReassigned)
  6413. return true;
  6414. return !!(this.init &&
  6415. !(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  6416. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  6417. }
  6418. }
  6419. }
  6420. include() {
  6421. if (!this.included) {
  6422. this.included = true;
  6423. for (const declaration of this.declarations) {
  6424. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  6425. if (!declaration.included)
  6426. declaration.include(createInclusionContext(), false);
  6427. let node = declaration.parent;
  6428. while (!node.included) {
  6429. // We do not want to properly include parents in case they are part of a dead branch
  6430. // in which case .include() might pull in more dead code
  6431. node.included = true;
  6432. if (node.type === Program$1)
  6433. break;
  6434. node = node.parent;
  6435. }
  6436. }
  6437. }
  6438. }
  6439. includeCallArguments(context, parameters) {
  6440. if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
  6441. for (const argument of parameters) {
  6442. argument.include(context, false);
  6443. }
  6444. }
  6445. else if (this.init) {
  6446. context.includedCallArguments.add(this.init);
  6447. this.init.includeCallArguments(context, parameters);
  6448. context.includedCallArguments.delete(this.init);
  6449. }
  6450. }
  6451. markCalledFromTryStatement() {
  6452. this.calledFromTryStatement = true;
  6453. }
  6454. markInitializersForDeoptimization() {
  6455. if (this.additionalInitializers === null) {
  6456. this.additionalInitializers = this.init === null ? [] : [this.init];
  6457. this.init = UNKNOWN_EXPRESSION;
  6458. this.isReassigned = true;
  6459. }
  6460. return this.additionalInitializers;
  6461. }
  6462. }
  6463. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  6464. const base = 64;
  6465. function toBase64(value) {
  6466. let outString = '';
  6467. do {
  6468. const currentDigit = value % base;
  6469. value = (value / base) | 0;
  6470. outString = chars[currentDigit] + outString;
  6471. } while (value !== 0);
  6472. return outString;
  6473. }
  6474. function getSafeName(baseName, usedNames, forbiddenNames) {
  6475. let safeName = baseName;
  6476. let count = 1;
  6477. while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName) || forbiddenNames?.has(safeName)) {
  6478. safeName = `${baseName}$${toBase64(count++)}`;
  6479. }
  6480. usedNames.add(safeName);
  6481. return safeName;
  6482. }
  6483. let Scope$1 = class Scope {
  6484. constructor() {
  6485. this.children = [];
  6486. this.variables = new Map();
  6487. }
  6488. addDeclaration(identifier, context, init, _isHoisted) {
  6489. const name = identifier.name;
  6490. let variable = this.variables.get(name);
  6491. if (variable) {
  6492. variable.addDeclaration(identifier, init);
  6493. }
  6494. else {
  6495. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  6496. this.variables.set(name, variable);
  6497. }
  6498. return variable;
  6499. }
  6500. contains(name) {
  6501. return this.variables.has(name);
  6502. }
  6503. findVariable(_name) {
  6504. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  6505. }
  6506. };
  6507. class ChildScope extends Scope$1 {
  6508. constructor(parent) {
  6509. super();
  6510. this.accessedOutsideVariables = new Map();
  6511. this.parent = parent;
  6512. parent.children.push(this);
  6513. }
  6514. addAccessedDynamicImport(importExpression) {
  6515. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  6516. if (this.parent instanceof ChildScope) {
  6517. this.parent.addAccessedDynamicImport(importExpression);
  6518. }
  6519. }
  6520. addAccessedGlobals(globals, accessedGlobalsByScope) {
  6521. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  6522. for (const name of globals) {
  6523. accessedGlobals.add(name);
  6524. }
  6525. accessedGlobalsByScope.set(this, accessedGlobals);
  6526. if (this.parent instanceof ChildScope) {
  6527. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  6528. }
  6529. }
  6530. addNamespaceMemberAccess(name, variable) {
  6531. this.accessedOutsideVariables.set(name, variable);
  6532. this.parent.addNamespaceMemberAccess(name, variable);
  6533. }
  6534. addReturnExpression(expression) {
  6535. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  6536. }
  6537. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  6538. for (const variable of this.accessedOutsideVariables.values()) {
  6539. if (variable.included) {
  6540. usedNames.add(variable.getBaseVariableName());
  6541. if (format === 'system' && exportNamesByVariable.has(variable)) {
  6542. usedNames.add('exports');
  6543. }
  6544. }
  6545. }
  6546. const accessedGlobals = accessedGlobalsByScope.get(this);
  6547. if (accessedGlobals) {
  6548. for (const name of accessedGlobals) {
  6549. usedNames.add(name);
  6550. }
  6551. }
  6552. }
  6553. contains(name) {
  6554. return this.variables.has(name) || this.parent.contains(name);
  6555. }
  6556. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  6557. const usedNames = new Set();
  6558. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  6559. if (this.accessedDynamicImports) {
  6560. for (const importExpression of this.accessedDynamicImports) {
  6561. if (importExpression.inlineNamespace) {
  6562. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  6563. }
  6564. }
  6565. }
  6566. for (const [name, variable] of this.variables) {
  6567. if (variable.included || variable.alwaysRendered) {
  6568. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  6569. }
  6570. }
  6571. for (const scope of this.children) {
  6572. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  6573. }
  6574. }
  6575. findLexicalBoundary() {
  6576. return this.parent.findLexicalBoundary();
  6577. }
  6578. findVariable(name) {
  6579. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  6580. if (knownVariable) {
  6581. return knownVariable;
  6582. }
  6583. const variable = this.parent.findVariable(name);
  6584. this.accessedOutsideVariables.set(name, variable);
  6585. return variable;
  6586. }
  6587. }
  6588. class ParameterScope extends ChildScope {
  6589. constructor(parent, context) {
  6590. super(parent);
  6591. this.parameters = [];
  6592. this.hasRest = false;
  6593. this.context = context;
  6594. this.hoistedBodyVarScope = new ChildScope(this);
  6595. }
  6596. /**
  6597. * Adds a parameter to this scope. Parameters must be added in the correct
  6598. * order, e.g. from left to right.
  6599. */
  6600. addParameterDeclaration(identifier) {
  6601. const name = identifier.name;
  6602. let variable = this.hoistedBodyVarScope.variables.get(name);
  6603. if (variable) {
  6604. variable.addDeclaration(identifier, null);
  6605. }
  6606. else {
  6607. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  6608. }
  6609. this.variables.set(name, variable);
  6610. return variable;
  6611. }
  6612. addParameterVariables(parameters, hasRest) {
  6613. this.parameters = parameters;
  6614. for (const parameterList of parameters) {
  6615. for (const parameter of parameterList) {
  6616. parameter.alwaysRendered = true;
  6617. }
  6618. }
  6619. this.hasRest = hasRest;
  6620. }
  6621. includeCallArguments(context, parameters) {
  6622. let calledFromTryStatement = false;
  6623. let argumentIncluded = false;
  6624. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  6625. for (const checkedArgument of parameters) {
  6626. if (checkedArgument instanceof SpreadElement) {
  6627. for (const argument of parameters) {
  6628. argument.include(context, false);
  6629. }
  6630. break;
  6631. }
  6632. }
  6633. for (let index = parameters.length - 1; index >= 0; index--) {
  6634. const parameterVariables = this.parameters[index] || restParameter;
  6635. const argument = parameters[index];
  6636. if (parameterVariables) {
  6637. calledFromTryStatement = false;
  6638. if (parameterVariables.length === 0) {
  6639. // handle empty destructuring
  6640. argumentIncluded = true;
  6641. }
  6642. else {
  6643. for (const variable of parameterVariables) {
  6644. if (variable.included) {
  6645. argumentIncluded = true;
  6646. }
  6647. if (variable.calledFromTryStatement) {
  6648. calledFromTryStatement = true;
  6649. }
  6650. }
  6651. }
  6652. }
  6653. if (!argumentIncluded && argument.shouldBeIncluded(context)) {
  6654. argumentIncluded = true;
  6655. }
  6656. if (argumentIncluded) {
  6657. argument.include(context, calledFromTryStatement);
  6658. }
  6659. }
  6660. }
  6661. }
  6662. class ReturnValueScope extends ParameterScope {
  6663. constructor() {
  6664. super(...arguments);
  6665. this.returnExpression = null;
  6666. this.returnExpressions = [];
  6667. }
  6668. addReturnExpression(expression) {
  6669. this.returnExpressions.push(expression);
  6670. }
  6671. getReturnExpression() {
  6672. if (this.returnExpression === null)
  6673. this.updateReturnExpression();
  6674. return this.returnExpression;
  6675. }
  6676. updateReturnExpression() {
  6677. if (this.returnExpressions.length === 1) {
  6678. this.returnExpression = this.returnExpressions[0];
  6679. }
  6680. else {
  6681. this.returnExpression = UNKNOWN_EXPRESSION;
  6682. for (const expression of this.returnExpressions) {
  6683. expression.deoptimizePath(UNKNOWN_PATH);
  6684. }
  6685. }
  6686. }
  6687. }
  6688. /** @typedef { import('estree').Node} Node */
  6689. /** @typedef {Node | {
  6690. * type: 'PropertyDefinition';
  6691. * computed: boolean;
  6692. * value: Node
  6693. * }} NodeWithPropertyDefinition */
  6694. /**
  6695. *
  6696. * @param {NodeWithPropertyDefinition} node
  6697. * @param {NodeWithPropertyDefinition} parent
  6698. * @returns {boolean}
  6699. */
  6700. function is_reference (node, parent) {
  6701. if (node.type === 'MemberExpression') {
  6702. return !node.computed && is_reference(node.object, node);
  6703. }
  6704. if (node.type === 'Identifier') {
  6705. if (!parent) return true;
  6706. switch (parent.type) {
  6707. // disregard `bar` in `foo.bar`
  6708. case 'MemberExpression': return parent.computed || node === parent.object;
  6709. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  6710. case 'MethodDefinition': return parent.computed;
  6711. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  6712. case 'PropertyDefinition': return parent.computed || node === parent.value;
  6713. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  6714. case 'Property': return parent.computed || node === parent.value;
  6715. // disregard the `bar` in `export { foo as bar }` or
  6716. // the foo in `import { foo as bar }`
  6717. case 'ExportSpecifier':
  6718. case 'ImportSpecifier': return node === parent.local;
  6719. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  6720. case 'LabeledStatement':
  6721. case 'BreakStatement':
  6722. case 'ContinueStatement': return false;
  6723. default: return true;
  6724. }
  6725. }
  6726. return false;
  6727. }
  6728. const PureFunctionKey = Symbol('PureFunction');
  6729. const getPureFunctions = ({ treeshake }) => {
  6730. const pureFunctions = Object.create(null);
  6731. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  6732. let currentFunctions = pureFunctions;
  6733. for (const pathSegment of functionName.split('.')) {
  6734. currentFunctions = currentFunctions[pathSegment] || (currentFunctions[pathSegment] = Object.create(null));
  6735. }
  6736. currentFunctions[PureFunctionKey] = true;
  6737. }
  6738. return pureFunctions;
  6739. };
  6740. /* eslint sort-keys: "off" */
  6741. const ValueProperties = Symbol('Value Properties');
  6742. const getTruthyLiteralValue = () => UnknownTruthyValue;
  6743. const returnFalse = () => false;
  6744. const returnTrue = () => true;
  6745. const PURE = {
  6746. getLiteralValue: getTruthyLiteralValue,
  6747. hasEffectsWhenCalled: returnFalse
  6748. };
  6749. const IMPURE = {
  6750. getLiteralValue: getTruthyLiteralValue,
  6751. hasEffectsWhenCalled: returnTrue
  6752. };
  6753. // We use shortened variables to reduce file size here
  6754. /* OBJECT */
  6755. const O = {
  6756. __proto__: null,
  6757. [ValueProperties]: IMPURE
  6758. };
  6759. /* PURE FUNCTION */
  6760. const PF = {
  6761. __proto__: null,
  6762. [ValueProperties]: PURE
  6763. };
  6764. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  6765. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  6766. __proto__: null,
  6767. [ValueProperties]: {
  6768. getLiteralValue: getTruthyLiteralValue,
  6769. hasEffectsWhenCalled({ args }, context) {
  6770. return (args.length === 0 ||
  6771. args[0].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  6772. }
  6773. }
  6774. };
  6775. /* CONSTRUCTOR */
  6776. const C = {
  6777. __proto__: null,
  6778. [ValueProperties]: IMPURE,
  6779. prototype: O
  6780. };
  6781. /* PURE CONSTRUCTOR */
  6782. const PC = {
  6783. __proto__: null,
  6784. [ValueProperties]: PURE,
  6785. prototype: O
  6786. };
  6787. const ARRAY_TYPE = {
  6788. __proto__: null,
  6789. [ValueProperties]: PURE,
  6790. from: PF,
  6791. of: PF,
  6792. prototype: O
  6793. };
  6794. const INTL_MEMBER = {
  6795. __proto__: null,
  6796. [ValueProperties]: PURE,
  6797. supportedLocalesOf: PC
  6798. };
  6799. const knownGlobals = {
  6800. // Placeholders for global objects to avoid shape mutations
  6801. global: O,
  6802. globalThis: O,
  6803. self: O,
  6804. window: O,
  6805. // Common globals
  6806. __proto__: null,
  6807. [ValueProperties]: IMPURE,
  6808. Array: {
  6809. __proto__: null,
  6810. [ValueProperties]: IMPURE,
  6811. from: O,
  6812. isArray: PF,
  6813. of: PF,
  6814. prototype: O
  6815. },
  6816. ArrayBuffer: {
  6817. __proto__: null,
  6818. [ValueProperties]: PURE,
  6819. isView: PF,
  6820. prototype: O
  6821. },
  6822. Atomics: O,
  6823. BigInt: C,
  6824. BigInt64Array: C,
  6825. BigUint64Array: C,
  6826. Boolean: PC,
  6827. constructor: C,
  6828. DataView: PC,
  6829. Date: {
  6830. __proto__: null,
  6831. [ValueProperties]: PURE,
  6832. now: PF,
  6833. parse: PF,
  6834. prototype: O,
  6835. UTC: PF
  6836. },
  6837. decodeURI: PF,
  6838. decodeURIComponent: PF,
  6839. encodeURI: PF,
  6840. encodeURIComponent: PF,
  6841. Error: PC,
  6842. escape: PF,
  6843. eval: O,
  6844. EvalError: PC,
  6845. Float32Array: ARRAY_TYPE,
  6846. Float64Array: ARRAY_TYPE,
  6847. Function: C,
  6848. hasOwnProperty: O,
  6849. Infinity: O,
  6850. Int16Array: ARRAY_TYPE,
  6851. Int32Array: ARRAY_TYPE,
  6852. Int8Array: ARRAY_TYPE,
  6853. isFinite: PF,
  6854. isNaN: PF,
  6855. isPrototypeOf: O,
  6856. JSON: O,
  6857. Map: PC,
  6858. Math: {
  6859. __proto__: null,
  6860. [ValueProperties]: IMPURE,
  6861. abs: PF,
  6862. acos: PF,
  6863. acosh: PF,
  6864. asin: PF,
  6865. asinh: PF,
  6866. atan: PF,
  6867. atan2: PF,
  6868. atanh: PF,
  6869. cbrt: PF,
  6870. ceil: PF,
  6871. clz32: PF,
  6872. cos: PF,
  6873. cosh: PF,
  6874. exp: PF,
  6875. expm1: PF,
  6876. floor: PF,
  6877. fround: PF,
  6878. hypot: PF,
  6879. imul: PF,
  6880. log: PF,
  6881. log10: PF,
  6882. log1p: PF,
  6883. log2: PF,
  6884. max: PF,
  6885. min: PF,
  6886. pow: PF,
  6887. random: PF,
  6888. round: PF,
  6889. sign: PF,
  6890. sin: PF,
  6891. sinh: PF,
  6892. sqrt: PF,
  6893. tan: PF,
  6894. tanh: PF,
  6895. trunc: PF
  6896. },
  6897. NaN: O,
  6898. Number: {
  6899. __proto__: null,
  6900. [ValueProperties]: PURE,
  6901. isFinite: PF,
  6902. isInteger: PF,
  6903. isNaN: PF,
  6904. isSafeInteger: PF,
  6905. parseFloat: PF,
  6906. parseInt: PF,
  6907. prototype: O
  6908. },
  6909. Object: {
  6910. __proto__: null,
  6911. [ValueProperties]: PURE,
  6912. create: PF,
  6913. // Technically those can throw in certain situations, but we ignore this as
  6914. // code that relies on this will hopefully wrap this in a try-catch, which
  6915. // deoptimizes everything anyway
  6916. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  6917. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  6918. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  6919. getOwnPropertyDescriptor: PF,
  6920. getOwnPropertyDescriptors: PF,
  6921. getOwnPropertyNames: PF,
  6922. getOwnPropertySymbols: PF,
  6923. getPrototypeOf: PF,
  6924. hasOwn: PF,
  6925. is: PF,
  6926. isExtensible: PF,
  6927. isFrozen: PF,
  6928. isSealed: PF,
  6929. keys: PF,
  6930. fromEntries: PF,
  6931. entries: PF,
  6932. prototype: O
  6933. },
  6934. parseFloat: PF,
  6935. parseInt: PF,
  6936. Promise: {
  6937. __proto__: null,
  6938. [ValueProperties]: IMPURE,
  6939. all: O,
  6940. allSettled: O,
  6941. any: O,
  6942. prototype: O,
  6943. race: O,
  6944. reject: O,
  6945. resolve: O
  6946. },
  6947. propertyIsEnumerable: O,
  6948. Proxy: O,
  6949. RangeError: PC,
  6950. ReferenceError: PC,
  6951. Reflect: O,
  6952. RegExp: PC,
  6953. Set: PC,
  6954. SharedArrayBuffer: C,
  6955. String: {
  6956. __proto__: null,
  6957. [ValueProperties]: PURE,
  6958. fromCharCode: PF,
  6959. fromCodePoint: PF,
  6960. prototype: O,
  6961. raw: PF
  6962. },
  6963. Symbol: {
  6964. __proto__: null,
  6965. [ValueProperties]: PURE,
  6966. for: PF,
  6967. keyFor: PF,
  6968. prototype: O,
  6969. toStringTag: {
  6970. __proto__: null,
  6971. [ValueProperties]: {
  6972. getLiteralValue() {
  6973. return SymbolToStringTag;
  6974. },
  6975. hasEffectsWhenCalled: returnTrue
  6976. }
  6977. }
  6978. },
  6979. SyntaxError: PC,
  6980. toLocaleString: O,
  6981. toString: O,
  6982. TypeError: PC,
  6983. Uint16Array: ARRAY_TYPE,
  6984. Uint32Array: ARRAY_TYPE,
  6985. Uint8Array: ARRAY_TYPE,
  6986. Uint8ClampedArray: ARRAY_TYPE,
  6987. // Technically, this is a global, but it needs special handling
  6988. // undefined: ?,
  6989. unescape: PF,
  6990. URIError: PC,
  6991. valueOf: O,
  6992. WeakMap: PC,
  6993. WeakSet: PC,
  6994. // Additional globals shared by Node and Browser that are not strictly part of the language
  6995. clearInterval: C,
  6996. clearTimeout: C,
  6997. console: O,
  6998. Intl: {
  6999. __proto__: null,
  7000. [ValueProperties]: IMPURE,
  7001. Collator: INTL_MEMBER,
  7002. DateTimeFormat: INTL_MEMBER,
  7003. ListFormat: INTL_MEMBER,
  7004. NumberFormat: INTL_MEMBER,
  7005. PluralRules: INTL_MEMBER,
  7006. RelativeTimeFormat: INTL_MEMBER
  7007. },
  7008. setInterval: C,
  7009. setTimeout: C,
  7010. TextDecoder: C,
  7011. TextEncoder: C,
  7012. URL: C,
  7013. URLSearchParams: C,
  7014. // Browser specific globals
  7015. AbortController: C,
  7016. AbortSignal: C,
  7017. addEventListener: O,
  7018. alert: O,
  7019. AnalyserNode: C,
  7020. Animation: C,
  7021. AnimationEvent: C,
  7022. applicationCache: O,
  7023. ApplicationCache: C,
  7024. ApplicationCacheErrorEvent: C,
  7025. atob: O,
  7026. Attr: C,
  7027. Audio: C,
  7028. AudioBuffer: C,
  7029. AudioBufferSourceNode: C,
  7030. AudioContext: C,
  7031. AudioDestinationNode: C,
  7032. AudioListener: C,
  7033. AudioNode: C,
  7034. AudioParam: C,
  7035. AudioProcessingEvent: C,
  7036. AudioScheduledSourceNode: C,
  7037. AudioWorkletNode: C,
  7038. BarProp: C,
  7039. BaseAudioContext: C,
  7040. BatteryManager: C,
  7041. BeforeUnloadEvent: C,
  7042. BiquadFilterNode: C,
  7043. Blob: C,
  7044. BlobEvent: C,
  7045. blur: O,
  7046. BroadcastChannel: C,
  7047. btoa: O,
  7048. ByteLengthQueuingStrategy: C,
  7049. Cache: C,
  7050. caches: O,
  7051. CacheStorage: C,
  7052. cancelAnimationFrame: O,
  7053. cancelIdleCallback: O,
  7054. CanvasCaptureMediaStreamTrack: C,
  7055. CanvasGradient: C,
  7056. CanvasPattern: C,
  7057. CanvasRenderingContext2D: C,
  7058. ChannelMergerNode: C,
  7059. ChannelSplitterNode: C,
  7060. CharacterData: C,
  7061. clientInformation: O,
  7062. ClipboardEvent: C,
  7063. close: O,
  7064. closed: O,
  7065. CloseEvent: C,
  7066. Comment: C,
  7067. CompositionEvent: C,
  7068. confirm: O,
  7069. ConstantSourceNode: C,
  7070. ConvolverNode: C,
  7071. CountQueuingStrategy: C,
  7072. createImageBitmap: O,
  7073. Credential: C,
  7074. CredentialsContainer: C,
  7075. crypto: O,
  7076. Crypto: C,
  7077. CryptoKey: C,
  7078. CSS: C,
  7079. CSSConditionRule: C,
  7080. CSSFontFaceRule: C,
  7081. CSSGroupingRule: C,
  7082. CSSImportRule: C,
  7083. CSSKeyframeRule: C,
  7084. CSSKeyframesRule: C,
  7085. CSSMediaRule: C,
  7086. CSSNamespaceRule: C,
  7087. CSSPageRule: C,
  7088. CSSRule: C,
  7089. CSSRuleList: C,
  7090. CSSStyleDeclaration: C,
  7091. CSSStyleRule: C,
  7092. CSSStyleSheet: C,
  7093. CSSSupportsRule: C,
  7094. CustomElementRegistry: C,
  7095. customElements: O,
  7096. CustomEvent: C,
  7097. DataTransfer: C,
  7098. DataTransferItem: C,
  7099. DataTransferItemList: C,
  7100. defaultstatus: O,
  7101. defaultStatus: O,
  7102. DelayNode: C,
  7103. DeviceMotionEvent: C,
  7104. DeviceOrientationEvent: C,
  7105. devicePixelRatio: O,
  7106. dispatchEvent: O,
  7107. document: O,
  7108. Document: C,
  7109. DocumentFragment: C,
  7110. DocumentType: C,
  7111. DOMError: C,
  7112. DOMException: C,
  7113. DOMImplementation: C,
  7114. DOMMatrix: C,
  7115. DOMMatrixReadOnly: C,
  7116. DOMParser: C,
  7117. DOMPoint: C,
  7118. DOMPointReadOnly: C,
  7119. DOMQuad: C,
  7120. DOMRect: C,
  7121. DOMRectReadOnly: C,
  7122. DOMStringList: C,
  7123. DOMStringMap: C,
  7124. DOMTokenList: C,
  7125. DragEvent: C,
  7126. DynamicsCompressorNode: C,
  7127. Element: C,
  7128. ErrorEvent: C,
  7129. Event: C,
  7130. EventSource: C,
  7131. EventTarget: C,
  7132. external: O,
  7133. fetch: O,
  7134. File: C,
  7135. FileList: C,
  7136. FileReader: C,
  7137. find: O,
  7138. focus: O,
  7139. FocusEvent: C,
  7140. FontFace: C,
  7141. FontFaceSetLoadEvent: C,
  7142. FormData: C,
  7143. frames: O,
  7144. GainNode: C,
  7145. Gamepad: C,
  7146. GamepadButton: C,
  7147. GamepadEvent: C,
  7148. getComputedStyle: O,
  7149. getSelection: O,
  7150. HashChangeEvent: C,
  7151. Headers: C,
  7152. history: O,
  7153. History: C,
  7154. HTMLAllCollection: C,
  7155. HTMLAnchorElement: C,
  7156. HTMLAreaElement: C,
  7157. HTMLAudioElement: C,
  7158. HTMLBaseElement: C,
  7159. HTMLBodyElement: C,
  7160. HTMLBRElement: C,
  7161. HTMLButtonElement: C,
  7162. HTMLCanvasElement: C,
  7163. HTMLCollection: C,
  7164. HTMLContentElement: C,
  7165. HTMLDataElement: C,
  7166. HTMLDataListElement: C,
  7167. HTMLDetailsElement: C,
  7168. HTMLDialogElement: C,
  7169. HTMLDirectoryElement: C,
  7170. HTMLDivElement: C,
  7171. HTMLDListElement: C,
  7172. HTMLDocument: C,
  7173. HTMLElement: C,
  7174. HTMLEmbedElement: C,
  7175. HTMLFieldSetElement: C,
  7176. HTMLFontElement: C,
  7177. HTMLFormControlsCollection: C,
  7178. HTMLFormElement: C,
  7179. HTMLFrameElement: C,
  7180. HTMLFrameSetElement: C,
  7181. HTMLHeadElement: C,
  7182. HTMLHeadingElement: C,
  7183. HTMLHRElement: C,
  7184. HTMLHtmlElement: C,
  7185. HTMLIFrameElement: C,
  7186. HTMLImageElement: C,
  7187. HTMLInputElement: C,
  7188. HTMLLabelElement: C,
  7189. HTMLLegendElement: C,
  7190. HTMLLIElement: C,
  7191. HTMLLinkElement: C,
  7192. HTMLMapElement: C,
  7193. HTMLMarqueeElement: C,
  7194. HTMLMediaElement: C,
  7195. HTMLMenuElement: C,
  7196. HTMLMetaElement: C,
  7197. HTMLMeterElement: C,
  7198. HTMLModElement: C,
  7199. HTMLObjectElement: C,
  7200. HTMLOListElement: C,
  7201. HTMLOptGroupElement: C,
  7202. HTMLOptionElement: C,
  7203. HTMLOptionsCollection: C,
  7204. HTMLOutputElement: C,
  7205. HTMLParagraphElement: C,
  7206. HTMLParamElement: C,
  7207. HTMLPictureElement: C,
  7208. HTMLPreElement: C,
  7209. HTMLProgressElement: C,
  7210. HTMLQuoteElement: C,
  7211. HTMLScriptElement: C,
  7212. HTMLSelectElement: C,
  7213. HTMLShadowElement: C,
  7214. HTMLSlotElement: C,
  7215. HTMLSourceElement: C,
  7216. HTMLSpanElement: C,
  7217. HTMLStyleElement: C,
  7218. HTMLTableCaptionElement: C,
  7219. HTMLTableCellElement: C,
  7220. HTMLTableColElement: C,
  7221. HTMLTableElement: C,
  7222. HTMLTableRowElement: C,
  7223. HTMLTableSectionElement: C,
  7224. HTMLTemplateElement: C,
  7225. HTMLTextAreaElement: C,
  7226. HTMLTimeElement: C,
  7227. HTMLTitleElement: C,
  7228. HTMLTrackElement: C,
  7229. HTMLUListElement: C,
  7230. HTMLUnknownElement: C,
  7231. HTMLVideoElement: C,
  7232. IDBCursor: C,
  7233. IDBCursorWithValue: C,
  7234. IDBDatabase: C,
  7235. IDBFactory: C,
  7236. IDBIndex: C,
  7237. IDBKeyRange: C,
  7238. IDBObjectStore: C,
  7239. IDBOpenDBRequest: C,
  7240. IDBRequest: C,
  7241. IDBTransaction: C,
  7242. IDBVersionChangeEvent: C,
  7243. IdleDeadline: C,
  7244. IIRFilterNode: C,
  7245. Image: C,
  7246. ImageBitmap: C,
  7247. ImageBitmapRenderingContext: C,
  7248. ImageCapture: C,
  7249. ImageData: C,
  7250. indexedDB: O,
  7251. innerHeight: O,
  7252. innerWidth: O,
  7253. InputEvent: C,
  7254. IntersectionObserver: C,
  7255. IntersectionObserverEntry: C,
  7256. isSecureContext: O,
  7257. KeyboardEvent: C,
  7258. KeyframeEffect: C,
  7259. length: O,
  7260. localStorage: O,
  7261. location: O,
  7262. Location: C,
  7263. locationbar: O,
  7264. matchMedia: O,
  7265. MediaDeviceInfo: C,
  7266. MediaDevices: C,
  7267. MediaElementAudioSourceNode: C,
  7268. MediaEncryptedEvent: C,
  7269. MediaError: C,
  7270. MediaKeyMessageEvent: C,
  7271. MediaKeySession: C,
  7272. MediaKeyStatusMap: C,
  7273. MediaKeySystemAccess: C,
  7274. MediaList: C,
  7275. MediaQueryList: C,
  7276. MediaQueryListEvent: C,
  7277. MediaRecorder: C,
  7278. MediaSettingsRange: C,
  7279. MediaSource: C,
  7280. MediaStream: C,
  7281. MediaStreamAudioDestinationNode: C,
  7282. MediaStreamAudioSourceNode: C,
  7283. MediaStreamEvent: C,
  7284. MediaStreamTrack: C,
  7285. MediaStreamTrackEvent: C,
  7286. menubar: O,
  7287. MessageChannel: C,
  7288. MessageEvent: C,
  7289. MessagePort: C,
  7290. MIDIAccess: C,
  7291. MIDIConnectionEvent: C,
  7292. MIDIInput: C,
  7293. MIDIInputMap: C,
  7294. MIDIMessageEvent: C,
  7295. MIDIOutput: C,
  7296. MIDIOutputMap: C,
  7297. MIDIPort: C,
  7298. MimeType: C,
  7299. MimeTypeArray: C,
  7300. MouseEvent: C,
  7301. moveBy: O,
  7302. moveTo: O,
  7303. MutationEvent: C,
  7304. MutationObserver: C,
  7305. MutationRecord: C,
  7306. name: O,
  7307. NamedNodeMap: C,
  7308. NavigationPreloadManager: C,
  7309. navigator: O,
  7310. Navigator: C,
  7311. NetworkInformation: C,
  7312. Node: C,
  7313. NodeFilter: O,
  7314. NodeIterator: C,
  7315. NodeList: C,
  7316. Notification: C,
  7317. OfflineAudioCompletionEvent: C,
  7318. OfflineAudioContext: C,
  7319. offscreenBuffering: O,
  7320. OffscreenCanvas: C,
  7321. open: O,
  7322. openDatabase: O,
  7323. Option: C,
  7324. origin: O,
  7325. OscillatorNode: C,
  7326. outerHeight: O,
  7327. outerWidth: O,
  7328. PageTransitionEvent: C,
  7329. pageXOffset: O,
  7330. pageYOffset: O,
  7331. PannerNode: C,
  7332. parent: O,
  7333. Path2D: C,
  7334. PaymentAddress: C,
  7335. PaymentRequest: C,
  7336. PaymentRequestUpdateEvent: C,
  7337. PaymentResponse: C,
  7338. performance: O,
  7339. Performance: C,
  7340. PerformanceEntry: C,
  7341. PerformanceLongTaskTiming: C,
  7342. PerformanceMark: C,
  7343. PerformanceMeasure: C,
  7344. PerformanceNavigation: C,
  7345. PerformanceNavigationTiming: C,
  7346. PerformanceObserver: C,
  7347. PerformanceObserverEntryList: C,
  7348. PerformancePaintTiming: C,
  7349. PerformanceResourceTiming: C,
  7350. PerformanceTiming: C,
  7351. PeriodicWave: C,
  7352. Permissions: C,
  7353. PermissionStatus: C,
  7354. personalbar: O,
  7355. PhotoCapabilities: C,
  7356. Plugin: C,
  7357. PluginArray: C,
  7358. PointerEvent: C,
  7359. PopStateEvent: C,
  7360. postMessage: O,
  7361. Presentation: C,
  7362. PresentationAvailability: C,
  7363. PresentationConnection: C,
  7364. PresentationConnectionAvailableEvent: C,
  7365. PresentationConnectionCloseEvent: C,
  7366. PresentationConnectionList: C,
  7367. PresentationReceiver: C,
  7368. PresentationRequest: C,
  7369. print: O,
  7370. ProcessingInstruction: C,
  7371. ProgressEvent: C,
  7372. PromiseRejectionEvent: C,
  7373. prompt: O,
  7374. PushManager: C,
  7375. PushSubscription: C,
  7376. PushSubscriptionOptions: C,
  7377. queueMicrotask: O,
  7378. RadioNodeList: C,
  7379. Range: C,
  7380. ReadableStream: C,
  7381. RemotePlayback: C,
  7382. removeEventListener: O,
  7383. Request: C,
  7384. requestAnimationFrame: O,
  7385. requestIdleCallback: O,
  7386. resizeBy: O,
  7387. ResizeObserver: C,
  7388. ResizeObserverEntry: C,
  7389. resizeTo: O,
  7390. Response: C,
  7391. RTCCertificate: C,
  7392. RTCDataChannel: C,
  7393. RTCDataChannelEvent: C,
  7394. RTCDtlsTransport: C,
  7395. RTCIceCandidate: C,
  7396. RTCIceTransport: C,
  7397. RTCPeerConnection: C,
  7398. RTCPeerConnectionIceEvent: C,
  7399. RTCRtpReceiver: C,
  7400. RTCRtpSender: C,
  7401. RTCSctpTransport: C,
  7402. RTCSessionDescription: C,
  7403. RTCStatsReport: C,
  7404. RTCTrackEvent: C,
  7405. screen: O,
  7406. Screen: C,
  7407. screenLeft: O,
  7408. ScreenOrientation: C,
  7409. screenTop: O,
  7410. screenX: O,
  7411. screenY: O,
  7412. ScriptProcessorNode: C,
  7413. scroll: O,
  7414. scrollbars: O,
  7415. scrollBy: O,
  7416. scrollTo: O,
  7417. scrollX: O,
  7418. scrollY: O,
  7419. SecurityPolicyViolationEvent: C,
  7420. Selection: C,
  7421. ServiceWorker: C,
  7422. ServiceWorkerContainer: C,
  7423. ServiceWorkerRegistration: C,
  7424. sessionStorage: O,
  7425. ShadowRoot: C,
  7426. SharedWorker: C,
  7427. SourceBuffer: C,
  7428. SourceBufferList: C,
  7429. speechSynthesis: O,
  7430. SpeechSynthesisEvent: C,
  7431. SpeechSynthesisUtterance: C,
  7432. StaticRange: C,
  7433. status: O,
  7434. statusbar: O,
  7435. StereoPannerNode: C,
  7436. stop: O,
  7437. Storage: C,
  7438. StorageEvent: C,
  7439. StorageManager: C,
  7440. styleMedia: O,
  7441. StyleSheet: C,
  7442. StyleSheetList: C,
  7443. SubtleCrypto: C,
  7444. SVGAElement: C,
  7445. SVGAngle: C,
  7446. SVGAnimatedAngle: C,
  7447. SVGAnimatedBoolean: C,
  7448. SVGAnimatedEnumeration: C,
  7449. SVGAnimatedInteger: C,
  7450. SVGAnimatedLength: C,
  7451. SVGAnimatedLengthList: C,
  7452. SVGAnimatedNumber: C,
  7453. SVGAnimatedNumberList: C,
  7454. SVGAnimatedPreserveAspectRatio: C,
  7455. SVGAnimatedRect: C,
  7456. SVGAnimatedString: C,
  7457. SVGAnimatedTransformList: C,
  7458. SVGAnimateElement: C,
  7459. SVGAnimateMotionElement: C,
  7460. SVGAnimateTransformElement: C,
  7461. SVGAnimationElement: C,
  7462. SVGCircleElement: C,
  7463. SVGClipPathElement: C,
  7464. SVGComponentTransferFunctionElement: C,
  7465. SVGDefsElement: C,
  7466. SVGDescElement: C,
  7467. SVGDiscardElement: C,
  7468. SVGElement: C,
  7469. SVGEllipseElement: C,
  7470. SVGFEBlendElement: C,
  7471. SVGFEColorMatrixElement: C,
  7472. SVGFEComponentTransferElement: C,
  7473. SVGFECompositeElement: C,
  7474. SVGFEConvolveMatrixElement: C,
  7475. SVGFEDiffuseLightingElement: C,
  7476. SVGFEDisplacementMapElement: C,
  7477. SVGFEDistantLightElement: C,
  7478. SVGFEDropShadowElement: C,
  7479. SVGFEFloodElement: C,
  7480. SVGFEFuncAElement: C,
  7481. SVGFEFuncBElement: C,
  7482. SVGFEFuncGElement: C,
  7483. SVGFEFuncRElement: C,
  7484. SVGFEGaussianBlurElement: C,
  7485. SVGFEImageElement: C,
  7486. SVGFEMergeElement: C,
  7487. SVGFEMergeNodeElement: C,
  7488. SVGFEMorphologyElement: C,
  7489. SVGFEOffsetElement: C,
  7490. SVGFEPointLightElement: C,
  7491. SVGFESpecularLightingElement: C,
  7492. SVGFESpotLightElement: C,
  7493. SVGFETileElement: C,
  7494. SVGFETurbulenceElement: C,
  7495. SVGFilterElement: C,
  7496. SVGForeignObjectElement: C,
  7497. SVGGElement: C,
  7498. SVGGeometryElement: C,
  7499. SVGGradientElement: C,
  7500. SVGGraphicsElement: C,
  7501. SVGImageElement: C,
  7502. SVGLength: C,
  7503. SVGLengthList: C,
  7504. SVGLinearGradientElement: C,
  7505. SVGLineElement: C,
  7506. SVGMarkerElement: C,
  7507. SVGMaskElement: C,
  7508. SVGMatrix: C,
  7509. SVGMetadataElement: C,
  7510. SVGMPathElement: C,
  7511. SVGNumber: C,
  7512. SVGNumberList: C,
  7513. SVGPathElement: C,
  7514. SVGPatternElement: C,
  7515. SVGPoint: C,
  7516. SVGPointList: C,
  7517. SVGPolygonElement: C,
  7518. SVGPolylineElement: C,
  7519. SVGPreserveAspectRatio: C,
  7520. SVGRadialGradientElement: C,
  7521. SVGRect: C,
  7522. SVGRectElement: C,
  7523. SVGScriptElement: C,
  7524. SVGSetElement: C,
  7525. SVGStopElement: C,
  7526. SVGStringList: C,
  7527. SVGStyleElement: C,
  7528. SVGSVGElement: C,
  7529. SVGSwitchElement: C,
  7530. SVGSymbolElement: C,
  7531. SVGTextContentElement: C,
  7532. SVGTextElement: C,
  7533. SVGTextPathElement: C,
  7534. SVGTextPositioningElement: C,
  7535. SVGTitleElement: C,
  7536. SVGTransform: C,
  7537. SVGTransformList: C,
  7538. SVGTSpanElement: C,
  7539. SVGUnitTypes: C,
  7540. SVGUseElement: C,
  7541. SVGViewElement: C,
  7542. TaskAttributionTiming: C,
  7543. Text: C,
  7544. TextEvent: C,
  7545. TextMetrics: C,
  7546. TextTrack: C,
  7547. TextTrackCue: C,
  7548. TextTrackCueList: C,
  7549. TextTrackList: C,
  7550. TimeRanges: C,
  7551. toolbar: O,
  7552. top: O,
  7553. Touch: C,
  7554. TouchEvent: C,
  7555. TouchList: C,
  7556. TrackEvent: C,
  7557. TransitionEvent: C,
  7558. TreeWalker: C,
  7559. UIEvent: C,
  7560. ValidityState: C,
  7561. visualViewport: O,
  7562. VisualViewport: C,
  7563. VTTCue: C,
  7564. WaveShaperNode: C,
  7565. WebAssembly: O,
  7566. WebGL2RenderingContext: C,
  7567. WebGLActiveInfo: C,
  7568. WebGLBuffer: C,
  7569. WebGLContextEvent: C,
  7570. WebGLFramebuffer: C,
  7571. WebGLProgram: C,
  7572. WebGLQuery: C,
  7573. WebGLRenderbuffer: C,
  7574. WebGLRenderingContext: C,
  7575. WebGLSampler: C,
  7576. WebGLShader: C,
  7577. WebGLShaderPrecisionFormat: C,
  7578. WebGLSync: C,
  7579. WebGLTexture: C,
  7580. WebGLTransformFeedback: C,
  7581. WebGLUniformLocation: C,
  7582. WebGLVertexArrayObject: C,
  7583. WebSocket: C,
  7584. WheelEvent: C,
  7585. Window: C,
  7586. Worker: C,
  7587. WritableStream: C,
  7588. XMLDocument: C,
  7589. XMLHttpRequest: C,
  7590. XMLHttpRequestEventTarget: C,
  7591. XMLHttpRequestUpload: C,
  7592. XMLSerializer: C,
  7593. XPathEvaluator: C,
  7594. XPathExpression: C,
  7595. XPathResult: C,
  7596. XSLTProcessor: C
  7597. };
  7598. for (const global of ['window', 'global', 'self', 'globalThis']) {
  7599. knownGlobals[global] = knownGlobals;
  7600. }
  7601. function getGlobalAtPath(path) {
  7602. let currentGlobal = knownGlobals;
  7603. for (const pathSegment of path) {
  7604. if (typeof pathSegment !== 'string') {
  7605. return null;
  7606. }
  7607. currentGlobal = currentGlobal[pathSegment];
  7608. if (!currentGlobal) {
  7609. return null;
  7610. }
  7611. }
  7612. return currentGlobal[ValueProperties];
  7613. }
  7614. class GlobalVariable extends Variable {
  7615. constructor() {
  7616. super(...arguments);
  7617. // Ensure we use live-bindings for globals as we do not know if they have
  7618. // been reassigned
  7619. this.isReassigned = true;
  7620. }
  7621. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  7622. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7623. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  7624. }
  7625. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7626. switch (interaction.type) {
  7627. case INTERACTION_ACCESSED: {
  7628. if (path.length === 0) {
  7629. // Technically, "undefined" is a global variable of sorts
  7630. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  7631. }
  7632. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  7633. }
  7634. case INTERACTION_ASSIGNED: {
  7635. return true;
  7636. }
  7637. case INTERACTION_CALLED: {
  7638. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7639. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  7640. }
  7641. }
  7642. }
  7643. }
  7644. const tdzVariableKinds = {
  7645. __proto__: null,
  7646. class: true,
  7647. const: true,
  7648. let: true,
  7649. var: true
  7650. };
  7651. class Identifier extends NodeBase {
  7652. constructor() {
  7653. super(...arguments);
  7654. this.variable = null;
  7655. this.isTDZAccess = null;
  7656. }
  7657. addExportedVariables(variables, exportNamesByVariable) {
  7658. if (exportNamesByVariable.has(this.variable)) {
  7659. variables.push(this.variable);
  7660. }
  7661. }
  7662. bind() {
  7663. if (!this.variable && is_reference(this, this.parent)) {
  7664. this.variable = this.scope.findVariable(this.name);
  7665. this.variable.addReference(this);
  7666. }
  7667. }
  7668. declare(kind, init) {
  7669. let variable;
  7670. const { treeshake } = this.context.options;
  7671. switch (kind) {
  7672. case 'var': {
  7673. variable = this.scope.addDeclaration(this, this.context, init, true);
  7674. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  7675. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  7676. variable.markInitializersForDeoptimization();
  7677. }
  7678. break;
  7679. }
  7680. case 'function': {
  7681. // in strict mode, functions are only hoisted within a scope but not across block scopes
  7682. variable = this.scope.addDeclaration(this, this.context, init, false);
  7683. break;
  7684. }
  7685. case 'let':
  7686. case 'const':
  7687. case 'class': {
  7688. variable = this.scope.addDeclaration(this, this.context, init, false);
  7689. break;
  7690. }
  7691. case 'parameter': {
  7692. variable = this.scope.addParameterDeclaration(this);
  7693. break;
  7694. }
  7695. /* istanbul ignore next */
  7696. default: {
  7697. /* istanbul ignore next */
  7698. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  7699. }
  7700. }
  7701. variable.kind = kind;
  7702. return [(this.variable = variable)];
  7703. }
  7704. deoptimizePath(path) {
  7705. if (path.length === 0 && !this.scope.contains(this.name)) {
  7706. this.disallowImportReassignment();
  7707. }
  7708. // We keep conditional chaining because an unknown Node could have an
  7709. // Identifier as property that might be deoptimized by default
  7710. this.variable?.deoptimizePath(path);
  7711. }
  7712. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7713. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7714. }
  7715. getLiteralValueAtPath(path, recursionTracker, origin) {
  7716. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  7717. }
  7718. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7719. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7720. return [expression, isPure || this.isPureFunction(path)];
  7721. }
  7722. hasEffects(context) {
  7723. if (!this.deoptimized)
  7724. this.applyDeoptimizations();
  7725. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  7726. return true;
  7727. }
  7728. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  7729. this.variable instanceof GlobalVariable &&
  7730. !this.isPureFunction(EMPTY_PATH) &&
  7731. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  7732. }
  7733. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7734. switch (interaction.type) {
  7735. case INTERACTION_ACCESSED: {
  7736. return (this.variable !== null &&
  7737. !this.isPureFunction(path) &&
  7738. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  7739. }
  7740. case INTERACTION_ASSIGNED: {
  7741. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  7742. }
  7743. case INTERACTION_CALLED: {
  7744. return (!this.isPureFunction(path) &&
  7745. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  7746. }
  7747. }
  7748. }
  7749. include() {
  7750. if (!this.deoptimized)
  7751. this.applyDeoptimizations();
  7752. if (!this.included) {
  7753. this.included = true;
  7754. if (this.variable !== null) {
  7755. this.context.includeVariableInModule(this.variable);
  7756. }
  7757. }
  7758. }
  7759. includeCallArguments(context, parameters) {
  7760. this.variable.includeCallArguments(context, parameters);
  7761. }
  7762. isPossibleTDZ() {
  7763. // return cached value to avoid issues with the next tree-shaking pass
  7764. if (this.isTDZAccess !== null)
  7765. return this.isTDZAccess;
  7766. if (!(this.variable instanceof LocalVariable &&
  7767. this.variable.kind &&
  7768. this.variable.kind in tdzVariableKinds &&
  7769. // we ignore possible TDZs due to circular module dependencies as
  7770. // otherwise we get many false positives
  7771. this.variable.module === this.context.module)) {
  7772. return (this.isTDZAccess = false);
  7773. }
  7774. let decl_id;
  7775. if (this.variable.declarations &&
  7776. this.variable.declarations.length === 1 &&
  7777. (decl_id = this.variable.declarations[0]) &&
  7778. this.start < decl_id.start &&
  7779. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  7780. // a variable accessed before its declaration
  7781. // in the same function or at top level of module
  7782. return (this.isTDZAccess = true);
  7783. }
  7784. if (!this.variable.initReached) {
  7785. // Either a const/let TDZ violation or
  7786. // var use before declaration was encountered.
  7787. return (this.isTDZAccess = true);
  7788. }
  7789. return (this.isTDZAccess = false);
  7790. }
  7791. markDeclarationReached() {
  7792. this.variable.initReached = true;
  7793. }
  7794. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  7795. if (this.variable) {
  7796. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  7797. if (name !== this.name) {
  7798. code.overwrite(this.start, this.end, name, {
  7799. contentOnly: true,
  7800. storeName: true
  7801. });
  7802. if (isShorthandProperty) {
  7803. code.prependRight(this.start, `${this.name}: `);
  7804. }
  7805. }
  7806. // In strict mode, any variable named "eval" must be the actual "eval" function
  7807. if (name === 'eval' &&
  7808. renderedParentType === CallExpression$1 &&
  7809. isCalleeOfRenderedParent) {
  7810. code.appendRight(this.start, '0, ');
  7811. }
  7812. }
  7813. }
  7814. applyDeoptimizations() {
  7815. this.deoptimized = true;
  7816. if (this.variable instanceof LocalVariable) {
  7817. this.variable.consolidateInitializers();
  7818. this.context.requestTreeshakingPass();
  7819. }
  7820. }
  7821. disallowImportReassignment() {
  7822. return this.context.error(errorIllegalImportReassignment(this.name, this.context.module.id), this.start);
  7823. }
  7824. getVariableRespectingTDZ() {
  7825. if (this.isPossibleTDZ()) {
  7826. return UNKNOWN_EXPRESSION;
  7827. }
  7828. return this.variable;
  7829. }
  7830. isPureFunction(path) {
  7831. let currentPureFunction = this.context.manualPureFunctions[this.name];
  7832. for (const segment of path) {
  7833. if (currentPureFunction) {
  7834. if (currentPureFunction[PureFunctionKey]) {
  7835. return true;
  7836. }
  7837. currentPureFunction = currentPureFunction[segment];
  7838. }
  7839. else {
  7840. return false;
  7841. }
  7842. }
  7843. return currentPureFunction?.[PureFunctionKey];
  7844. }
  7845. }
  7846. function closestParentFunctionOrProgram(node) {
  7847. while (node && !/^Program|Function/.test(node.type)) {
  7848. node = node.parent;
  7849. }
  7850. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  7851. return node;
  7852. }
  7853. function treeshakeNode(node, code, start, end) {
  7854. code.remove(start, end);
  7855. if (node.annotations) {
  7856. for (const annotation of node.annotations) {
  7857. if (annotation.start < start) {
  7858. code.remove(annotation.start, annotation.end);
  7859. }
  7860. else {
  7861. return;
  7862. }
  7863. }
  7864. }
  7865. }
  7866. function removeAnnotations(node, code) {
  7867. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  7868. node = node.parent;
  7869. }
  7870. if (node.annotations) {
  7871. for (const annotation of node.annotations) {
  7872. code.remove(annotation.start, annotation.end);
  7873. }
  7874. }
  7875. }
  7876. const NO_SEMICOLON = { isNoStatement: true };
  7877. // This assumes there are only white-space and comments between start and the string we are looking for
  7878. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  7879. let searchPos, charCodeAfterSlash;
  7880. searchPos = code.indexOf(searchString, start);
  7881. while (true) {
  7882. start = code.indexOf('/', start);
  7883. if (start === -1 || start >= searchPos)
  7884. return searchPos;
  7885. charCodeAfterSlash = code.charCodeAt(++start);
  7886. ++start;
  7887. // With our assumption, '/' always starts a comment. Determine comment type:
  7888. start =
  7889. charCodeAfterSlash === 47 /*"/"*/
  7890. ? code.indexOf('\n', start) + 1
  7891. : code.indexOf('*/', start) + 2;
  7892. if (start > searchPos) {
  7893. searchPos = code.indexOf(searchString, start);
  7894. }
  7895. }
  7896. }
  7897. const NON_WHITESPACE = /\S/g;
  7898. function findNonWhiteSpace(code, index) {
  7899. NON_WHITESPACE.lastIndex = index;
  7900. const result = NON_WHITESPACE.exec(code);
  7901. return result.index;
  7902. }
  7903. // This assumes "code" only contains white-space and comments
  7904. // Returns position of line-comment if applicable
  7905. function findFirstLineBreakOutsideComment(code) {
  7906. let lineBreakPos, charCodeAfterSlash, start = 0;
  7907. lineBreakPos = code.indexOf('\n', start);
  7908. while (true) {
  7909. start = code.indexOf('/', start);
  7910. if (start === -1 || start > lineBreakPos)
  7911. return [lineBreakPos, lineBreakPos + 1];
  7912. // With our assumption, '/' always starts a comment. Determine comment type:
  7913. charCodeAfterSlash = code.charCodeAt(start + 1);
  7914. if (charCodeAfterSlash === 47 /*"/"*/)
  7915. return [start, lineBreakPos + 1];
  7916. start = code.indexOf('*/', start + 3) + 2;
  7917. if (start > lineBreakPos) {
  7918. lineBreakPos = code.indexOf('\n', start);
  7919. }
  7920. }
  7921. }
  7922. function renderStatementList(statements, code, start, end, options) {
  7923. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  7924. let nextNode = statements[0];
  7925. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  7926. if (nextNodeNeedsBoundaries) {
  7927. nextNodeStart =
  7928. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  7929. }
  7930. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  7931. currentNode = nextNode;
  7932. currentNodeStart = nextNodeStart;
  7933. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  7934. nextNode = statements[nextIndex];
  7935. nextNodeNeedsBoundaries =
  7936. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  7937. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  7938. nextNodeStart =
  7939. currentNode.end +
  7940. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  7941. if (currentNode.included) {
  7942. currentNodeNeedsBoundaries
  7943. ? currentNode.render(code, options, {
  7944. end: nextNodeStart,
  7945. start: currentNodeStart
  7946. })
  7947. : currentNode.render(code, options);
  7948. }
  7949. else {
  7950. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  7951. }
  7952. }
  7953. else {
  7954. currentNode.render(code, options);
  7955. }
  7956. }
  7957. }
  7958. // This assumes that the first character is not part of the first node
  7959. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  7960. const splitUpNodes = [];
  7961. let node, nextNodeStart, contentEnd, char;
  7962. let separator = start - 1;
  7963. for (const nextNode of nodes) {
  7964. if (node !== undefined) {
  7965. separator =
  7966. node.end +
  7967. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  7968. }
  7969. nextNodeStart = contentEnd =
  7970. separator +
  7971. 1 +
  7972. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  7973. while (((char = code.original.charCodeAt(nextNodeStart)),
  7974. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  7975. nextNodeStart++;
  7976. if (node !== undefined) {
  7977. splitUpNodes.push({
  7978. contentEnd,
  7979. end: nextNodeStart,
  7980. node,
  7981. separator,
  7982. start
  7983. });
  7984. }
  7985. node = nextNode;
  7986. start = nextNodeStart;
  7987. }
  7988. splitUpNodes.push({
  7989. contentEnd: end,
  7990. end,
  7991. node: node,
  7992. separator: null,
  7993. start
  7994. });
  7995. return splitUpNodes;
  7996. }
  7997. // This assumes there are only white-space and comments between start and end
  7998. function removeLineBreaks(code, start, end) {
  7999. while (true) {
  8000. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  8001. if (removeStart === -1) {
  8002. break;
  8003. }
  8004. code.remove(start + removeStart, (start += removeEnd));
  8005. }
  8006. }
  8007. class BlockScope extends ChildScope {
  8008. addDeclaration(identifier, context, init, isHoisted) {
  8009. if (isHoisted) {
  8010. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  8011. // Necessary to make sure the init is deoptimized for conditional declarations.
  8012. // We cannot call deoptimizePath here.
  8013. variable.markInitializersForDeoptimization();
  8014. return variable;
  8015. }
  8016. else {
  8017. return super.addDeclaration(identifier, context, init, false);
  8018. }
  8019. }
  8020. }
  8021. class ExpressionStatement extends NodeBase {
  8022. initialise() {
  8023. if (this.directive &&
  8024. this.directive !== 'use strict' &&
  8025. this.parent.type === Program$1) {
  8026. this.context.warn(
  8027. // This is necessary, because either way (deleting or not) can lead to errors.
  8028. errorModuleLevelDirective(this.directive, this.context.module.id), this.start);
  8029. }
  8030. }
  8031. render(code, options) {
  8032. super.render(code, options);
  8033. if (this.included)
  8034. this.insertSemicolon(code);
  8035. }
  8036. shouldBeIncluded(context) {
  8037. if (this.directive && this.directive !== 'use strict')
  8038. return this.parent.type !== Program$1;
  8039. return super.shouldBeIncluded(context);
  8040. }
  8041. applyDeoptimizations() { }
  8042. }
  8043. class BlockStatement extends NodeBase {
  8044. constructor() {
  8045. super(...arguments);
  8046. this.directlyIncluded = false;
  8047. }
  8048. addImplicitReturnExpressionToScope() {
  8049. const lastStatement = this.body[this.body.length - 1];
  8050. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  8051. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  8052. }
  8053. }
  8054. createScope(parentScope) {
  8055. this.scope = this.parent.preventChildBlockScope
  8056. ? parentScope
  8057. : new BlockScope(parentScope);
  8058. }
  8059. hasEffects(context) {
  8060. if (this.deoptimizeBody)
  8061. return true;
  8062. for (const node of this.body) {
  8063. if (context.brokenFlow)
  8064. break;
  8065. if (node.hasEffects(context))
  8066. return true;
  8067. }
  8068. return false;
  8069. }
  8070. include(context, includeChildrenRecursively) {
  8071. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  8072. this.included = true;
  8073. this.directlyIncluded = true;
  8074. if (this.deoptimizeBody)
  8075. includeChildrenRecursively = true;
  8076. for (const node of this.body) {
  8077. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8078. node.include(context, includeChildrenRecursively);
  8079. }
  8080. }
  8081. }
  8082. initialise() {
  8083. const firstBodyStatement = this.body[0];
  8084. this.deoptimizeBody =
  8085. firstBodyStatement instanceof ExpressionStatement &&
  8086. firstBodyStatement.directive === 'use asm';
  8087. }
  8088. render(code, options) {
  8089. if (this.body.length > 0) {
  8090. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  8091. }
  8092. else {
  8093. super.render(code, options);
  8094. }
  8095. }
  8096. }
  8097. class RestElement extends NodeBase {
  8098. constructor() {
  8099. super(...arguments);
  8100. this.declarationInit = null;
  8101. }
  8102. addExportedVariables(variables, exportNamesByVariable) {
  8103. this.argument.addExportedVariables(variables, exportNamesByVariable);
  8104. }
  8105. declare(kind, init) {
  8106. this.declarationInit = init;
  8107. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  8108. }
  8109. deoptimizePath(path) {
  8110. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  8111. }
  8112. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8113. return (path.length > 0 ||
  8114. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  8115. }
  8116. markDeclarationReached() {
  8117. this.argument.markDeclarationReached();
  8118. }
  8119. applyDeoptimizations() {
  8120. this.deoptimized = true;
  8121. if (this.declarationInit !== null) {
  8122. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  8123. this.context.requestTreeshakingPass();
  8124. }
  8125. }
  8126. }
  8127. class FunctionBase extends NodeBase {
  8128. constructor() {
  8129. super(...arguments);
  8130. this.objectEntity = null;
  8131. this.deoptimizedReturn = false;
  8132. }
  8133. deoptimizePath(path) {
  8134. this.getObjectEntity().deoptimizePath(path);
  8135. if (path.length === 1 && path[0] === UnknownKey) {
  8136. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  8137. // which means the return expression needs to be reassigned
  8138. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  8139. }
  8140. }
  8141. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8142. if (path.length > 0) {
  8143. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8144. }
  8145. }
  8146. getLiteralValueAtPath(path, recursionTracker, origin) {
  8147. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8148. }
  8149. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8150. if (path.length > 0) {
  8151. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8152. }
  8153. if (this.async) {
  8154. if (!this.deoptimizedReturn) {
  8155. this.deoptimizedReturn = true;
  8156. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  8157. this.context.requestTreeshakingPass();
  8158. }
  8159. return UNKNOWN_RETURN_EXPRESSION;
  8160. }
  8161. return [this.scope.getReturnExpression(), false];
  8162. }
  8163. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8164. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  8165. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  8166. }
  8167. if (this.async) {
  8168. const { propertyReadSideEffects } = this.context.options
  8169. .treeshake;
  8170. const returnExpression = this.scope.getReturnExpression();
  8171. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  8172. (propertyReadSideEffects &&
  8173. (propertyReadSideEffects === 'always' ||
  8174. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  8175. return true;
  8176. }
  8177. }
  8178. for (const parameter of this.params) {
  8179. if (parameter.hasEffects(context))
  8180. return true;
  8181. }
  8182. return false;
  8183. }
  8184. include(context, includeChildrenRecursively) {
  8185. if (!this.deoptimized)
  8186. this.applyDeoptimizations();
  8187. this.included = true;
  8188. const { brokenFlow } = context;
  8189. context.brokenFlow = BROKEN_FLOW_NONE;
  8190. this.body.include(context, includeChildrenRecursively);
  8191. context.brokenFlow = brokenFlow;
  8192. }
  8193. includeCallArguments(context, parameters) {
  8194. this.scope.includeCallArguments(context, parameters);
  8195. }
  8196. initialise() {
  8197. this.scope.addParameterVariables(this.params.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  8198. if (this.body instanceof BlockStatement) {
  8199. this.body.addImplicitReturnExpressionToScope();
  8200. }
  8201. else {
  8202. this.scope.addReturnExpression(this.body);
  8203. }
  8204. }
  8205. parseNode(esTreeNode) {
  8206. if (esTreeNode.body.type === BlockStatement$1) {
  8207. this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  8208. }
  8209. super.parseNode(esTreeNode);
  8210. }
  8211. applyDeoptimizations() { }
  8212. }
  8213. FunctionBase.prototype.preventChildBlockScope = true;
  8214. class ArrowFunctionExpression extends FunctionBase {
  8215. constructor() {
  8216. super(...arguments);
  8217. this.objectEntity = null;
  8218. }
  8219. createScope(parentScope) {
  8220. this.scope = new ReturnValueScope(parentScope, this.context);
  8221. }
  8222. hasEffects() {
  8223. if (!this.deoptimized)
  8224. this.applyDeoptimizations();
  8225. return false;
  8226. }
  8227. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8228. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  8229. return true;
  8230. if (interaction.type === INTERACTION_CALLED) {
  8231. const { ignore, brokenFlow } = context;
  8232. context.ignore = {
  8233. breaks: false,
  8234. continues: false,
  8235. labels: new Set(),
  8236. returnYield: true,
  8237. this: false
  8238. };
  8239. if (this.body.hasEffects(context))
  8240. return true;
  8241. context.ignore = ignore;
  8242. context.brokenFlow = brokenFlow;
  8243. }
  8244. return false;
  8245. }
  8246. include(context, includeChildrenRecursively) {
  8247. super.include(context, includeChildrenRecursively);
  8248. for (const parameter of this.params) {
  8249. if (!(parameter instanceof Identifier)) {
  8250. parameter.include(context, includeChildrenRecursively);
  8251. }
  8252. }
  8253. }
  8254. getObjectEntity() {
  8255. if (this.objectEntity !== null) {
  8256. return this.objectEntity;
  8257. }
  8258. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  8259. }
  8260. }
  8261. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  8262. if (exportedVariables.length === 1 &&
  8263. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  8264. const variable = exportedVariables[0];
  8265. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
  8266. }
  8267. else {
  8268. const fields = [];
  8269. for (const variable of exportedVariables) {
  8270. for (const exportName of exportNamesByVariable.get(variable)) {
  8271. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  8272. }
  8273. }
  8274. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  8275. }
  8276. }
  8277. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  8278. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  8279. code.appendLeft(expressionEnd, ')');
  8280. }
  8281. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  8282. const { _, getDirectReturnIifeLeft } = options.snippets;
  8283. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  8284. code.appendLeft(expressionEnd, ')');
  8285. }
  8286. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  8287. const { _, getPropertyAccess } = options.snippets;
  8288. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  8289. if (needsParens) {
  8290. code.prependRight(expressionStart, '(');
  8291. code.appendLeft(expressionEnd, ')');
  8292. }
  8293. }
  8294. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  8295. const { _ } = options.snippets;
  8296. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  8297. if (needsParens) {
  8298. code.prependRight(expressionStart, '(');
  8299. code.appendLeft(expressionEnd, ')');
  8300. }
  8301. }
  8302. class ObjectPattern extends NodeBase {
  8303. addExportedVariables(variables, exportNamesByVariable) {
  8304. for (const property of this.properties) {
  8305. if (property.type === Property$1) {
  8306. property.value.addExportedVariables(variables, exportNamesByVariable);
  8307. }
  8308. else {
  8309. property.argument.addExportedVariables(variables, exportNamesByVariable);
  8310. }
  8311. }
  8312. }
  8313. declare(kind, init) {
  8314. const variables = [];
  8315. for (const property of this.properties) {
  8316. variables.push(...property.declare(kind, init));
  8317. }
  8318. return variables;
  8319. }
  8320. deoptimizePath(path) {
  8321. if (path.length === 0) {
  8322. for (const property of this.properties) {
  8323. property.deoptimizePath(path);
  8324. }
  8325. }
  8326. }
  8327. hasEffectsOnInteractionAtPath(
  8328. // At the moment, this is only triggered for assignment left-hand sides,
  8329. // where the path is empty
  8330. _path, interaction, context) {
  8331. for (const property of this.properties) {
  8332. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  8333. return true;
  8334. }
  8335. return false;
  8336. }
  8337. markDeclarationReached() {
  8338. for (const property of this.properties) {
  8339. property.markDeclarationReached();
  8340. }
  8341. }
  8342. }
  8343. class AssignmentExpression extends NodeBase {
  8344. hasEffects(context) {
  8345. const { deoptimized, left, operator, right } = this;
  8346. if (!deoptimized)
  8347. this.applyDeoptimizations();
  8348. // MemberExpressions do not access the property before assignments if the
  8349. // operator is '='.
  8350. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, operator !== '='));
  8351. }
  8352. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8353. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  8354. }
  8355. include(context, includeChildrenRecursively) {
  8356. const { deoptimized, left, right, operator } = this;
  8357. if (!deoptimized)
  8358. this.applyDeoptimizations();
  8359. this.included = true;
  8360. if (includeChildrenRecursively ||
  8361. operator !== '=' ||
  8362. left.included ||
  8363. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  8364. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  8365. }
  8366. right.include(context, includeChildrenRecursively);
  8367. }
  8368. initialise() {
  8369. this.left.setAssignedValue(this.right);
  8370. }
  8371. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  8372. const { left, right, start, end, parent } = this;
  8373. if (left.included) {
  8374. left.render(code, options);
  8375. right.render(code, options);
  8376. }
  8377. else {
  8378. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  8379. code.remove(start, inclusionStart);
  8380. if (preventASI) {
  8381. removeLineBreaks(code, inclusionStart, right.start);
  8382. }
  8383. right.render(code, options, {
  8384. renderedParentType: renderedParentType || parent.type,
  8385. renderedSurroundingElement: renderedSurroundingElement || parent.type
  8386. });
  8387. }
  8388. if (options.format === 'system') {
  8389. if (left instanceof Identifier) {
  8390. const variable = left.variable;
  8391. const exportNames = options.exportNamesByVariable.get(variable);
  8392. if (exportNames) {
  8393. if (exportNames.length === 1) {
  8394. renderSystemExportExpression(variable, start, end, code, options);
  8395. }
  8396. else {
  8397. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  8398. }
  8399. return;
  8400. }
  8401. }
  8402. else {
  8403. const systemPatternExports = [];
  8404. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  8405. if (systemPatternExports.length > 0) {
  8406. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  8407. return;
  8408. }
  8409. }
  8410. }
  8411. if (left.included &&
  8412. left instanceof ObjectPattern &&
  8413. (renderedSurroundingElement === ExpressionStatement$1 ||
  8414. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  8415. code.appendRight(start, '(');
  8416. code.prependLeft(end, ')');
  8417. }
  8418. }
  8419. applyDeoptimizations() {
  8420. this.deoptimized = true;
  8421. this.left.deoptimizePath(EMPTY_PATH);
  8422. this.right.deoptimizePath(UNKNOWN_PATH);
  8423. this.context.requestTreeshakingPass();
  8424. }
  8425. }
  8426. class AssignmentPattern extends NodeBase {
  8427. addExportedVariables(variables, exportNamesByVariable) {
  8428. this.left.addExportedVariables(variables, exportNamesByVariable);
  8429. }
  8430. declare(kind, init) {
  8431. return this.left.declare(kind, init);
  8432. }
  8433. deoptimizePath(path) {
  8434. path.length === 0 && this.left.deoptimizePath(path);
  8435. }
  8436. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8437. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  8438. }
  8439. markDeclarationReached() {
  8440. this.left.markDeclarationReached();
  8441. }
  8442. render(code, options, { isShorthandProperty } = BLANK) {
  8443. this.left.render(code, options, { isShorthandProperty });
  8444. this.right.render(code, options);
  8445. }
  8446. applyDeoptimizations() {
  8447. this.deoptimized = true;
  8448. this.left.deoptimizePath(EMPTY_PATH);
  8449. this.right.deoptimizePath(UNKNOWN_PATH);
  8450. this.context.requestTreeshakingPass();
  8451. }
  8452. }
  8453. class ArgumentsVariable extends LocalVariable {
  8454. constructor(context) {
  8455. super('arguments', null, UNKNOWN_EXPRESSION, context);
  8456. }
  8457. hasEffectsOnInteractionAtPath(path, { type }) {
  8458. return type !== INTERACTION_ACCESSED || path.length > 1;
  8459. }
  8460. }
  8461. class ThisVariable extends LocalVariable {
  8462. constructor(context) {
  8463. super('this', null, null, context);
  8464. this.deoptimizedPaths = [];
  8465. this.entitiesToBeDeoptimized = new Set();
  8466. this.thisDeoptimizationList = [];
  8467. this.thisDeoptimizations = new DiscriminatedPathTracker();
  8468. }
  8469. addEntityToBeDeoptimized(entity) {
  8470. for (const path of this.deoptimizedPaths) {
  8471. entity.deoptimizePath(path);
  8472. }
  8473. for (const { interaction, path } of this.thisDeoptimizationList) {
  8474. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  8475. }
  8476. this.entitiesToBeDeoptimized.add(entity);
  8477. }
  8478. deoptimizePath(path) {
  8479. if (path.length === 0 ||
  8480. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  8481. return;
  8482. }
  8483. this.deoptimizedPaths.push(path);
  8484. for (const entity of this.entitiesToBeDeoptimized) {
  8485. entity.deoptimizePath(path);
  8486. }
  8487. }
  8488. deoptimizeThisOnInteractionAtPath(interaction, path) {
  8489. const thisDeoptimization = {
  8490. interaction,
  8491. path
  8492. };
  8493. if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.type, interaction.thisArg)) {
  8494. for (const entity of this.entitiesToBeDeoptimized) {
  8495. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  8496. }
  8497. this.thisDeoptimizationList.push(thisDeoptimization);
  8498. }
  8499. }
  8500. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8501. const replacedVariableInit = context.replacedVariableInits.get(this);
  8502. if (replacedVariableInit) {
  8503. return (replacedVariableInit.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  8504. // If the surrounding function is included, all mutations of "this" must
  8505. // be counted as side effects, which is what this second line does.
  8506. (!context.ignore.this && super.hasEffectsOnInteractionAtPath(path, interaction, context)));
  8507. }
  8508. return UNKNOWN_EXPRESSION.hasEffectsOnInteractionAtPath(path, interaction, context);
  8509. }
  8510. }
  8511. class FunctionScope extends ReturnValueScope {
  8512. constructor(parent, context) {
  8513. super(parent, context);
  8514. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  8515. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  8516. }
  8517. findLexicalBoundary() {
  8518. return this;
  8519. }
  8520. includeCallArguments(context, parameters) {
  8521. super.includeCallArguments(context, parameters);
  8522. if (this.argumentsVariable.included) {
  8523. for (const argument of parameters) {
  8524. if (!argument.included) {
  8525. argument.include(context, false);
  8526. }
  8527. }
  8528. }
  8529. }
  8530. }
  8531. class FunctionNode extends FunctionBase {
  8532. constructor() {
  8533. super(...arguments);
  8534. this.objectEntity = null;
  8535. }
  8536. createScope(parentScope) {
  8537. this.scope = new FunctionScope(parentScope, this.context);
  8538. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  8539. // This makes sure that all deoptimizations of "this" are applied to the
  8540. // constructed entity.
  8541. this.scope.thisVariable.addEntityToBeDeoptimized(this.constructedEntity);
  8542. }
  8543. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8544. super.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8545. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  8546. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.thisArg);
  8547. }
  8548. }
  8549. hasEffects(context) {
  8550. if (!this.deoptimized)
  8551. this.applyDeoptimizations();
  8552. return !!this.id?.hasEffects(context);
  8553. }
  8554. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8555. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  8556. return true;
  8557. if (interaction.type === INTERACTION_CALLED) {
  8558. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  8559. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  8560. const { brokenFlow, ignore, replacedVariableInits } = context;
  8561. context.ignore = {
  8562. breaks: false,
  8563. continues: false,
  8564. labels: new Set(),
  8565. returnYield: true,
  8566. this: interaction.withNew
  8567. };
  8568. if (this.body.hasEffects(context))
  8569. return true;
  8570. context.brokenFlow = brokenFlow;
  8571. if (thisInit) {
  8572. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  8573. }
  8574. else {
  8575. replacedVariableInits.delete(this.scope.thisVariable);
  8576. }
  8577. context.ignore = ignore;
  8578. }
  8579. return false;
  8580. }
  8581. include(context, includeChildrenRecursively) {
  8582. super.include(context, includeChildrenRecursively);
  8583. this.id?.include();
  8584. const hasArguments = this.scope.argumentsVariable.included;
  8585. for (const parameter of this.params) {
  8586. if (!(parameter instanceof Identifier) || hasArguments) {
  8587. parameter.include(context, includeChildrenRecursively);
  8588. }
  8589. }
  8590. }
  8591. initialise() {
  8592. super.initialise();
  8593. this.id?.declare('function', this);
  8594. }
  8595. getObjectEntity() {
  8596. if (this.objectEntity !== null) {
  8597. return this.objectEntity;
  8598. }
  8599. return (this.objectEntity = new ObjectEntity([
  8600. {
  8601. key: 'prototype',
  8602. kind: 'init',
  8603. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  8604. }
  8605. ], OBJECT_PROTOTYPE));
  8606. }
  8607. }
  8608. class AwaitExpression extends NodeBase {
  8609. hasEffects() {
  8610. if (!this.deoptimized)
  8611. this.applyDeoptimizations();
  8612. return true;
  8613. }
  8614. include(context, includeChildrenRecursively) {
  8615. if (!this.deoptimized)
  8616. this.applyDeoptimizations();
  8617. if (!this.included) {
  8618. this.included = true;
  8619. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  8620. let parent = this.parent;
  8621. do {
  8622. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  8623. break checkTopLevelAwait;
  8624. } while ((parent = parent.parent));
  8625. this.context.usesTopLevelAwait = true;
  8626. }
  8627. }
  8628. this.argument.include(context, includeChildrenRecursively);
  8629. }
  8630. }
  8631. const binaryOperators = {
  8632. '!=': (left, right) => left != right,
  8633. '!==': (left, right) => left !== right,
  8634. '%': (left, right) => left % right,
  8635. '&': (left, right) => left & right,
  8636. '*': (left, right) => left * right,
  8637. // At the moment, "**" will be transpiled to Math.pow
  8638. '**': (left, right) => left ** right,
  8639. '+': (left, right) => left + right,
  8640. '-': (left, right) => left - right,
  8641. '/': (left, right) => left / right,
  8642. '<': (left, right) => left < right,
  8643. '<<': (left, right) => left << right,
  8644. '<=': (left, right) => left <= right,
  8645. '==': (left, right) => left == right,
  8646. '===': (left, right) => left === right,
  8647. '>': (left, right) => left > right,
  8648. '>=': (left, right) => left >= right,
  8649. '>>': (left, right) => left >> right,
  8650. '>>>': (left, right) => left >>> right,
  8651. '^': (left, right) => left ^ right,
  8652. '|': (left, right) => left | right
  8653. // We use the fallback for cases where we return something unknown
  8654. // in: () => UnknownValue,
  8655. // instanceof: () => UnknownValue,
  8656. };
  8657. class BinaryExpression extends NodeBase {
  8658. deoptimizeCache() { }
  8659. getLiteralValueAtPath(path, recursionTracker, origin) {
  8660. if (path.length > 0)
  8661. return UnknownValue;
  8662. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8663. if (typeof leftValue === 'symbol')
  8664. return UnknownValue;
  8665. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8666. if (typeof rightValue === 'symbol')
  8667. return UnknownValue;
  8668. const operatorFunction = binaryOperators[this.operator];
  8669. if (!operatorFunction)
  8670. return UnknownValue;
  8671. return operatorFunction(leftValue, rightValue);
  8672. }
  8673. hasEffects(context) {
  8674. // support some implicit type coercion runtime errors
  8675. if (this.operator === '+' &&
  8676. this.parent instanceof ExpressionStatement &&
  8677. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  8678. return true;
  8679. }
  8680. return super.hasEffects(context);
  8681. }
  8682. hasEffectsOnInteractionAtPath(path, { type }) {
  8683. return type !== INTERACTION_ACCESSED || path.length > 1;
  8684. }
  8685. render(code, options, { renderedSurroundingElement } = BLANK) {
  8686. this.left.render(code, options, { renderedSurroundingElement });
  8687. this.right.render(code, options);
  8688. }
  8689. }
  8690. class BreakStatement extends NodeBase {
  8691. hasEffects(context) {
  8692. if (this.label) {
  8693. if (!context.ignore.labels.has(this.label.name))
  8694. return true;
  8695. context.includedLabels.add(this.label.name);
  8696. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8697. }
  8698. else {
  8699. if (!context.ignore.breaks)
  8700. return true;
  8701. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  8702. }
  8703. return false;
  8704. }
  8705. include(context) {
  8706. this.included = true;
  8707. if (this.label) {
  8708. this.label.include();
  8709. context.includedLabels.add(this.label.name);
  8710. }
  8711. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  8712. }
  8713. }
  8714. function renderCallArguments(code, options, node) {
  8715. if (node.arguments.length > 0) {
  8716. if (node.arguments[node.arguments.length - 1].included) {
  8717. for (const argument of node.arguments) {
  8718. argument.render(code, options);
  8719. }
  8720. }
  8721. else {
  8722. let lastIncludedIndex = node.arguments.length - 2;
  8723. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  8724. lastIncludedIndex--;
  8725. }
  8726. if (lastIncludedIndex >= 0) {
  8727. for (let index = 0; index <= lastIncludedIndex; index++) {
  8728. node.arguments[index].render(code, options);
  8729. }
  8730. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  8731. }
  8732. else {
  8733. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  8734. }
  8735. }
  8736. }
  8737. }
  8738. class Literal extends NodeBase {
  8739. deoptimizeThisOnInteractionAtPath() { }
  8740. getLiteralValueAtPath(path) {
  8741. if (path.length > 0 ||
  8742. // unknown literals can also be null but do not start with an "n"
  8743. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  8744. typeof this.value === 'bigint' ||
  8745. // to support shims for regular expressions
  8746. this.context.code.charCodeAt(this.start) === 47) {
  8747. return UnknownValue;
  8748. }
  8749. return this.value;
  8750. }
  8751. getReturnExpressionWhenCalledAtPath(path) {
  8752. if (path.length !== 1)
  8753. return UNKNOWN_RETURN_EXPRESSION;
  8754. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  8755. }
  8756. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8757. switch (interaction.type) {
  8758. case INTERACTION_ACCESSED: {
  8759. return path.length > (this.value === null ? 0 : 1);
  8760. }
  8761. case INTERACTION_ASSIGNED: {
  8762. return true;
  8763. }
  8764. case INTERACTION_CALLED: {
  8765. if (this.included &&
  8766. this.value instanceof RegExp &&
  8767. (this.value.global || this.value.sticky)) {
  8768. return true;
  8769. }
  8770. return (path.length !== 1 ||
  8771. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  8772. }
  8773. }
  8774. }
  8775. initialise() {
  8776. this.members = getLiteralMembersForValue(this.value);
  8777. }
  8778. parseNode(esTreeNode) {
  8779. this.value = esTreeNode.value;
  8780. this.regex = esTreeNode.regex;
  8781. super.parseNode(esTreeNode);
  8782. }
  8783. render(code) {
  8784. if (typeof this.value === 'string') {
  8785. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  8786. }
  8787. }
  8788. }
  8789. // To avoid infinite recursions
  8790. const MAX_PATH_DEPTH = 7;
  8791. function getResolvablePropertyKey(memberExpression) {
  8792. return memberExpression.computed
  8793. ? getResolvableComputedPropertyKey(memberExpression.property)
  8794. : memberExpression.property.name;
  8795. }
  8796. function getResolvableComputedPropertyKey(propertyKey) {
  8797. if (propertyKey instanceof Literal) {
  8798. return String(propertyKey.value);
  8799. }
  8800. return null;
  8801. }
  8802. function getPathIfNotComputed(memberExpression) {
  8803. const nextPathKey = memberExpression.propertyKey;
  8804. const object = memberExpression.object;
  8805. if (typeof nextPathKey === 'string') {
  8806. if (object instanceof Identifier) {
  8807. return [
  8808. { key: object.name, pos: object.start },
  8809. { key: nextPathKey, pos: memberExpression.property.start }
  8810. ];
  8811. }
  8812. if (object instanceof MemberExpression) {
  8813. const parentPath = getPathIfNotComputed(object);
  8814. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  8815. }
  8816. }
  8817. return null;
  8818. }
  8819. function getStringFromPath(path) {
  8820. let pathString = path[0].key;
  8821. for (let index = 1; index < path.length; index++) {
  8822. pathString += '.' + path[index].key;
  8823. }
  8824. return pathString;
  8825. }
  8826. class MemberExpression extends NodeBase {
  8827. constructor() {
  8828. super(...arguments);
  8829. this.variable = null;
  8830. this.assignmentDeoptimized = false;
  8831. this.bound = false;
  8832. this.expressionsToBeDeoptimized = [];
  8833. this.isUndefined = false;
  8834. }
  8835. bind() {
  8836. this.bound = true;
  8837. const path = getPathIfNotComputed(this);
  8838. const baseVariable = path && this.scope.findVariable(path[0].key);
  8839. if (baseVariable?.isNamespace) {
  8840. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
  8841. if (!resolvedVariable) {
  8842. super.bind();
  8843. }
  8844. else if (resolvedVariable === 'undefined') {
  8845. this.isUndefined = true;
  8846. }
  8847. else {
  8848. this.variable = resolvedVariable;
  8849. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  8850. }
  8851. }
  8852. else {
  8853. super.bind();
  8854. }
  8855. }
  8856. deoptimizeCache() {
  8857. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  8858. this.expressionsToBeDeoptimized = [];
  8859. this.propertyKey = UnknownKey;
  8860. this.object.deoptimizePath(UNKNOWN_PATH);
  8861. for (const expression of expressionsToBeDeoptimized) {
  8862. expression.deoptimizeCache();
  8863. }
  8864. }
  8865. deoptimizePath(path) {
  8866. if (path.length === 0)
  8867. this.disallowNamespaceReassignment();
  8868. if (this.variable) {
  8869. this.variable.deoptimizePath(path);
  8870. }
  8871. else if (!this.isUndefined && path.length < MAX_PATH_DEPTH) {
  8872. const propertyKey = this.getPropertyKey();
  8873. this.object.deoptimizePath([
  8874. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  8875. ...path
  8876. ]);
  8877. }
  8878. }
  8879. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8880. if (this.variable) {
  8881. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8882. }
  8883. else if (!this.isUndefined) {
  8884. if (path.length < MAX_PATH_DEPTH) {
  8885. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  8886. }
  8887. else {
  8888. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  8889. }
  8890. }
  8891. }
  8892. getLiteralValueAtPath(path, recursionTracker, origin) {
  8893. if (this.variable) {
  8894. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  8895. }
  8896. if (this.isUndefined) {
  8897. return undefined;
  8898. }
  8899. this.expressionsToBeDeoptimized.push(origin);
  8900. if (path.length < MAX_PATH_DEPTH) {
  8901. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  8902. }
  8903. return UnknownValue;
  8904. }
  8905. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8906. if (this.variable) {
  8907. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8908. }
  8909. if (this.isUndefined) {
  8910. return [UNDEFINED_EXPRESSION, false];
  8911. }
  8912. this.expressionsToBeDeoptimized.push(origin);
  8913. if (path.length < MAX_PATH_DEPTH) {
  8914. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  8915. }
  8916. return UNKNOWN_RETURN_EXPRESSION;
  8917. }
  8918. hasEffects(context) {
  8919. if (!this.deoptimized)
  8920. this.applyDeoptimizations();
  8921. return (this.property.hasEffects(context) ||
  8922. this.object.hasEffects(context) ||
  8923. this.hasAccessEffect(context));
  8924. }
  8925. hasEffectsAsAssignmentTarget(context, checkAccess) {
  8926. if (checkAccess && !this.deoptimized)
  8927. this.applyDeoptimizations();
  8928. if (!this.assignmentDeoptimized)
  8929. this.applyAssignmentDeoptimization();
  8930. return (this.property.hasEffects(context) ||
  8931. this.object.hasEffects(context) ||
  8932. (checkAccess && this.hasAccessEffect(context)) ||
  8933. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  8934. }
  8935. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8936. if (this.variable) {
  8937. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  8938. }
  8939. if (this.isUndefined) {
  8940. return true;
  8941. }
  8942. if (path.length < MAX_PATH_DEPTH) {
  8943. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  8944. }
  8945. return true;
  8946. }
  8947. include(context, includeChildrenRecursively) {
  8948. if (!this.deoptimized)
  8949. this.applyDeoptimizations();
  8950. this.includeProperties(context, includeChildrenRecursively);
  8951. }
  8952. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  8953. if (!this.assignmentDeoptimized)
  8954. this.applyAssignmentDeoptimization();
  8955. if (deoptimizeAccess) {
  8956. this.include(context, includeChildrenRecursively);
  8957. }
  8958. else {
  8959. this.includeProperties(context, includeChildrenRecursively);
  8960. }
  8961. }
  8962. includeCallArguments(context, parameters) {
  8963. if (this.variable) {
  8964. this.variable.includeCallArguments(context, parameters);
  8965. }
  8966. else {
  8967. super.includeCallArguments(context, parameters);
  8968. }
  8969. }
  8970. initialise() {
  8971. this.propertyKey = getResolvablePropertyKey(this);
  8972. this.accessInteraction = { thisArg: this.object, type: INTERACTION_ACCESSED };
  8973. }
  8974. isSkippedAsOptional(origin) {
  8975. return (!this.variable &&
  8976. !this.isUndefined &&
  8977. (this.object.isSkippedAsOptional?.(origin) ||
  8978. (this.optional &&
  8979. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null)));
  8980. }
  8981. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  8982. if (this.variable || this.isUndefined) {
  8983. const { snippets: { getPropertyAccess } } = options;
  8984. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  8985. if (renderedParentType && isCalleeOfRenderedParent)
  8986. replacement = '0, ' + replacement;
  8987. code.overwrite(this.start, this.end, replacement, {
  8988. contentOnly: true,
  8989. storeName: true
  8990. });
  8991. }
  8992. else {
  8993. if (renderedParentType && isCalleeOfRenderedParent) {
  8994. code.appendRight(this.start, '0, ');
  8995. }
  8996. this.object.render(code, options, { renderedSurroundingElement });
  8997. this.property.render(code, options);
  8998. }
  8999. }
  9000. setAssignedValue(value) {
  9001. this.assignmentInteraction = {
  9002. args: [value],
  9003. thisArg: this.object,
  9004. type: INTERACTION_ASSIGNED
  9005. };
  9006. }
  9007. applyDeoptimizations() {
  9008. this.deoptimized = true;
  9009. const { propertyReadSideEffects } = this.context.options
  9010. .treeshake;
  9011. if (
  9012. // Namespaces are not bound and should not be deoptimized
  9013. this.bound &&
  9014. propertyReadSideEffects &&
  9015. !(this.variable || this.isUndefined)) {
  9016. const propertyKey = this.getPropertyKey();
  9017. this.object.deoptimizeThisOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  9018. this.context.requestTreeshakingPass();
  9019. }
  9020. }
  9021. applyAssignmentDeoptimization() {
  9022. this.assignmentDeoptimized = true;
  9023. const { propertyReadSideEffects } = this.context.options
  9024. .treeshake;
  9025. if (
  9026. // Namespaces are not bound and should not be deoptimized
  9027. this.bound &&
  9028. propertyReadSideEffects &&
  9029. !(this.variable || this.isUndefined)) {
  9030. this.object.deoptimizeThisOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  9031. this.context.requestTreeshakingPass();
  9032. }
  9033. }
  9034. disallowNamespaceReassignment() {
  9035. if (this.object instanceof Identifier) {
  9036. const variable = this.scope.findVariable(this.object.name);
  9037. if (variable.isNamespace) {
  9038. if (this.variable) {
  9039. this.context.includeVariableInModule(this.variable);
  9040. }
  9041. this.context.warn(errorIllegalImportReassignment(this.object.name, this.context.module.id), this.start);
  9042. }
  9043. }
  9044. }
  9045. getPropertyKey() {
  9046. if (this.propertyKey === null) {
  9047. this.propertyKey = UnknownKey;
  9048. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9049. return (this.propertyKey =
  9050. value === SymbolToStringTag
  9051. ? value
  9052. : typeof value === 'symbol'
  9053. ? UnknownKey
  9054. : String(value));
  9055. }
  9056. return this.propertyKey;
  9057. }
  9058. hasAccessEffect(context) {
  9059. const { propertyReadSideEffects } = this.context.options
  9060. .treeshake;
  9061. return (!(this.variable || this.isUndefined) &&
  9062. propertyReadSideEffects &&
  9063. (propertyReadSideEffects === 'always' ||
  9064. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  9065. }
  9066. includeProperties(context, includeChildrenRecursively) {
  9067. if (!this.included) {
  9068. this.included = true;
  9069. if (this.variable) {
  9070. this.context.includeVariableInModule(this.variable);
  9071. }
  9072. }
  9073. this.object.include(context, includeChildrenRecursively);
  9074. this.property.include(context, includeChildrenRecursively);
  9075. }
  9076. }
  9077. function resolveNamespaceVariables(baseVariable, path, astContext) {
  9078. if (path.length === 0)
  9079. return baseVariable;
  9080. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  9081. return null;
  9082. const exportName = path[0].key;
  9083. const variable = baseVariable.context.traceExport(exportName);
  9084. if (!variable) {
  9085. if (path.length === 1) {
  9086. const fileName = baseVariable.context.fileName;
  9087. astContext.warn(errorMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  9088. return 'undefined';
  9089. }
  9090. return null;
  9091. }
  9092. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  9093. }
  9094. class CallExpressionBase extends NodeBase {
  9095. constructor() {
  9096. super(...arguments);
  9097. this.returnExpression = null;
  9098. this.deoptimizableDependentExpressions = [];
  9099. this.expressionsToBeDeoptimized = new Set();
  9100. }
  9101. deoptimizeCache() {
  9102. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  9103. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  9104. for (const expression of this.deoptimizableDependentExpressions) {
  9105. expression.deoptimizeCache();
  9106. }
  9107. for (const expression of this.expressionsToBeDeoptimized) {
  9108. expression.deoptimizePath(UNKNOWN_PATH);
  9109. }
  9110. }
  9111. }
  9112. deoptimizePath(path) {
  9113. if (path.length === 0 ||
  9114. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  9115. return;
  9116. }
  9117. const [returnExpression] = this.getReturnExpression();
  9118. if (returnExpression !== UNKNOWN_EXPRESSION) {
  9119. returnExpression.deoptimizePath(path);
  9120. }
  9121. }
  9122. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  9123. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  9124. if (isPure)
  9125. return;
  9126. if (returnExpression === UNKNOWN_EXPRESSION) {
  9127. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  9128. }
  9129. else {
  9130. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  9131. this.expressionsToBeDeoptimized.add(interaction.thisArg);
  9132. returnExpression.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9133. }, null);
  9134. }
  9135. }
  9136. getLiteralValueAtPath(path, recursionTracker, origin) {
  9137. const [returnExpression] = this.getReturnExpression(recursionTracker);
  9138. if (returnExpression === UNKNOWN_EXPRESSION) {
  9139. return UnknownValue;
  9140. }
  9141. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  9142. this.deoptimizableDependentExpressions.push(origin);
  9143. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  9144. }, UnknownValue);
  9145. }
  9146. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9147. const returnExpression = this.getReturnExpression(recursionTracker);
  9148. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  9149. return returnExpression;
  9150. }
  9151. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  9152. this.deoptimizableDependentExpressions.push(origin);
  9153. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9154. return [expression, isPure || returnExpression[1]];
  9155. }, UNKNOWN_RETURN_EXPRESSION);
  9156. }
  9157. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9158. const { type } = interaction;
  9159. if (type === INTERACTION_CALLED) {
  9160. const { args, withNew } = interaction;
  9161. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  9162. return false;
  9163. }
  9164. }
  9165. else if ((type === INTERACTION_ASSIGNED
  9166. ? context.assigned
  9167. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  9168. return false;
  9169. }
  9170. const [returnExpression, isPure] = this.getReturnExpression();
  9171. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  9172. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  9173. }
  9174. }
  9175. class CallExpression extends CallExpressionBase {
  9176. bind() {
  9177. super.bind();
  9178. if (this.callee instanceof Identifier) {
  9179. const variable = this.scope.findVariable(this.callee.name);
  9180. if (variable.isNamespace) {
  9181. this.context.warn(errorCannotCallNamespace(this.callee.name), this.start);
  9182. }
  9183. if (this.callee.name === 'eval') {
  9184. this.context.warn(errorEval(this.context.module.id), this.start);
  9185. }
  9186. }
  9187. this.interaction = {
  9188. args: this.arguments,
  9189. thisArg: this.callee instanceof MemberExpression && !this.callee.variable
  9190. ? this.callee.object
  9191. : null,
  9192. type: INTERACTION_CALLED,
  9193. withNew: false
  9194. };
  9195. }
  9196. hasEffects(context) {
  9197. try {
  9198. for (const argument of this.arguments) {
  9199. if (argument.hasEffects(context))
  9200. return true;
  9201. }
  9202. if (this.context.options.treeshake.annotations &&
  9203. this.annotations)
  9204. return false;
  9205. return (this.callee.hasEffects(context) ||
  9206. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  9207. }
  9208. finally {
  9209. if (!this.deoptimized)
  9210. this.applyDeoptimizations();
  9211. }
  9212. }
  9213. include(context, includeChildrenRecursively) {
  9214. if (!this.deoptimized)
  9215. this.applyDeoptimizations();
  9216. if (includeChildrenRecursively) {
  9217. super.include(context, includeChildrenRecursively);
  9218. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  9219. this.callee instanceof Identifier &&
  9220. this.callee.variable) {
  9221. this.callee.variable.markCalledFromTryStatement();
  9222. }
  9223. }
  9224. else {
  9225. this.included = true;
  9226. this.callee.include(context, false);
  9227. }
  9228. this.callee.includeCallArguments(context, this.arguments);
  9229. }
  9230. isSkippedAsOptional(origin) {
  9231. return (this.callee.isSkippedAsOptional?.(origin) ||
  9232. (this.optional &&
  9233. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null));
  9234. }
  9235. render(code, options, { renderedSurroundingElement } = BLANK) {
  9236. this.callee.render(code, options, {
  9237. isCalleeOfRenderedParent: true,
  9238. renderedSurroundingElement
  9239. });
  9240. renderCallArguments(code, options, this);
  9241. }
  9242. applyDeoptimizations() {
  9243. this.deoptimized = true;
  9244. if (this.interaction.thisArg) {
  9245. this.callee.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  9246. }
  9247. for (const argument of this.arguments) {
  9248. // This will make sure all properties of parameters behave as "unknown"
  9249. argument.deoptimizePath(UNKNOWN_PATH);
  9250. }
  9251. this.context.requestTreeshakingPass();
  9252. }
  9253. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  9254. if (this.returnExpression === null) {
  9255. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  9256. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  9257. }
  9258. return this.returnExpression;
  9259. }
  9260. }
  9261. class CatchScope extends ParameterScope {
  9262. addDeclaration(identifier, context, init, isHoisted) {
  9263. const existingParameter = this.variables.get(identifier.name);
  9264. if (existingParameter) {
  9265. // While we still create a hoisted declaration, the initializer goes to
  9266. // the parameter. Note that technically, the declaration now belongs to
  9267. // two variables, which is not correct but should not cause issues.
  9268. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  9269. existingParameter.addDeclaration(identifier, init);
  9270. return existingParameter;
  9271. }
  9272. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  9273. }
  9274. }
  9275. class CatchClause extends NodeBase {
  9276. createScope(parentScope) {
  9277. this.scope = new CatchScope(parentScope, this.context);
  9278. }
  9279. parseNode(esTreeNode) {
  9280. // Parameters need to be declared first as the logic is that initializers
  9281. // of hoisted body variables are associated with parameters of the same
  9282. // name instead of the variable
  9283. const { param } = esTreeNode;
  9284. if (param) {
  9285. this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
  9286. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  9287. }
  9288. super.parseNode(esTreeNode);
  9289. }
  9290. }
  9291. class ChainExpression extends NodeBase {
  9292. // deoptimizations are not relevant as we are not caching values
  9293. deoptimizeCache() { }
  9294. getLiteralValueAtPath(path, recursionTracker, origin) {
  9295. if (this.expression.isSkippedAsOptional(origin))
  9296. return undefined;
  9297. return this.expression.getLiteralValueAtPath(path, recursionTracker, origin);
  9298. }
  9299. hasEffects(context) {
  9300. if (this.expression.isSkippedAsOptional(this))
  9301. return false;
  9302. return this.expression.hasEffects(context);
  9303. }
  9304. }
  9305. class ClassBodyScope extends ChildScope {
  9306. constructor(parent, classNode, context) {
  9307. super(parent);
  9308. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  9309. this.instanceScope = new ChildScope(this);
  9310. this.instanceScope.variables.set('this', new ThisVariable(context));
  9311. }
  9312. findLexicalBoundary() {
  9313. return this;
  9314. }
  9315. }
  9316. class ClassBody extends NodeBase {
  9317. createScope(parentScope) {
  9318. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  9319. }
  9320. include(context, includeChildrenRecursively) {
  9321. this.included = true;
  9322. this.context.includeVariableInModule(this.scope.thisVariable);
  9323. for (const definition of this.body) {
  9324. definition.include(context, includeChildrenRecursively);
  9325. }
  9326. }
  9327. parseNode(esTreeNode) {
  9328. const body = (this.body = []);
  9329. for (const definition of esTreeNode.body) {
  9330. body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
  9331. }
  9332. super.parseNode(esTreeNode);
  9333. }
  9334. applyDeoptimizations() { }
  9335. }
  9336. class MethodBase extends NodeBase {
  9337. constructor() {
  9338. super(...arguments);
  9339. this.accessedValue = null;
  9340. }
  9341. // As getter properties directly receive their values from fixed function
  9342. // expressions, there is no known situation where a getter is deoptimized.
  9343. deoptimizeCache() { }
  9344. deoptimizePath(path) {
  9345. this.getAccessedValue()[0].deoptimizePath(path);
  9346. }
  9347. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  9348. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  9349. return this.value.deoptimizeThisOnInteractionAtPath({
  9350. args: NO_ARGS,
  9351. thisArg: interaction.thisArg,
  9352. type: INTERACTION_CALLED,
  9353. withNew: false
  9354. }, EMPTY_PATH, recursionTracker);
  9355. }
  9356. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  9357. return this.value.deoptimizeThisOnInteractionAtPath({
  9358. args: interaction.args,
  9359. thisArg: interaction.thisArg,
  9360. type: INTERACTION_CALLED,
  9361. withNew: false
  9362. }, EMPTY_PATH, recursionTracker);
  9363. }
  9364. this.getAccessedValue()[0].deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9365. }
  9366. getLiteralValueAtPath(path, recursionTracker, origin) {
  9367. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  9368. }
  9369. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9370. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9371. }
  9372. hasEffects(context) {
  9373. return this.key.hasEffects(context);
  9374. }
  9375. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9376. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  9377. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  9378. args: NO_ARGS,
  9379. thisArg: interaction.thisArg,
  9380. type: INTERACTION_CALLED,
  9381. withNew: false
  9382. }, context);
  9383. }
  9384. // setters are only called for empty paths
  9385. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  9386. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  9387. args: interaction.args,
  9388. thisArg: interaction.thisArg,
  9389. type: INTERACTION_CALLED,
  9390. withNew: false
  9391. }, context);
  9392. }
  9393. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  9394. }
  9395. applyDeoptimizations() { }
  9396. getAccessedValue() {
  9397. if (this.accessedValue === null) {
  9398. if (this.kind === 'get') {
  9399. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  9400. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  9401. }
  9402. else {
  9403. return (this.accessedValue = [this.value, false]);
  9404. }
  9405. }
  9406. return this.accessedValue;
  9407. }
  9408. }
  9409. class MethodDefinition extends MethodBase {
  9410. applyDeoptimizations() { }
  9411. }
  9412. class ObjectMember extends ExpressionEntity {
  9413. constructor(object, key) {
  9414. super();
  9415. this.object = object;
  9416. this.key = key;
  9417. }
  9418. deoptimizePath(path) {
  9419. this.object.deoptimizePath([this.key, ...path]);
  9420. }
  9421. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  9422. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  9423. }
  9424. getLiteralValueAtPath(path, recursionTracker, origin) {
  9425. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  9426. }
  9427. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9428. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  9429. }
  9430. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9431. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  9432. }
  9433. }
  9434. class ClassNode extends NodeBase {
  9435. constructor() {
  9436. super(...arguments);
  9437. this.objectEntity = null;
  9438. }
  9439. createScope(parentScope) {
  9440. this.scope = new ChildScope(parentScope);
  9441. }
  9442. deoptimizeCache() {
  9443. this.getObjectEntity().deoptimizeAllProperties();
  9444. }
  9445. deoptimizePath(path) {
  9446. this.getObjectEntity().deoptimizePath(path);
  9447. }
  9448. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  9449. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9450. }
  9451. getLiteralValueAtPath(path, recursionTracker, origin) {
  9452. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  9453. }
  9454. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9455. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9456. }
  9457. hasEffects(context) {
  9458. if (!this.deoptimized)
  9459. this.applyDeoptimizations();
  9460. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  9461. this.id?.markDeclarationReached();
  9462. return initEffect || super.hasEffects(context);
  9463. }
  9464. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9465. return interaction.type === INTERACTION_CALLED && path.length === 0
  9466. ? !interaction.withNew ||
  9467. (this.classConstructor === null
  9468. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  9469. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  9470. false
  9471. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  9472. }
  9473. include(context, includeChildrenRecursively) {
  9474. if (!this.deoptimized)
  9475. this.applyDeoptimizations();
  9476. this.included = true;
  9477. this.superClass?.include(context, includeChildrenRecursively);
  9478. this.body.include(context, includeChildrenRecursively);
  9479. if (this.id) {
  9480. this.id.markDeclarationReached();
  9481. this.id.include();
  9482. }
  9483. }
  9484. initialise() {
  9485. this.id?.declare('class', this);
  9486. for (const method of this.body.body) {
  9487. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  9488. this.classConstructor = method;
  9489. return;
  9490. }
  9491. }
  9492. this.classConstructor = null;
  9493. }
  9494. applyDeoptimizations() {
  9495. this.deoptimized = true;
  9496. for (const definition of this.body.body) {
  9497. if (!(definition.static ||
  9498. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  9499. // Calls to methods are not tracked, ensure that the return value is deoptimized
  9500. definition.deoptimizePath(UNKNOWN_PATH);
  9501. }
  9502. }
  9503. this.context.requestTreeshakingPass();
  9504. }
  9505. getObjectEntity() {
  9506. if (this.objectEntity !== null) {
  9507. return this.objectEntity;
  9508. }
  9509. const staticProperties = [];
  9510. const dynamicMethods = [];
  9511. for (const definition of this.body.body) {
  9512. const properties = definition.static ? staticProperties : dynamicMethods;
  9513. const definitionKind = definition.kind;
  9514. // Note that class fields do not end up on the prototype
  9515. if (properties === dynamicMethods && !definitionKind)
  9516. continue;
  9517. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  9518. let key;
  9519. if (definition.computed) {
  9520. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9521. if (typeof keyValue === 'symbol') {
  9522. properties.push({ key: UnknownKey, kind, property: definition });
  9523. continue;
  9524. }
  9525. else {
  9526. key = String(keyValue);
  9527. }
  9528. }
  9529. else {
  9530. key =
  9531. definition.key instanceof Identifier
  9532. ? definition.key.name
  9533. : String(definition.key.value);
  9534. }
  9535. properties.push({ key, kind, property: definition });
  9536. }
  9537. staticProperties.unshift({
  9538. key: 'prototype',
  9539. kind: 'init',
  9540. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  9541. });
  9542. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  9543. }
  9544. }
  9545. class ClassDeclaration extends ClassNode {
  9546. initialise() {
  9547. super.initialise();
  9548. if (this.id !== null) {
  9549. this.id.variable.isId = true;
  9550. }
  9551. }
  9552. parseNode(esTreeNode) {
  9553. if (esTreeNode.id !== null) {
  9554. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  9555. }
  9556. super.parseNode(esTreeNode);
  9557. }
  9558. render(code, options) {
  9559. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  9560. if (this.id) {
  9561. const { variable, name } = this.id;
  9562. if (format === 'system' && exportNamesByVariable.has(variable)) {
  9563. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  9564. }
  9565. const renderedVariable = variable.getName(getPropertyAccess);
  9566. if (renderedVariable !== name) {
  9567. this.superClass?.render(code, options);
  9568. this.body.render(code, {
  9569. ...options,
  9570. useOriginalName: (_variable) => _variable === variable
  9571. });
  9572. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  9573. code.prependLeft(this.end, ';');
  9574. return;
  9575. }
  9576. }
  9577. super.render(code, options);
  9578. }
  9579. applyDeoptimizations() {
  9580. super.applyDeoptimizations();
  9581. const { id, scope } = this;
  9582. if (id) {
  9583. const { name, variable } = id;
  9584. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  9585. if (accessedVariable !== variable) {
  9586. accessedVariable.forbidName(name);
  9587. }
  9588. }
  9589. }
  9590. }
  9591. }
  9592. class ClassExpression extends ClassNode {
  9593. render(code, options, { renderedSurroundingElement } = BLANK) {
  9594. super.render(code, options);
  9595. if (renderedSurroundingElement === ExpressionStatement$1) {
  9596. code.appendRight(this.start, '(');
  9597. code.prependLeft(this.end, ')');
  9598. }
  9599. }
  9600. }
  9601. class MultiExpression extends ExpressionEntity {
  9602. constructor(expressions) {
  9603. super();
  9604. this.expressions = expressions;
  9605. this.included = false;
  9606. }
  9607. deoptimizePath(path) {
  9608. for (const expression of this.expressions) {
  9609. expression.deoptimizePath(path);
  9610. }
  9611. }
  9612. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9613. return [
  9614. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  9615. false
  9616. ];
  9617. }
  9618. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9619. for (const expression of this.expressions) {
  9620. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  9621. return true;
  9622. }
  9623. return false;
  9624. }
  9625. }
  9626. class ConditionalExpression extends NodeBase {
  9627. constructor() {
  9628. super(...arguments);
  9629. this.expressionsToBeDeoptimized = [];
  9630. this.isBranchResolutionAnalysed = false;
  9631. this.usedBranch = null;
  9632. }
  9633. deoptimizeCache() {
  9634. if (this.usedBranch !== null) {
  9635. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  9636. this.usedBranch = null;
  9637. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  9638. for (const expression of this.expressionsToBeDeoptimized) {
  9639. expression.deoptimizeCache();
  9640. }
  9641. }
  9642. }
  9643. deoptimizePath(path) {
  9644. const usedBranch = this.getUsedBranch();
  9645. if (usedBranch) {
  9646. usedBranch.deoptimizePath(path);
  9647. }
  9648. else {
  9649. this.consequent.deoptimizePath(path);
  9650. this.alternate.deoptimizePath(path);
  9651. }
  9652. }
  9653. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  9654. this.consequent.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9655. this.alternate.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9656. }
  9657. getLiteralValueAtPath(path, recursionTracker, origin) {
  9658. const usedBranch = this.getUsedBranch();
  9659. if (!usedBranch)
  9660. return UnknownValue;
  9661. this.expressionsToBeDeoptimized.push(origin);
  9662. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  9663. }
  9664. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9665. const usedBranch = this.getUsedBranch();
  9666. if (!usedBranch)
  9667. return [
  9668. new MultiExpression([
  9669. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  9670. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  9671. ]),
  9672. false
  9673. ];
  9674. this.expressionsToBeDeoptimized.push(origin);
  9675. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9676. }
  9677. hasEffects(context) {
  9678. if (this.test.hasEffects(context))
  9679. return true;
  9680. const usedBranch = this.getUsedBranch();
  9681. if (!usedBranch) {
  9682. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  9683. }
  9684. return usedBranch.hasEffects(context);
  9685. }
  9686. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9687. const usedBranch = this.getUsedBranch();
  9688. if (!usedBranch) {
  9689. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  9690. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  9691. }
  9692. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  9693. }
  9694. include(context, includeChildrenRecursively) {
  9695. this.included = true;
  9696. const usedBranch = this.getUsedBranch();
  9697. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  9698. this.test.include(context, includeChildrenRecursively);
  9699. this.consequent.include(context, includeChildrenRecursively);
  9700. this.alternate.include(context, includeChildrenRecursively);
  9701. }
  9702. else {
  9703. usedBranch.include(context, includeChildrenRecursively);
  9704. }
  9705. }
  9706. includeCallArguments(context, parameters) {
  9707. const usedBranch = this.getUsedBranch();
  9708. if (usedBranch) {
  9709. usedBranch.includeCallArguments(context, parameters);
  9710. }
  9711. else {
  9712. this.consequent.includeCallArguments(context, parameters);
  9713. this.alternate.includeCallArguments(context, parameters);
  9714. }
  9715. }
  9716. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  9717. const usedBranch = this.getUsedBranch();
  9718. if (this.test.included) {
  9719. this.test.render(code, options, { renderedSurroundingElement });
  9720. this.consequent.render(code, options);
  9721. this.alternate.render(code, options);
  9722. }
  9723. else {
  9724. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  9725. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  9726. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  9727. : colonPos) + 1);
  9728. if (preventASI) {
  9729. removeLineBreaks(code, inclusionStart, usedBranch.start);
  9730. }
  9731. code.remove(this.start, inclusionStart);
  9732. if (this.consequent.included) {
  9733. code.remove(colonPos, this.end);
  9734. }
  9735. removeAnnotations(this, code);
  9736. usedBranch.render(code, options, {
  9737. isCalleeOfRenderedParent,
  9738. preventASI: true,
  9739. renderedParentType: renderedParentType || this.parent.type,
  9740. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  9741. });
  9742. }
  9743. }
  9744. getUsedBranch() {
  9745. if (this.isBranchResolutionAnalysed) {
  9746. return this.usedBranch;
  9747. }
  9748. this.isBranchResolutionAnalysed = true;
  9749. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9750. return typeof testValue === 'symbol'
  9751. ? null
  9752. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  9753. }
  9754. }
  9755. class ContinueStatement extends NodeBase {
  9756. hasEffects(context) {
  9757. if (this.label) {
  9758. if (!context.ignore.labels.has(this.label.name))
  9759. return true;
  9760. context.includedLabels.add(this.label.name);
  9761. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  9762. }
  9763. else {
  9764. if (!context.ignore.continues)
  9765. return true;
  9766. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  9767. }
  9768. return false;
  9769. }
  9770. include(context) {
  9771. this.included = true;
  9772. if (this.label) {
  9773. this.label.include();
  9774. context.includedLabels.add(this.label.name);
  9775. }
  9776. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  9777. }
  9778. }
  9779. class DoWhileStatement extends NodeBase {
  9780. hasEffects(context) {
  9781. if (this.test.hasEffects(context))
  9782. return true;
  9783. const { brokenFlow, ignore } = context;
  9784. const { breaks, continues } = ignore;
  9785. ignore.breaks = true;
  9786. ignore.continues = true;
  9787. if (this.body.hasEffects(context))
  9788. return true;
  9789. ignore.breaks = breaks;
  9790. ignore.continues = continues;
  9791. context.brokenFlow = brokenFlow;
  9792. return false;
  9793. }
  9794. include(context, includeChildrenRecursively) {
  9795. this.included = true;
  9796. this.test.include(context, includeChildrenRecursively);
  9797. const { brokenFlow } = context;
  9798. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9799. context.brokenFlow = brokenFlow;
  9800. }
  9801. }
  9802. class EmptyStatement extends NodeBase {
  9803. hasEffects() {
  9804. return false;
  9805. }
  9806. }
  9807. class ExportAllDeclaration extends NodeBase {
  9808. hasEffects() {
  9809. return false;
  9810. }
  9811. initialise() {
  9812. this.context.addExport(this);
  9813. }
  9814. render(code, _options, nodeRenderOptions) {
  9815. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  9816. }
  9817. applyDeoptimizations() { }
  9818. }
  9819. ExportAllDeclaration.prototype.needsBoundaries = true;
  9820. class FunctionDeclaration extends FunctionNode {
  9821. initialise() {
  9822. super.initialise();
  9823. if (this.id !== null) {
  9824. this.id.variable.isId = true;
  9825. }
  9826. }
  9827. parseNode(esTreeNode) {
  9828. if (esTreeNode.id !== null) {
  9829. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  9830. }
  9831. super.parseNode(esTreeNode);
  9832. }
  9833. }
  9834. // The header ends at the first non-white-space after "default"
  9835. function getDeclarationStart(code, start) {
  9836. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  9837. }
  9838. function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
  9839. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  9840. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
  9841. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  9842. if (generatorStarPos === -1) {
  9843. return declarationEnd;
  9844. }
  9845. return declarationEnd + generatorStarPos + 1;
  9846. }
  9847. class ExportDefaultDeclaration extends NodeBase {
  9848. include(context, includeChildrenRecursively) {
  9849. super.include(context, includeChildrenRecursively);
  9850. if (includeChildrenRecursively) {
  9851. this.context.includeVariableInModule(this.variable);
  9852. }
  9853. }
  9854. initialise() {
  9855. const declaration = this.declaration;
  9856. this.declarationName =
  9857. (declaration.id && declaration.id.name) || this.declaration.name;
  9858. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  9859. this.context.addExport(this);
  9860. }
  9861. render(code, options, nodeRenderOptions) {
  9862. const { start, end } = nodeRenderOptions;
  9863. const declarationStart = getDeclarationStart(code.original, this.start);
  9864. if (this.declaration instanceof FunctionDeclaration) {
  9865. this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
  9866. }
  9867. else if (this.declaration instanceof ClassDeclaration) {
  9868. this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
  9869. }
  9870. else if (this.variable.getOriginalVariable() !== this.variable) {
  9871. // Remove altogether to prevent re-declaring the same variable
  9872. treeshakeNode(this, code, start, end);
  9873. return;
  9874. }
  9875. else if (this.variable.included) {
  9876. this.renderVariableDeclaration(code, declarationStart, options);
  9877. }
  9878. else {
  9879. code.remove(this.start, declarationStart);
  9880. this.declaration.render(code, options, {
  9881. renderedSurroundingElement: ExpressionStatement$1
  9882. });
  9883. if (code.original[this.end - 1] !== ';') {
  9884. code.appendLeft(this.end, ';');
  9885. }
  9886. return;
  9887. }
  9888. this.declaration.render(code, options);
  9889. }
  9890. applyDeoptimizations() { }
  9891. renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
  9892. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  9893. const name = this.variable.getName(getPropertyAccess);
  9894. // Remove `export default`
  9895. code.remove(this.start, declarationStart);
  9896. if (needsId) {
  9897. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
  9898. }
  9899. if (format === 'system' &&
  9900. this.declaration instanceof ClassDeclaration &&
  9901. exportNamesByVariable.has(this.variable)) {
  9902. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  9903. }
  9904. }
  9905. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  9906. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  9907. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  9908. if (systemExportNames) {
  9909. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
  9910. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  9911. }
  9912. else {
  9913. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  9914. if (!hasTrailingSemicolon) {
  9915. code.appendLeft(this.end, ';');
  9916. }
  9917. }
  9918. }
  9919. }
  9920. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  9921. class ExportNamedDeclaration extends NodeBase {
  9922. bind() {
  9923. // Do not bind specifiers
  9924. this.declaration?.bind();
  9925. }
  9926. hasEffects(context) {
  9927. return !!this.declaration?.hasEffects(context);
  9928. }
  9929. initialise() {
  9930. this.context.addExport(this);
  9931. }
  9932. render(code, options, nodeRenderOptions) {
  9933. const { start, end } = nodeRenderOptions;
  9934. if (this.declaration === null) {
  9935. code.remove(start, end);
  9936. }
  9937. else {
  9938. code.remove(this.start, this.declaration.start);
  9939. this.declaration.render(code, options, { end, start });
  9940. }
  9941. }
  9942. applyDeoptimizations() { }
  9943. }
  9944. ExportNamedDeclaration.prototype.needsBoundaries = true;
  9945. class ExportSpecifier extends NodeBase {
  9946. applyDeoptimizations() { }
  9947. }
  9948. class ForInStatement extends NodeBase {
  9949. createScope(parentScope) {
  9950. this.scope = new BlockScope(parentScope);
  9951. }
  9952. hasEffects(context) {
  9953. const { body, deoptimized, left, right } = this;
  9954. if (!deoptimized)
  9955. this.applyDeoptimizations();
  9956. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  9957. return true;
  9958. const { brokenFlow, ignore } = context;
  9959. const { breaks, continues } = ignore;
  9960. ignore.breaks = true;
  9961. ignore.continues = true;
  9962. if (body.hasEffects(context))
  9963. return true;
  9964. ignore.breaks = breaks;
  9965. ignore.continues = continues;
  9966. context.brokenFlow = brokenFlow;
  9967. return false;
  9968. }
  9969. include(context, includeChildrenRecursively) {
  9970. const { body, deoptimized, left, right } = this;
  9971. if (!deoptimized)
  9972. this.applyDeoptimizations();
  9973. this.included = true;
  9974. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  9975. right.include(context, includeChildrenRecursively);
  9976. const { brokenFlow } = context;
  9977. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9978. context.brokenFlow = brokenFlow;
  9979. }
  9980. initialise() {
  9981. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  9982. }
  9983. render(code, options) {
  9984. this.left.render(code, options, NO_SEMICOLON);
  9985. this.right.render(code, options, NO_SEMICOLON);
  9986. // handle no space between "in" and the right side
  9987. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  9988. code.prependLeft(this.right.start, ' ');
  9989. }
  9990. this.body.render(code, options);
  9991. }
  9992. applyDeoptimizations() {
  9993. this.deoptimized = true;
  9994. this.left.deoptimizePath(EMPTY_PATH);
  9995. this.context.requestTreeshakingPass();
  9996. }
  9997. }
  9998. class ForOfStatement extends NodeBase {
  9999. createScope(parentScope) {
  10000. this.scope = new BlockScope(parentScope);
  10001. }
  10002. hasEffects() {
  10003. if (!this.deoptimized)
  10004. this.applyDeoptimizations();
  10005. // Placeholder until proper Symbol.Iterator support
  10006. return true;
  10007. }
  10008. include(context, includeChildrenRecursively) {
  10009. const { body, deoptimized, left, right } = this;
  10010. if (!deoptimized)
  10011. this.applyDeoptimizations();
  10012. this.included = true;
  10013. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  10014. right.include(context, includeChildrenRecursively);
  10015. const { brokenFlow } = context;
  10016. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  10017. context.brokenFlow = brokenFlow;
  10018. }
  10019. initialise() {
  10020. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  10021. }
  10022. render(code, options) {
  10023. this.left.render(code, options, NO_SEMICOLON);
  10024. this.right.render(code, options, NO_SEMICOLON);
  10025. // handle no space between "of" and the right side
  10026. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  10027. code.prependLeft(this.right.start, ' ');
  10028. }
  10029. this.body.render(code, options);
  10030. }
  10031. applyDeoptimizations() {
  10032. this.deoptimized = true;
  10033. this.left.deoptimizePath(EMPTY_PATH);
  10034. this.context.requestTreeshakingPass();
  10035. }
  10036. }
  10037. class ForStatement extends NodeBase {
  10038. createScope(parentScope) {
  10039. this.scope = new BlockScope(parentScope);
  10040. }
  10041. hasEffects(context) {
  10042. if (this.init?.hasEffects(context) ||
  10043. this.test?.hasEffects(context) ||
  10044. this.update?.hasEffects(context))
  10045. return true;
  10046. const { brokenFlow, ignore } = context;
  10047. const { breaks, continues } = ignore;
  10048. ignore.breaks = true;
  10049. ignore.continues = true;
  10050. if (this.body.hasEffects(context))
  10051. return true;
  10052. ignore.breaks = breaks;
  10053. ignore.continues = continues;
  10054. context.brokenFlow = brokenFlow;
  10055. return false;
  10056. }
  10057. include(context, includeChildrenRecursively) {
  10058. this.included = true;
  10059. this.init?.include(context, includeChildrenRecursively, { asSingleStatement: true });
  10060. this.test?.include(context, includeChildrenRecursively);
  10061. const { brokenFlow } = context;
  10062. this.update?.include(context, includeChildrenRecursively);
  10063. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  10064. context.brokenFlow = brokenFlow;
  10065. }
  10066. render(code, options) {
  10067. this.init?.render(code, options, NO_SEMICOLON);
  10068. this.test?.render(code, options, NO_SEMICOLON);
  10069. this.update?.render(code, options, NO_SEMICOLON);
  10070. this.body.render(code, options);
  10071. }
  10072. }
  10073. class FunctionExpression extends FunctionNode {
  10074. render(code, options, { renderedSurroundingElement } = BLANK) {
  10075. super.render(code, options);
  10076. if (renderedSurroundingElement === ExpressionStatement$1) {
  10077. code.appendRight(this.start, '(');
  10078. code.prependLeft(this.end, ')');
  10079. }
  10080. }
  10081. }
  10082. class TrackingScope extends BlockScope {
  10083. constructor() {
  10084. super(...arguments);
  10085. this.hoistedDeclarations = [];
  10086. }
  10087. addDeclaration(identifier, context, init, isHoisted) {
  10088. this.hoistedDeclarations.push(identifier);
  10089. return super.addDeclaration(identifier, context, init, isHoisted);
  10090. }
  10091. }
  10092. const unset = Symbol('unset');
  10093. class IfStatement extends NodeBase {
  10094. constructor() {
  10095. super(...arguments);
  10096. this.testValue = unset;
  10097. }
  10098. deoptimizeCache() {
  10099. this.testValue = UnknownValue;
  10100. }
  10101. hasEffects(context) {
  10102. if (this.test.hasEffects(context)) {
  10103. return true;
  10104. }
  10105. const testValue = this.getTestValue();
  10106. if (typeof testValue === 'symbol') {
  10107. const { brokenFlow } = context;
  10108. if (this.consequent.hasEffects(context))
  10109. return true;
  10110. // eslint-disable-next-line unicorn/consistent-destructuring
  10111. const consequentBrokenFlow = context.brokenFlow;
  10112. context.brokenFlow = brokenFlow;
  10113. if (this.alternate === null)
  10114. return false;
  10115. if (this.alternate.hasEffects(context))
  10116. return true;
  10117. context.brokenFlow =
  10118. // eslint-disable-next-line unicorn/consistent-destructuring
  10119. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  10120. return false;
  10121. }
  10122. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  10123. }
  10124. include(context, includeChildrenRecursively) {
  10125. this.included = true;
  10126. if (includeChildrenRecursively) {
  10127. this.includeRecursively(includeChildrenRecursively, context);
  10128. }
  10129. else {
  10130. const testValue = this.getTestValue();
  10131. if (typeof testValue === 'symbol') {
  10132. this.includeUnknownTest(context);
  10133. }
  10134. else {
  10135. this.includeKnownTest(context, testValue);
  10136. }
  10137. }
  10138. }
  10139. parseNode(esTreeNode) {
  10140. this.consequentScope = new TrackingScope(this.scope);
  10141. this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
  10142. if (esTreeNode.alternate) {
  10143. this.alternateScope = new TrackingScope(this.scope);
  10144. this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
  10145. }
  10146. super.parseNode(esTreeNode);
  10147. }
  10148. render(code, options) {
  10149. const { snippets: { getPropertyAccess } } = options;
  10150. // Note that unknown test values are always included
  10151. const testValue = this.getTestValue();
  10152. const hoistedDeclarations = [];
  10153. const includesIfElse = this.test.included;
  10154. const noTreeshake = !this.context.options.treeshake;
  10155. if (includesIfElse) {
  10156. this.test.render(code, options);
  10157. }
  10158. else {
  10159. code.remove(this.start, this.consequent.start);
  10160. }
  10161. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  10162. this.consequent.render(code, options);
  10163. }
  10164. else {
  10165. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  10166. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  10167. }
  10168. if (this.alternate) {
  10169. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  10170. if (includesIfElse) {
  10171. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  10172. code.prependLeft(this.alternate.start, ' ');
  10173. }
  10174. }
  10175. else {
  10176. code.remove(this.consequent.end, this.alternate.start);
  10177. }
  10178. this.alternate.render(code, options);
  10179. }
  10180. else {
  10181. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  10182. code.overwrite(this.alternate.start, this.end, ';');
  10183. }
  10184. else {
  10185. code.remove(this.consequent.end, this.end);
  10186. }
  10187. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  10188. }
  10189. }
  10190. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  10191. }
  10192. applyDeoptimizations() { }
  10193. getTestValue() {
  10194. if (this.testValue === unset) {
  10195. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  10196. }
  10197. return this.testValue;
  10198. }
  10199. includeKnownTest(context, testValue) {
  10200. if (this.test.shouldBeIncluded(context)) {
  10201. this.test.include(context, false);
  10202. }
  10203. if (testValue && this.consequent.shouldBeIncluded(context)) {
  10204. this.consequent.include(context, false, { asSingleStatement: true });
  10205. }
  10206. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  10207. this.alternate.include(context, false, { asSingleStatement: true });
  10208. }
  10209. }
  10210. includeRecursively(includeChildrenRecursively, context) {
  10211. this.test.include(context, includeChildrenRecursively);
  10212. this.consequent.include(context, includeChildrenRecursively);
  10213. this.alternate?.include(context, includeChildrenRecursively);
  10214. }
  10215. includeUnknownTest(context) {
  10216. this.test.include(context, false);
  10217. const { brokenFlow } = context;
  10218. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  10219. if (this.consequent.shouldBeIncluded(context)) {
  10220. this.consequent.include(context, false, { asSingleStatement: true });
  10221. // eslint-disable-next-line unicorn/consistent-destructuring
  10222. consequentBrokenFlow = context.brokenFlow;
  10223. context.brokenFlow = brokenFlow;
  10224. }
  10225. if (this.alternate?.shouldBeIncluded(context)) {
  10226. this.alternate.include(context, false, { asSingleStatement: true });
  10227. context.brokenFlow =
  10228. // eslint-disable-next-line unicorn/consistent-destructuring
  10229. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  10230. }
  10231. }
  10232. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  10233. const hoistedVariables = [
  10234. ...new Set(hoistedDeclarations.map(identifier => {
  10235. const variable = identifier.variable;
  10236. return variable.included ? variable.getName(getPropertyAccess) : '';
  10237. }))
  10238. ]
  10239. .filter(Boolean)
  10240. .join(', ');
  10241. if (hoistedVariables) {
  10242. const parentType = this.parent.type;
  10243. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  10244. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  10245. if (needsBraces) {
  10246. code.appendLeft(this.end, ` }`);
  10247. }
  10248. }
  10249. }
  10250. shouldKeepAlternateBranch() {
  10251. let currentParent = this.parent;
  10252. do {
  10253. if (currentParent instanceof IfStatement && currentParent.alternate) {
  10254. return true;
  10255. }
  10256. if (currentParent instanceof BlockStatement) {
  10257. return false;
  10258. }
  10259. currentParent = currentParent.parent;
  10260. } while (currentParent);
  10261. return false;
  10262. }
  10263. }
  10264. class ImportAttribute extends NodeBase {
  10265. }
  10266. class ImportDeclaration extends NodeBase {
  10267. // Do not bind specifiers or assertions
  10268. bind() { }
  10269. hasEffects() {
  10270. return false;
  10271. }
  10272. initialise() {
  10273. this.context.addImport(this);
  10274. }
  10275. render(code, _options, nodeRenderOptions) {
  10276. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  10277. }
  10278. applyDeoptimizations() { }
  10279. }
  10280. ImportDeclaration.prototype.needsBoundaries = true;
  10281. class ImportDefaultSpecifier extends NodeBase {
  10282. applyDeoptimizations() { }
  10283. }
  10284. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  10285. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  10286. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  10287. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  10288. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  10289. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  10290. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  10291. const defaultInteropHelpersByInteropType = {
  10292. auto: INTEROP_DEFAULT_VARIABLE,
  10293. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  10294. default: null,
  10295. defaultOnly: null,
  10296. esModule: null
  10297. };
  10298. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  10299. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  10300. const namespaceInteropHelpersByInteropType = {
  10301. auto: INTEROP_NAMESPACE_VARIABLE,
  10302. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  10303. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  10304. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  10305. esModule: null
  10306. };
  10307. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  10308. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
  10309. const usedHelpers = new Set(additionalHelpers);
  10310. for (const variable of HELPER_NAMES) {
  10311. if (accessedGlobals.has(variable)) {
  10312. usedHelpers.add(variable);
  10313. }
  10314. }
  10315. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  10316. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  10317. : '').join('');
  10318. };
  10319. const HELPER_GENERATORS = {
  10320. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  10321. const { _, getDirectReturnFunction, n } = snippets;
  10322. const [left, right] = getDirectReturnFunction(['e'], {
  10323. functionReturn: true,
  10324. lineBreakIndent: null,
  10325. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  10326. });
  10327. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  10328. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  10329. },
  10330. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  10331. const { _, getDirectReturnFunction, n } = snippets;
  10332. const [left, right] = getDirectReturnFunction(['e'], {
  10333. functionReturn: true,
  10334. lineBreakIndent: null,
  10335. name: INTEROP_DEFAULT_VARIABLE
  10336. });
  10337. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  10338. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  10339. },
  10340. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  10341. const { _, getDirectReturnFunction, n } = snippets;
  10342. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  10343. const [left, right] = getDirectReturnFunction(['e'], {
  10344. functionReturn: true,
  10345. lineBreakIndent: null,
  10346. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  10347. });
  10348. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  10349. }
  10350. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  10351. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  10352. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  10353. `}${n}${n}`);
  10354. },
  10355. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
  10356. const { getDirectReturnFunction, getObject, n } = snippets;
  10357. const [left, right] = getDirectReturnFunction(['e'], {
  10358. functionReturn: true,
  10359. lineBreakIndent: null,
  10360. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  10361. });
  10362. return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
  10363. ['__proto__', 'null'],
  10364. ['default', 'e']
  10365. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  10366. },
  10367. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  10368. const { _, n } = snippets;
  10369. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  10370. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  10371. `}${n}${n}`);
  10372. },
  10373. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  10374. const { _, getDirectReturnFunction, n } = snippets;
  10375. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  10376. const [left, right] = getDirectReturnFunction(['e'], {
  10377. functionReturn: true,
  10378. lineBreakIndent: null,
  10379. name: INTEROP_NAMESPACE_VARIABLE
  10380. });
  10381. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  10382. }
  10383. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  10384. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  10385. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  10386. `}${n}${n}`);
  10387. },
  10388. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  10389. const { _, cnst, n } = snippets;
  10390. const useForEach = cnst === 'var' && liveBindings;
  10391. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  10392. `${t}${loopOverNamespaces(`{${n}` +
  10393. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  10394. (liveBindings
  10395. ? useForEach
  10396. ? copyOwnPropertyLiveBinding
  10397. : copyPropertyLiveBinding
  10398. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  10399. `${t}${t}${t}}${n}` +
  10400. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  10401. `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
  10402. `}${n}${n}`);
  10403. }
  10404. };
  10405. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  10406. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  10407. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  10408. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, namespaceToStringTag) => {
  10409. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  10410. const copyProperty = `{${n}` +
  10411. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  10412. `${index}${t}}`;
  10413. return (`${index}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
  10414. ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
  10415. : ''});${n}` +
  10416. `${index}if${_}(e)${_}{${n}` +
  10417. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  10418. `${index}}${n}` +
  10419. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  10420. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  10421. };
  10422. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  10423. ? `for${_}(${cnst} k in e)${_}${body}`
  10424. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10425. isAsync: false,
  10426. name: null
  10427. })}${body})${s}`;
  10428. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  10429. if (useForEach) {
  10430. const [left, right] = getDirectReturnFunction(['e'], {
  10431. functionReturn: false,
  10432. lineBreakIndent: { base: t, t },
  10433. name: null
  10434. });
  10435. return (`m.forEach(${left}` +
  10436. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10437. isAsync: false,
  10438. name: null
  10439. })}${body})${right});`);
  10440. }
  10441. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  10442. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  10443. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  10444. };
  10445. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  10446. const { _, n } = snippets;
  10447. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  10448. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  10449. `${index}}${n}`);
  10450. };
  10451. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10452. const [left, right] = getDirectReturnFunction([], {
  10453. functionReturn: true,
  10454. lineBreakIndent: null,
  10455. name: null
  10456. });
  10457. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10458. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10459. `${index}${t}enumerable:${_}true,${n}` +
  10460. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  10461. `${index}});${n}`);
  10462. };
  10463. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10464. const [left, right] = getDirectReturnFunction([], {
  10465. functionReturn: true,
  10466. lineBreakIndent: null,
  10467. name: null
  10468. });
  10469. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10470. `${index}if${_}(d)${_}{${n}` +
  10471. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10472. `${index}${t}${t}enumerable:${_}true,${n}` +
  10473. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  10474. `${index}${t}});${n}` +
  10475. `${index}}${n}`);
  10476. };
  10477. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  10478. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  10479. const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
  10480. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  10481. : fragment;
  10482. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  10483. function getToStringTagValue(getObject) {
  10484. return getObject([['value', "'Module'"]], {
  10485. lineBreakIndent: null
  10486. });
  10487. }
  10488. // TODO once ImportExpression follows official ESTree specs with "null" as
  10489. // default, keys.ts should be updated
  10490. class ImportExpression extends NodeBase {
  10491. constructor() {
  10492. super(...arguments);
  10493. this.inlineNamespace = null;
  10494. this.assertions = null;
  10495. this.mechanism = null;
  10496. this.namespaceExportName = undefined;
  10497. this.resolution = null;
  10498. this.resolutionString = null;
  10499. }
  10500. // Do not bind assertions
  10501. bind() {
  10502. this.source.bind();
  10503. }
  10504. hasEffects() {
  10505. return true;
  10506. }
  10507. include(context, includeChildrenRecursively) {
  10508. if (!this.included) {
  10509. this.included = true;
  10510. this.context.includeDynamicImport(this);
  10511. this.scope.addAccessedDynamicImport(this);
  10512. }
  10513. this.source.include(context, includeChildrenRecursively);
  10514. }
  10515. initialise() {
  10516. this.context.addDynamicImport(this);
  10517. }
  10518. parseNode(esTreeNode) {
  10519. // Keep the source AST to be used by renderDynamicImport
  10520. super.parseNode(esTreeNode, ['source']);
  10521. }
  10522. render(code, options) {
  10523. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess } } = options;
  10524. if (this.inlineNamespace) {
  10525. const [left, right] = getDirectReturnFunction([], {
  10526. functionReturn: true,
  10527. lineBreakIndent: null,
  10528. name: null
  10529. });
  10530. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  10531. return;
  10532. }
  10533. if (this.mechanism) {
  10534. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  10535. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  10536. }
  10537. if (this.resolutionString) {
  10538. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  10539. if (this.namespaceExportName) {
  10540. const [left, right] = getDirectReturnFunction(['n'], {
  10541. functionReturn: true,
  10542. lineBreakIndent: null,
  10543. name: null
  10544. });
  10545. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  10546. }
  10547. }
  10548. else {
  10549. this.source.render(code, options);
  10550. }
  10551. if (this.assertions !== true) {
  10552. if (this.arguments) {
  10553. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  10554. }
  10555. if (this.assertions) {
  10556. code.appendLeft(this.end - 1, `,${_}${getObject([['assert', this.assertions]], {
  10557. lineBreakIndent: null
  10558. })}`);
  10559. }
  10560. }
  10561. }
  10562. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, assertions) {
  10563. const { format } = options;
  10564. this.inlineNamespace = null;
  10565. this.resolution = resolution;
  10566. this.resolutionString = resolutionString;
  10567. this.namespaceExportName = namespaceExportName;
  10568. this.assertions = assertions;
  10569. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  10570. let helper;
  10571. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  10572. if (helper) {
  10573. accessedGlobals.push(helper);
  10574. }
  10575. if (accessedGlobals.length > 0) {
  10576. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  10577. }
  10578. }
  10579. setInternalResolution(inlineNamespace) {
  10580. this.inlineNamespace = inlineNamespace;
  10581. }
  10582. applyDeoptimizations() { }
  10583. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  10584. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  10585. {
  10586. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  10587. format,
  10588. moduleId: this.context.module.id,
  10589. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  10590. }
  10591. ]);
  10592. if (mechanism) {
  10593. return { helper: null, mechanism };
  10594. }
  10595. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  10596. switch (format) {
  10597. case 'cjs': {
  10598. if (dynamicImportInCjs &&
  10599. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  10600. return { helper: null, mechanism: null };
  10601. }
  10602. const helper = getInteropHelper(resolution, exportMode, interop);
  10603. let left = `require(`;
  10604. let right = `)`;
  10605. if (helper) {
  10606. left = `/*#__PURE__*/${helper}(${left}`;
  10607. right += ')';
  10608. }
  10609. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  10610. functionReturn: true,
  10611. lineBreakIndent: null,
  10612. name: null
  10613. });
  10614. left = `Promise.resolve().then(${functionLeft}${left}`;
  10615. right += `${functionRight})`;
  10616. if (!arrowFunctions && hasDynamicTarget) {
  10617. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  10618. needsArrowReturnParens: false,
  10619. needsWrappedFunction: true
  10620. });
  10621. right = ')';
  10622. }
  10623. return {
  10624. helper,
  10625. mechanism: { left, right }
  10626. };
  10627. }
  10628. case 'amd': {
  10629. const resolve = compact ? 'c' : 'resolve';
  10630. const reject = compact ? 'e' : 'reject';
  10631. const helper = getInteropHelper(resolution, exportMode, interop);
  10632. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  10633. functionReturn: false,
  10634. lineBreakIndent: null,
  10635. name: null
  10636. });
  10637. const resolveNamespace = helper
  10638. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  10639. : resolve;
  10640. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  10641. functionReturn: false,
  10642. lineBreakIndent: null,
  10643. name: null
  10644. });
  10645. let left = `new Promise(${handlerLeft}require([`;
  10646. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  10647. if (!arrowFunctions && hasDynamicTarget) {
  10648. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  10649. needsArrowReturnParens: false,
  10650. needsWrappedFunction: true
  10651. });
  10652. right = ')';
  10653. }
  10654. return {
  10655. helper,
  10656. mechanism: { left, right }
  10657. };
  10658. }
  10659. case 'system': {
  10660. return {
  10661. helper: null,
  10662. mechanism: {
  10663. left: 'module.import(',
  10664. right: ')'
  10665. }
  10666. };
  10667. }
  10668. case 'es': {
  10669. if (dynamicImportFunction) {
  10670. return {
  10671. helper: null,
  10672. mechanism: {
  10673. left: `${dynamicImportFunction}(`,
  10674. right: ')'
  10675. }
  10676. };
  10677. }
  10678. }
  10679. }
  10680. return { helper: null, mechanism: null };
  10681. }
  10682. }
  10683. function getInteropHelper(resolution, exportMode, interop) {
  10684. return exportMode === 'external'
  10685. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  10686. : exportMode === 'default'
  10687. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  10688. : null;
  10689. }
  10690. const accessedImportGlobals = {
  10691. amd: ['require'],
  10692. cjs: ['require'],
  10693. system: ['module']
  10694. };
  10695. class ImportNamespaceSpecifier extends NodeBase {
  10696. applyDeoptimizations() { }
  10697. }
  10698. class ImportSpecifier extends NodeBase {
  10699. applyDeoptimizations() { }
  10700. }
  10701. class LabeledStatement extends NodeBase {
  10702. hasEffects(context) {
  10703. const brokenFlow = context.brokenFlow;
  10704. context.ignore.labels.add(this.label.name);
  10705. if (this.body.hasEffects(context))
  10706. return true;
  10707. context.ignore.labels.delete(this.label.name);
  10708. if (context.includedLabels.has(this.label.name)) {
  10709. context.includedLabels.delete(this.label.name);
  10710. context.brokenFlow = brokenFlow;
  10711. }
  10712. return false;
  10713. }
  10714. include(context, includeChildrenRecursively) {
  10715. this.included = true;
  10716. const brokenFlow = context.brokenFlow;
  10717. this.body.include(context, includeChildrenRecursively);
  10718. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  10719. this.label.include();
  10720. context.includedLabels.delete(this.label.name);
  10721. context.brokenFlow = brokenFlow;
  10722. }
  10723. }
  10724. render(code, options) {
  10725. if (this.label.included) {
  10726. this.label.render(code, options);
  10727. }
  10728. else {
  10729. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  10730. }
  10731. this.body.render(code, options);
  10732. }
  10733. }
  10734. class LogicalExpression extends NodeBase {
  10735. constructor() {
  10736. super(...arguments);
  10737. // We collect deoptimization information if usedBranch !== null
  10738. this.expressionsToBeDeoptimized = [];
  10739. this.isBranchResolutionAnalysed = false;
  10740. this.usedBranch = null;
  10741. }
  10742. deoptimizeCache() {
  10743. if (this.usedBranch) {
  10744. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  10745. this.usedBranch = null;
  10746. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  10747. for (const expression of this.expressionsToBeDeoptimized) {
  10748. expression.deoptimizeCache();
  10749. }
  10750. // Request another pass because we need to ensure "include" runs again if
  10751. // it is rendered
  10752. this.context.requestTreeshakingPass();
  10753. }
  10754. }
  10755. deoptimizePath(path) {
  10756. const usedBranch = this.getUsedBranch();
  10757. if (usedBranch) {
  10758. usedBranch.deoptimizePath(path);
  10759. }
  10760. else {
  10761. this.left.deoptimizePath(path);
  10762. this.right.deoptimizePath(path);
  10763. }
  10764. }
  10765. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10766. this.left.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10767. this.right.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10768. }
  10769. getLiteralValueAtPath(path, recursionTracker, origin) {
  10770. const usedBranch = this.getUsedBranch();
  10771. if (!usedBranch)
  10772. return UnknownValue;
  10773. this.expressionsToBeDeoptimized.push(origin);
  10774. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  10775. }
  10776. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10777. const usedBranch = this.getUsedBranch();
  10778. if (!usedBranch)
  10779. return [
  10780. new MultiExpression([
  10781. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  10782. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  10783. ]),
  10784. false
  10785. ];
  10786. this.expressionsToBeDeoptimized.push(origin);
  10787. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10788. }
  10789. hasEffects(context) {
  10790. if (this.left.hasEffects(context)) {
  10791. return true;
  10792. }
  10793. if (this.getUsedBranch() !== this.left) {
  10794. return this.right.hasEffects(context);
  10795. }
  10796. return false;
  10797. }
  10798. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10799. const usedBranch = this.getUsedBranch();
  10800. if (!usedBranch) {
  10801. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  10802. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  10803. }
  10804. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  10805. }
  10806. include(context, includeChildrenRecursively) {
  10807. this.included = true;
  10808. const usedBranch = this.getUsedBranch();
  10809. if (includeChildrenRecursively ||
  10810. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  10811. !usedBranch) {
  10812. this.left.include(context, includeChildrenRecursively);
  10813. this.right.include(context, includeChildrenRecursively);
  10814. }
  10815. else {
  10816. usedBranch.include(context, includeChildrenRecursively);
  10817. }
  10818. }
  10819. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  10820. if (!this.left.included || !this.right.included) {
  10821. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  10822. if (this.right.included) {
  10823. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  10824. code.remove(this.start, removePos);
  10825. if (preventASI) {
  10826. removeLineBreaks(code, removePos, this.right.start);
  10827. }
  10828. }
  10829. else {
  10830. code.remove(operatorPos, this.end);
  10831. }
  10832. removeAnnotations(this, code);
  10833. this.getUsedBranch().render(code, options, {
  10834. isCalleeOfRenderedParent,
  10835. preventASI,
  10836. renderedParentType: renderedParentType || this.parent.type,
  10837. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  10838. });
  10839. }
  10840. else {
  10841. this.left.render(code, options, {
  10842. preventASI,
  10843. renderedSurroundingElement
  10844. });
  10845. this.right.render(code, options);
  10846. }
  10847. }
  10848. getUsedBranch() {
  10849. if (!this.isBranchResolutionAnalysed) {
  10850. this.isBranchResolutionAnalysed = true;
  10851. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10852. if (typeof leftValue === 'symbol') {
  10853. return null;
  10854. }
  10855. else {
  10856. this.usedBranch =
  10857. (this.operator === '||' && leftValue) ||
  10858. (this.operator === '&&' && !leftValue) ||
  10859. (this.operator === '??' && leftValue != null)
  10860. ? this.left
  10861. : this.right;
  10862. }
  10863. }
  10864. return this.usedBranch;
  10865. }
  10866. }
  10867. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  10868. const IMPORT = 'import';
  10869. class MetaProperty extends NodeBase {
  10870. constructor() {
  10871. super(...arguments);
  10872. this.metaProperty = null;
  10873. this.preliminaryChunkId = null;
  10874. this.referenceId = null;
  10875. }
  10876. getReferencedFileName(outputPluginDriver) {
  10877. const { meta: { name }, metaProperty } = this;
  10878. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  10879. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  10880. }
  10881. return null;
  10882. }
  10883. hasEffects() {
  10884. return false;
  10885. }
  10886. hasEffectsOnInteractionAtPath(path, { type }) {
  10887. return path.length > 1 || type !== INTERACTION_ACCESSED;
  10888. }
  10889. include() {
  10890. if (!this.included) {
  10891. this.included = true;
  10892. if (this.meta.name === IMPORT) {
  10893. this.context.addImportMeta(this);
  10894. const parent = this.parent;
  10895. const metaProperty = (this.metaProperty =
  10896. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  10897. ? parent.propertyKey
  10898. : null);
  10899. if (metaProperty?.startsWith(FILE_PREFIX)) {
  10900. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  10901. }
  10902. }
  10903. }
  10904. }
  10905. render(code, { format, pluginDriver, snippets }) {
  10906. const { context: { module: { id: moduleId } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  10907. if (name !== IMPORT)
  10908. return;
  10909. const chunkId = preliminaryChunkId;
  10910. if (referenceId) {
  10911. const fileName = pluginDriver.getFileName(referenceId);
  10912. const relativePath = normalize(node_path.relative(node_path.dirname(chunkId), fileName));
  10913. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  10914. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  10915. ]) || relativeUrlMechanisms[format](relativePath);
  10916. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10917. return;
  10918. }
  10919. const replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  10920. metaProperty,
  10921. { chunkId, format, moduleId }
  10922. ]) || importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  10923. if (typeof replacement === 'string') {
  10924. if (parent instanceof MemberExpression) {
  10925. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10926. }
  10927. else {
  10928. code.overwrite(start, end, replacement, { contentOnly: true });
  10929. }
  10930. }
  10931. }
  10932. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  10933. this.preliminaryChunkId = preliminaryChunkId;
  10934. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  10935. if (accessedGlobals.length > 0) {
  10936. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  10937. }
  10938. }
  10939. }
  10940. const accessedMetaUrlGlobals = {
  10941. amd: ['document', 'module', 'URL'],
  10942. cjs: ['document', 'require', 'URL'],
  10943. es: [],
  10944. iife: ['document', 'URL'],
  10945. system: ['module'],
  10946. umd: ['document', 'require', 'URL']
  10947. };
  10948. const accessedFileUrlGlobals = {
  10949. amd: ['document', 'require', 'URL'],
  10950. cjs: ['document', 'require', 'URL'],
  10951. es: [],
  10952. iife: ['document', 'URL'],
  10953. system: ['module', 'URL'],
  10954. umd: ['document', 'require', 'URL']
  10955. };
  10956. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  10957. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
  10958. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  10959. const urlMechanism = getUrl(chunkId);
  10960. return property === null
  10961. ? `({ url: ${urlMechanism} })`
  10962. : property === 'url'
  10963. ? urlMechanism
  10964. : 'undefined';
  10965. };
  10966. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  10967. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${path}'`);
  10968. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.src || new URL('${escapeId(chunkId)}', document.baseURI).href)`;
  10969. const relativeUrlMechanisms = {
  10970. amd: relativePath => {
  10971. if (relativePath[0] !== '.')
  10972. relativePath = './' + relativePath;
  10973. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  10974. },
  10975. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  10976. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  10977. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  10978. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  10979. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  10980. };
  10981. const importMetaMechanisms = {
  10982. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  10983. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  10984. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  10985. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  10986. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  10987. };
  10988. class NewExpression extends NodeBase {
  10989. hasEffects(context) {
  10990. try {
  10991. for (const argument of this.arguments) {
  10992. if (argument.hasEffects(context))
  10993. return true;
  10994. }
  10995. if (this.context.options.treeshake.annotations &&
  10996. this.annotations) {
  10997. return false;
  10998. }
  10999. return (this.callee.hasEffects(context) ||
  11000. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  11001. }
  11002. finally {
  11003. if (!this.deoptimized)
  11004. this.applyDeoptimizations();
  11005. }
  11006. }
  11007. hasEffectsOnInteractionAtPath(path, { type }) {
  11008. return path.length > 0 || type !== INTERACTION_ACCESSED;
  11009. }
  11010. include(context, includeChildrenRecursively) {
  11011. if (!this.deoptimized)
  11012. this.applyDeoptimizations();
  11013. if (includeChildrenRecursively) {
  11014. super.include(context, includeChildrenRecursively);
  11015. }
  11016. else {
  11017. this.included = true;
  11018. this.callee.include(context, false);
  11019. }
  11020. this.callee.includeCallArguments(context, this.arguments);
  11021. }
  11022. initialise() {
  11023. this.interaction = {
  11024. args: this.arguments,
  11025. thisArg: null,
  11026. type: INTERACTION_CALLED,
  11027. withNew: true
  11028. };
  11029. }
  11030. render(code, options) {
  11031. this.callee.render(code, options);
  11032. renderCallArguments(code, options, this);
  11033. }
  11034. applyDeoptimizations() {
  11035. this.deoptimized = true;
  11036. for (const argument of this.arguments) {
  11037. // This will make sure all properties of parameters behave as "unknown"
  11038. argument.deoptimizePath(UNKNOWN_PATH);
  11039. }
  11040. this.context.requestTreeshakingPass();
  11041. }
  11042. }
  11043. class ObjectExpression extends NodeBase {
  11044. constructor() {
  11045. super(...arguments);
  11046. this.objectEntity = null;
  11047. }
  11048. deoptimizeCache() {
  11049. this.getObjectEntity().deoptimizeAllProperties();
  11050. }
  11051. deoptimizePath(path) {
  11052. this.getObjectEntity().deoptimizePath(path);
  11053. }
  11054. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  11055. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  11056. }
  11057. getLiteralValueAtPath(path, recursionTracker, origin) {
  11058. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  11059. }
  11060. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11061. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11062. }
  11063. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11064. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  11065. }
  11066. render(code, options, { renderedSurroundingElement } = BLANK) {
  11067. super.render(code, options);
  11068. if (renderedSurroundingElement === ExpressionStatement$1 ||
  11069. renderedSurroundingElement === ArrowFunctionExpression$1) {
  11070. code.appendRight(this.start, '(');
  11071. code.prependLeft(this.end, ')');
  11072. }
  11073. }
  11074. applyDeoptimizations() { }
  11075. getObjectEntity() {
  11076. if (this.objectEntity !== null) {
  11077. return this.objectEntity;
  11078. }
  11079. let prototype = OBJECT_PROTOTYPE;
  11080. const properties = [];
  11081. for (const property of this.properties) {
  11082. if (property instanceof SpreadElement) {
  11083. properties.push({ key: UnknownKey, kind: 'init', property });
  11084. continue;
  11085. }
  11086. let key;
  11087. if (property.computed) {
  11088. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  11089. if (typeof keyValue === 'symbol') {
  11090. properties.push({ key: UnknownKey, kind: property.kind, property });
  11091. continue;
  11092. }
  11093. else {
  11094. key = String(keyValue);
  11095. }
  11096. }
  11097. else {
  11098. key =
  11099. property.key instanceof Identifier
  11100. ? property.key.name
  11101. : String(property.key.value);
  11102. if (key === '__proto__' && property.kind === 'init') {
  11103. prototype =
  11104. property.value instanceof Literal && property.value.value === null
  11105. ? null
  11106. : property.value;
  11107. continue;
  11108. }
  11109. }
  11110. properties.push({ key, kind: property.kind, property });
  11111. }
  11112. return (this.objectEntity = new ObjectEntity(properties, prototype));
  11113. }
  11114. }
  11115. class PrivateIdentifier extends NodeBase {
  11116. }
  11117. function getOriginalLocation(sourcemapChain, location) {
  11118. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !!sourcemap.mappings);
  11119. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  11120. const sourcemap = filteredSourcemapChain.pop();
  11121. const line = sourcemap.mappings[location.line - 1];
  11122. if (line) {
  11123. const filteredLine = line.filter((segment) => segment.length > 1);
  11124. const lastSegment = filteredLine[filteredLine.length - 1];
  11125. for (const segment of filteredLine) {
  11126. if (segment[0] >= location.column || segment === lastSegment) {
  11127. location = {
  11128. column: segment[3],
  11129. line: segment[2] + 1
  11130. };
  11131. continue traceSourcemap;
  11132. }
  11133. }
  11134. }
  11135. throw new Error("Can't resolve original location of error.");
  11136. }
  11137. return location;
  11138. }
  11139. class Program extends NodeBase {
  11140. constructor() {
  11141. super(...arguments);
  11142. this.hasCachedEffect = null;
  11143. this.hasLoggedEffect = false;
  11144. }
  11145. hasCachedEffects() {
  11146. return this.hasCachedEffect === null
  11147. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  11148. : this.hasCachedEffect;
  11149. }
  11150. hasEffects(context) {
  11151. for (const node of this.body) {
  11152. if (node.hasEffects(context)) {
  11153. if (this.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  11154. this.hasLoggedEffect = true;
  11155. const { code, module } = this.context;
  11156. const { line, column } = locate(code, node.start, { offsetLine: 1 });
  11157. console.log(`First side effect in ${relativeId(module.id)} is at (${line}:${column})\n${getCodeFrame(code, line, column)}`);
  11158. try {
  11159. const { column: originalColumn, line: originalLine } = getOriginalLocation(module.sourcemapChain, { column, line });
  11160. if (originalLine !== line) {
  11161. console.log(`Original location is at (${originalLine}:${originalColumn})\n${getCodeFrame(module.originalCode, originalLine, originalColumn)}\n`);
  11162. }
  11163. }
  11164. catch {
  11165. /* ignored */
  11166. }
  11167. console.log();
  11168. }
  11169. return (this.hasCachedEffect = true);
  11170. }
  11171. }
  11172. return false;
  11173. }
  11174. include(context, includeChildrenRecursively) {
  11175. this.included = true;
  11176. for (const node of this.body) {
  11177. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  11178. node.include(context, includeChildrenRecursively);
  11179. }
  11180. }
  11181. }
  11182. render(code, options) {
  11183. let start = this.start;
  11184. if (code.original.startsWith('#!')) {
  11185. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  11186. code.remove(0, start);
  11187. }
  11188. if (this.body.length > 0) {
  11189. renderStatementList(this.body, code, start, this.end, options);
  11190. }
  11191. else {
  11192. super.render(code, options);
  11193. }
  11194. }
  11195. applyDeoptimizations() { }
  11196. }
  11197. class Property extends MethodBase {
  11198. constructor() {
  11199. super(...arguments);
  11200. this.declarationInit = null;
  11201. }
  11202. declare(kind, init) {
  11203. this.declarationInit = init;
  11204. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  11205. }
  11206. hasEffects(context) {
  11207. if (!this.deoptimized)
  11208. this.applyDeoptimizations();
  11209. const propertyReadSideEffects = this.context.options.treeshake
  11210. .propertyReadSideEffects;
  11211. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  11212. this.key.hasEffects(context) ||
  11213. this.value.hasEffects(context));
  11214. }
  11215. markDeclarationReached() {
  11216. this.value.markDeclarationReached();
  11217. }
  11218. render(code, options) {
  11219. if (!this.shorthand) {
  11220. this.key.render(code, options);
  11221. }
  11222. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  11223. }
  11224. applyDeoptimizations() {
  11225. this.deoptimized = true;
  11226. if (this.declarationInit !== null) {
  11227. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  11228. this.context.requestTreeshakingPass();
  11229. }
  11230. }
  11231. }
  11232. class PropertyDefinition extends NodeBase {
  11233. deoptimizePath(path) {
  11234. this.value?.deoptimizePath(path);
  11235. }
  11236. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  11237. this.value?.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  11238. }
  11239. getLiteralValueAtPath(path, recursionTracker, origin) {
  11240. return this.value
  11241. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  11242. : UnknownValue;
  11243. }
  11244. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11245. return this.value
  11246. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  11247. : UNKNOWN_RETURN_EXPRESSION;
  11248. }
  11249. hasEffects(context) {
  11250. return this.key.hasEffects(context) || (this.static && !!this.value?.hasEffects(context));
  11251. }
  11252. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11253. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  11254. }
  11255. applyDeoptimizations() { }
  11256. }
  11257. class ReturnStatement extends NodeBase {
  11258. hasEffects(context) {
  11259. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  11260. return true;
  11261. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  11262. return false;
  11263. }
  11264. include(context, includeChildrenRecursively) {
  11265. this.included = true;
  11266. this.argument?.include(context, includeChildrenRecursively);
  11267. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  11268. }
  11269. initialise() {
  11270. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  11271. }
  11272. render(code, options) {
  11273. if (this.argument) {
  11274. this.argument.render(code, options, { preventASI: true });
  11275. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  11276. code.prependLeft(this.start + 6, ' ');
  11277. }
  11278. }
  11279. }
  11280. }
  11281. class SequenceExpression extends NodeBase {
  11282. deoptimizePath(path) {
  11283. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  11284. }
  11285. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  11286. this.expressions[this.expressions.length - 1].deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  11287. }
  11288. getLiteralValueAtPath(path, recursionTracker, origin) {
  11289. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  11290. }
  11291. hasEffects(context) {
  11292. for (const expression of this.expressions) {
  11293. if (expression.hasEffects(context))
  11294. return true;
  11295. }
  11296. return false;
  11297. }
  11298. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11299. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  11300. }
  11301. include(context, includeChildrenRecursively) {
  11302. this.included = true;
  11303. const lastExpression = this.expressions[this.expressions.length - 1];
  11304. for (const expression of this.expressions) {
  11305. if (includeChildrenRecursively ||
  11306. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  11307. expression.shouldBeIncluded(context))
  11308. expression.include(context, includeChildrenRecursively);
  11309. }
  11310. }
  11311. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  11312. let includedNodes = 0;
  11313. let lastSeparatorPos = null;
  11314. const lastNode = this.expressions[this.expressions.length - 1];
  11315. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  11316. if (!node.included) {
  11317. treeshakeNode(node, code, start, end);
  11318. continue;
  11319. }
  11320. includedNodes++;
  11321. lastSeparatorPos = separator;
  11322. if (includedNodes === 1 && preventASI) {
  11323. removeLineBreaks(code, start, node.start);
  11324. }
  11325. if (includedNodes === 1) {
  11326. const parentType = renderedParentType || this.parent.type;
  11327. node.render(code, options, {
  11328. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  11329. renderedParentType: parentType,
  11330. renderedSurroundingElement: parentType
  11331. });
  11332. }
  11333. else {
  11334. node.render(code, options);
  11335. }
  11336. }
  11337. if (lastSeparatorPos) {
  11338. code.remove(lastSeparatorPos, this.end);
  11339. }
  11340. }
  11341. }
  11342. class StaticBlock extends NodeBase {
  11343. createScope(parentScope) {
  11344. this.scope = new BlockScope(parentScope);
  11345. }
  11346. hasEffects(context) {
  11347. for (const node of this.body) {
  11348. if (node.hasEffects(context))
  11349. return true;
  11350. }
  11351. return false;
  11352. }
  11353. include(context, includeChildrenRecursively) {
  11354. this.included = true;
  11355. for (const node of this.body) {
  11356. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  11357. node.include(context, includeChildrenRecursively);
  11358. }
  11359. }
  11360. render(code, options) {
  11361. if (this.body.length > 0) {
  11362. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  11363. }
  11364. else {
  11365. super.render(code, options);
  11366. }
  11367. }
  11368. }
  11369. class Super extends NodeBase {
  11370. bind() {
  11371. this.variable = this.scope.findVariable('this');
  11372. }
  11373. deoptimizePath(path) {
  11374. this.variable.deoptimizePath(path);
  11375. }
  11376. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  11377. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  11378. }
  11379. include() {
  11380. if (!this.included) {
  11381. this.included = true;
  11382. this.context.includeVariableInModule(this.variable);
  11383. }
  11384. }
  11385. }
  11386. class SwitchCase extends NodeBase {
  11387. hasEffects(context) {
  11388. if (this.test?.hasEffects(context))
  11389. return true;
  11390. for (const node of this.consequent) {
  11391. if (context.brokenFlow)
  11392. break;
  11393. if (node.hasEffects(context))
  11394. return true;
  11395. }
  11396. return false;
  11397. }
  11398. include(context, includeChildrenRecursively) {
  11399. this.included = true;
  11400. this.test?.include(context, includeChildrenRecursively);
  11401. for (const node of this.consequent) {
  11402. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  11403. node.include(context, includeChildrenRecursively);
  11404. }
  11405. }
  11406. render(code, options, nodeRenderOptions) {
  11407. if (this.consequent.length > 0) {
  11408. this.test && this.test.render(code, options);
  11409. const testEnd = this.test
  11410. ? this.test.end
  11411. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  11412. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  11413. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  11414. }
  11415. else {
  11416. super.render(code, options);
  11417. }
  11418. }
  11419. }
  11420. SwitchCase.prototype.needsBoundaries = true;
  11421. class SwitchStatement extends NodeBase {
  11422. createScope(parentScope) {
  11423. this.scope = new BlockScope(parentScope);
  11424. }
  11425. hasEffects(context) {
  11426. if (this.discriminant.hasEffects(context))
  11427. return true;
  11428. const { brokenFlow, ignore } = context;
  11429. const { breaks } = ignore;
  11430. let minBrokenFlow = Infinity;
  11431. ignore.breaks = true;
  11432. for (const switchCase of this.cases) {
  11433. if (switchCase.hasEffects(context))
  11434. return true;
  11435. // eslint-disable-next-line unicorn/consistent-destructuring
  11436. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  11437. context.brokenFlow = brokenFlow;
  11438. }
  11439. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  11440. context.brokenFlow = minBrokenFlow;
  11441. }
  11442. ignore.breaks = breaks;
  11443. return false;
  11444. }
  11445. include(context, includeChildrenRecursively) {
  11446. this.included = true;
  11447. this.discriminant.include(context, includeChildrenRecursively);
  11448. const { brokenFlow } = context;
  11449. let minBrokenFlow = Infinity;
  11450. let isCaseIncluded = includeChildrenRecursively ||
  11451. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  11452. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  11453. const switchCase = this.cases[caseIndex];
  11454. if (switchCase.included) {
  11455. isCaseIncluded = true;
  11456. }
  11457. if (!isCaseIncluded) {
  11458. const hasEffectsContext = createHasEffectsContext();
  11459. hasEffectsContext.ignore.breaks = true;
  11460. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  11461. }
  11462. if (isCaseIncluded) {
  11463. switchCase.include(context, includeChildrenRecursively);
  11464. // eslint-disable-next-line unicorn/consistent-destructuring
  11465. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  11466. context.brokenFlow = brokenFlow;
  11467. }
  11468. else {
  11469. minBrokenFlow = brokenFlow;
  11470. }
  11471. }
  11472. if (isCaseIncluded &&
  11473. this.defaultCase !== null &&
  11474. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  11475. context.brokenFlow = minBrokenFlow;
  11476. }
  11477. }
  11478. initialise() {
  11479. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  11480. if (this.cases[caseIndex].test === null) {
  11481. this.defaultCase = caseIndex;
  11482. return;
  11483. }
  11484. }
  11485. this.defaultCase = null;
  11486. }
  11487. render(code, options) {
  11488. this.discriminant.render(code, options);
  11489. if (this.cases.length > 0) {
  11490. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  11491. }
  11492. }
  11493. }
  11494. class TaggedTemplateExpression extends CallExpressionBase {
  11495. bind() {
  11496. super.bind();
  11497. if (this.tag.type === Identifier$1) {
  11498. const name = this.tag.name;
  11499. const variable = this.scope.findVariable(name);
  11500. if (variable.isNamespace) {
  11501. this.context.warn(errorCannotCallNamespace(name), this.start);
  11502. }
  11503. }
  11504. }
  11505. hasEffects(context) {
  11506. try {
  11507. for (const argument of this.quasi.expressions) {
  11508. if (argument.hasEffects(context))
  11509. return true;
  11510. }
  11511. return (this.tag.hasEffects(context) ||
  11512. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  11513. }
  11514. finally {
  11515. if (!this.deoptimized)
  11516. this.applyDeoptimizations();
  11517. }
  11518. }
  11519. include(context, includeChildrenRecursively) {
  11520. if (!this.deoptimized)
  11521. this.applyDeoptimizations();
  11522. if (includeChildrenRecursively) {
  11523. super.include(context, includeChildrenRecursively);
  11524. }
  11525. else {
  11526. this.included = true;
  11527. this.tag.include(context, includeChildrenRecursively);
  11528. this.quasi.include(context, includeChildrenRecursively);
  11529. }
  11530. this.tag.includeCallArguments(context, this.interaction.args);
  11531. const [returnExpression] = this.getReturnExpression();
  11532. if (!returnExpression.included) {
  11533. returnExpression.include(context, false);
  11534. }
  11535. }
  11536. initialise() {
  11537. this.interaction = {
  11538. args: [UNKNOWN_EXPRESSION, ...this.quasi.expressions],
  11539. thisArg: this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  11540. type: INTERACTION_CALLED,
  11541. withNew: false
  11542. };
  11543. }
  11544. render(code, options) {
  11545. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  11546. this.quasi.render(code, options);
  11547. }
  11548. applyDeoptimizations() {
  11549. this.deoptimized = true;
  11550. if (this.interaction.thisArg) {
  11551. this.tag.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  11552. }
  11553. for (const argument of this.quasi.expressions) {
  11554. // This will make sure all properties of parameters behave as "unknown"
  11555. argument.deoptimizePath(UNKNOWN_PATH);
  11556. }
  11557. this.context.requestTreeshakingPass();
  11558. }
  11559. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  11560. if (this.returnExpression === null) {
  11561. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11562. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  11563. }
  11564. return this.returnExpression;
  11565. }
  11566. }
  11567. class TemplateElement extends NodeBase {
  11568. // Do not try to bind value
  11569. bind() { }
  11570. hasEffects() {
  11571. return false;
  11572. }
  11573. include() {
  11574. this.included = true;
  11575. }
  11576. parseNode(esTreeNode) {
  11577. this.value = esTreeNode.value;
  11578. super.parseNode(esTreeNode);
  11579. }
  11580. render() { }
  11581. }
  11582. class TemplateLiteral extends NodeBase {
  11583. deoptimizeThisOnInteractionAtPath() { }
  11584. getLiteralValueAtPath(path) {
  11585. if (path.length > 0 || this.quasis.length !== 1) {
  11586. return UnknownValue;
  11587. }
  11588. return this.quasis[0].value.cooked;
  11589. }
  11590. getReturnExpressionWhenCalledAtPath(path) {
  11591. if (path.length !== 1) {
  11592. return UNKNOWN_RETURN_EXPRESSION;
  11593. }
  11594. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  11595. }
  11596. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11597. if (interaction.type === INTERACTION_ACCESSED) {
  11598. return path.length > 1;
  11599. }
  11600. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  11601. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  11602. }
  11603. return true;
  11604. }
  11605. render(code, options) {
  11606. code.indentExclusionRanges.push([this.start, this.end]);
  11607. super.render(code, options);
  11608. }
  11609. }
  11610. class UndefinedVariable extends Variable {
  11611. constructor() {
  11612. super('undefined');
  11613. }
  11614. getLiteralValueAtPath() {
  11615. return undefined;
  11616. }
  11617. }
  11618. class ExportDefaultVariable extends LocalVariable {
  11619. constructor(name, exportDefaultDeclaration, context) {
  11620. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  11621. this.hasId = false;
  11622. this.originalId = null;
  11623. this.originalVariable = null;
  11624. const declaration = exportDefaultDeclaration.declaration;
  11625. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  11626. declaration.id) {
  11627. this.hasId = true;
  11628. this.originalId = declaration.id;
  11629. }
  11630. else if (declaration instanceof Identifier) {
  11631. this.originalId = declaration;
  11632. }
  11633. }
  11634. addReference(identifier) {
  11635. if (!this.hasId) {
  11636. this.name = identifier.name;
  11637. }
  11638. }
  11639. forbidName(name) {
  11640. const original = this.getOriginalVariable();
  11641. if (original === this) {
  11642. super.forbidName(name);
  11643. }
  11644. else {
  11645. original.forbidName(name);
  11646. }
  11647. }
  11648. getAssignedVariableName() {
  11649. return (this.originalId && this.originalId.name) || null;
  11650. }
  11651. getBaseVariableName() {
  11652. const original = this.getOriginalVariable();
  11653. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  11654. }
  11655. getDirectOriginalVariable() {
  11656. return this.originalId &&
  11657. (this.hasId ||
  11658. !(this.originalId.isPossibleTDZ() ||
  11659. this.originalId.variable.isReassigned ||
  11660. this.originalId.variable instanceof UndefinedVariable ||
  11661. // this avoids a circular dependency
  11662. 'syntheticNamespace' in this.originalId.variable))
  11663. ? this.originalId.variable
  11664. : null;
  11665. }
  11666. getName(getPropertyAccess) {
  11667. const original = this.getOriginalVariable();
  11668. return original === this
  11669. ? super.getName(getPropertyAccess)
  11670. : original.getName(getPropertyAccess);
  11671. }
  11672. getOriginalVariable() {
  11673. if (this.originalVariable)
  11674. return this.originalVariable;
  11675. // eslint-disable-next-line @typescript-eslint/no-this-alias
  11676. let original = this;
  11677. let currentVariable;
  11678. const checkedVariables = new Set();
  11679. do {
  11680. checkedVariables.add(original);
  11681. currentVariable = original;
  11682. original = currentVariable.getDirectOriginalVariable();
  11683. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  11684. return (this.originalVariable = original || currentVariable);
  11685. }
  11686. }
  11687. class ModuleScope extends ChildScope {
  11688. constructor(parent, context) {
  11689. super(parent);
  11690. this.context = context;
  11691. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  11692. }
  11693. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  11694. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  11695. this.variables.set('default', variable);
  11696. return variable;
  11697. }
  11698. addNamespaceMemberAccess() { }
  11699. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  11700. // all module level variables are already deconflicted when deconflicting the chunk
  11701. for (const scope of this.children)
  11702. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  11703. }
  11704. findLexicalBoundary() {
  11705. return this;
  11706. }
  11707. findVariable(name) {
  11708. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  11709. if (knownVariable) {
  11710. return knownVariable;
  11711. }
  11712. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  11713. if (variable instanceof GlobalVariable) {
  11714. this.accessedOutsideVariables.set(name, variable);
  11715. }
  11716. return variable;
  11717. }
  11718. }
  11719. class ThisExpression extends NodeBase {
  11720. bind() {
  11721. this.variable = this.scope.findVariable('this');
  11722. }
  11723. deoptimizePath(path) {
  11724. this.variable.deoptimizePath(path);
  11725. }
  11726. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  11727. // We rewrite the parameter so that a ThisVariable can detect self-mutations
  11728. this.variable.deoptimizeThisOnInteractionAtPath(interaction.thisArg === this ? { ...interaction, thisArg: this.variable } : interaction, path, recursionTracker);
  11729. }
  11730. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11731. if (path.length === 0) {
  11732. return interaction.type !== INTERACTION_ACCESSED;
  11733. }
  11734. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  11735. }
  11736. include() {
  11737. if (!this.included) {
  11738. this.included = true;
  11739. this.context.includeVariableInModule(this.variable);
  11740. }
  11741. }
  11742. initialise() {
  11743. this.alias =
  11744. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  11745. if (this.alias === 'undefined') {
  11746. this.context.warn(errorThisIsUndefined(), this.start);
  11747. }
  11748. }
  11749. render(code) {
  11750. if (this.alias !== null) {
  11751. code.overwrite(this.start, this.end, this.alias, {
  11752. contentOnly: false,
  11753. storeName: true
  11754. });
  11755. }
  11756. }
  11757. }
  11758. class ThrowStatement extends NodeBase {
  11759. hasEffects() {
  11760. return true;
  11761. }
  11762. include(context, includeChildrenRecursively) {
  11763. this.included = true;
  11764. this.argument.include(context, includeChildrenRecursively);
  11765. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  11766. }
  11767. render(code, options) {
  11768. this.argument.render(code, options, { preventASI: true });
  11769. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  11770. code.prependLeft(this.start + 5, ' ');
  11771. }
  11772. }
  11773. }
  11774. class TryStatement extends NodeBase {
  11775. constructor() {
  11776. super(...arguments);
  11777. this.directlyIncluded = false;
  11778. this.includedLabelsAfterBlock = null;
  11779. }
  11780. hasEffects(context) {
  11781. return ((this.context.options.treeshake.tryCatchDeoptimization
  11782. ? this.block.body.length > 0
  11783. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  11784. }
  11785. include(context, includeChildrenRecursively) {
  11786. const tryCatchDeoptimization = this.context.options.treeshake
  11787. ?.tryCatchDeoptimization;
  11788. const { brokenFlow, includedLabels } = context;
  11789. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  11790. this.included = true;
  11791. this.directlyIncluded = true;
  11792. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  11793. if (includedLabels.size > 0) {
  11794. this.includedLabelsAfterBlock = [...includedLabels];
  11795. }
  11796. context.brokenFlow = brokenFlow;
  11797. }
  11798. else if (this.includedLabelsAfterBlock) {
  11799. for (const label of this.includedLabelsAfterBlock) {
  11800. includedLabels.add(label);
  11801. }
  11802. }
  11803. if (this.handler !== null) {
  11804. this.handler.include(context, includeChildrenRecursively);
  11805. context.brokenFlow = brokenFlow;
  11806. }
  11807. this.finalizer?.include(context, includeChildrenRecursively);
  11808. }
  11809. }
  11810. const unaryOperators = {
  11811. '!': value => !value,
  11812. '+': value => +value,
  11813. '-': value => -value,
  11814. delete: () => UnknownValue,
  11815. typeof: value => typeof value,
  11816. void: () => undefined,
  11817. '~': value => ~value
  11818. };
  11819. class UnaryExpression extends NodeBase {
  11820. getLiteralValueAtPath(path, recursionTracker, origin) {
  11821. if (path.length > 0)
  11822. return UnknownValue;
  11823. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  11824. if (typeof argumentValue === 'symbol')
  11825. return UnknownValue;
  11826. return unaryOperators[this.operator](argumentValue);
  11827. }
  11828. hasEffects(context) {
  11829. if (!this.deoptimized)
  11830. this.applyDeoptimizations();
  11831. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  11832. return false;
  11833. return (this.argument.hasEffects(context) ||
  11834. (this.operator === 'delete' &&
  11835. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  11836. }
  11837. hasEffectsOnInteractionAtPath(path, { type }) {
  11838. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  11839. }
  11840. applyDeoptimizations() {
  11841. this.deoptimized = true;
  11842. if (this.operator === 'delete') {
  11843. this.argument.deoptimizePath(EMPTY_PATH);
  11844. this.context.requestTreeshakingPass();
  11845. }
  11846. }
  11847. }
  11848. class UnknownNode extends NodeBase {
  11849. hasEffects() {
  11850. return true;
  11851. }
  11852. include(context) {
  11853. super.include(context, true);
  11854. }
  11855. }
  11856. class UpdateExpression extends NodeBase {
  11857. hasEffects(context) {
  11858. if (!this.deoptimized)
  11859. this.applyDeoptimizations();
  11860. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  11861. }
  11862. hasEffectsOnInteractionAtPath(path, { type }) {
  11863. return path.length > 1 || type !== INTERACTION_ACCESSED;
  11864. }
  11865. include(context, includeChildrenRecursively) {
  11866. if (!this.deoptimized)
  11867. this.applyDeoptimizations();
  11868. this.included = true;
  11869. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  11870. }
  11871. initialise() {
  11872. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  11873. }
  11874. render(code, options) {
  11875. const { exportNamesByVariable, format, snippets: { _ } } = options;
  11876. this.argument.render(code, options);
  11877. if (format === 'system') {
  11878. const variable = this.argument.variable;
  11879. const exportNames = exportNamesByVariable.get(variable);
  11880. if (exportNames) {
  11881. if (this.prefix) {
  11882. if (exportNames.length === 1) {
  11883. renderSystemExportExpression(variable, this.start, this.end, code, options);
  11884. }
  11885. else {
  11886. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  11887. }
  11888. }
  11889. else {
  11890. const operator = this.operator[0];
  11891. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  11892. }
  11893. }
  11894. }
  11895. }
  11896. applyDeoptimizations() {
  11897. this.deoptimized = true;
  11898. this.argument.deoptimizePath(EMPTY_PATH);
  11899. if (this.argument instanceof Identifier) {
  11900. const variable = this.scope.findVariable(this.argument.name);
  11901. variable.isReassigned = true;
  11902. }
  11903. this.context.requestTreeshakingPass();
  11904. }
  11905. }
  11906. function isReassignedExportsMember(variable, exportNamesByVariable) {
  11907. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  11908. }
  11909. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  11910. for (const declarator of declarations) {
  11911. if (!declarator.id.included)
  11912. return false;
  11913. if (declarator.id.type === Identifier$1) {
  11914. if (exportNamesByVariable.has(declarator.id.variable))
  11915. return false;
  11916. }
  11917. else {
  11918. const exportedVariables = [];
  11919. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  11920. if (exportedVariables.length > 0)
  11921. return false;
  11922. }
  11923. }
  11924. return true;
  11925. }
  11926. class VariableDeclaration extends NodeBase {
  11927. deoptimizePath() {
  11928. for (const declarator of this.declarations) {
  11929. declarator.deoptimizePath(EMPTY_PATH);
  11930. }
  11931. }
  11932. hasEffectsOnInteractionAtPath() {
  11933. return false;
  11934. }
  11935. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  11936. this.included = true;
  11937. for (const declarator of this.declarations) {
  11938. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  11939. declarator.include(context, includeChildrenRecursively);
  11940. const { id, init } = declarator;
  11941. if (asSingleStatement) {
  11942. id.include(context, includeChildrenRecursively);
  11943. }
  11944. if (init &&
  11945. id.included &&
  11946. !init.included &&
  11947. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  11948. init.include(context, includeChildrenRecursively);
  11949. }
  11950. }
  11951. }
  11952. initialise() {
  11953. for (const declarator of this.declarations) {
  11954. declarator.declareDeclarator(this.kind);
  11955. }
  11956. }
  11957. render(code, options, nodeRenderOptions = BLANK) {
  11958. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  11959. for (const declarator of this.declarations) {
  11960. declarator.render(code, options);
  11961. }
  11962. if (!nodeRenderOptions.isNoStatement &&
  11963. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  11964. code.appendLeft(this.end, ';');
  11965. }
  11966. }
  11967. else {
  11968. this.renderReplacedDeclarations(code, options);
  11969. }
  11970. }
  11971. applyDeoptimizations() { }
  11972. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  11973. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  11974. code.remove(this.end - 1, this.end);
  11975. }
  11976. separatorString += ';';
  11977. if (lastSeparatorPos === null) {
  11978. code.appendLeft(renderedContentEnd, separatorString);
  11979. }
  11980. else {
  11981. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  11982. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  11983. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  11984. actualContentEnd--;
  11985. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  11986. actualContentEnd--;
  11987. }
  11988. }
  11989. if (actualContentEnd === lastSeparatorPos + 1) {
  11990. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  11991. }
  11992. else {
  11993. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  11994. code.remove(actualContentEnd, renderedContentEnd);
  11995. }
  11996. }
  11997. if (systemPatternExports.length > 0) {
  11998. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  11999. }
  12000. }
  12001. renderReplacedDeclarations(code, options) {
  12002. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  12003. let actualContentEnd, renderedContentEnd;
  12004. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  12005. let lastSeparatorPos = renderedContentEnd - 1;
  12006. code.remove(this.start, lastSeparatorPos);
  12007. let isInDeclaration = false;
  12008. let hasRenderedContent = false;
  12009. let separatorString = '', leadingString, nextSeparatorString;
  12010. const aggregatedSystemExports = [];
  12011. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  12012. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  12013. if (!node.included) {
  12014. code.remove(start, end);
  12015. continue;
  12016. }
  12017. node.render(code, options);
  12018. leadingString = '';
  12019. nextSeparatorString = '';
  12020. if (!node.id.included ||
  12021. (node.id instanceof Identifier &&
  12022. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  12023. if (hasRenderedContent) {
  12024. separatorString += ';';
  12025. }
  12026. isInDeclaration = false;
  12027. }
  12028. else {
  12029. if (singleSystemExport && singleSystemExport === node.id.variable) {
  12030. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  12031. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  12032. }
  12033. if (isInDeclaration) {
  12034. separatorString += ',';
  12035. }
  12036. else {
  12037. if (hasRenderedContent) {
  12038. separatorString += ';';
  12039. }
  12040. leadingString += `${this.kind} `;
  12041. isInDeclaration = true;
  12042. }
  12043. }
  12044. if (renderedContentEnd === lastSeparatorPos + 1) {
  12045. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  12046. }
  12047. else {
  12048. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  12049. code.appendLeft(renderedContentEnd, leadingString);
  12050. }
  12051. actualContentEnd = contentEnd;
  12052. renderedContentEnd = end;
  12053. hasRenderedContent = true;
  12054. lastSeparatorPos = separator;
  12055. separatorString = nextSeparatorString;
  12056. }
  12057. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  12058. }
  12059. }
  12060. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  12061. let singleSystemExport = null;
  12062. if (options.format === 'system') {
  12063. for (const { node } of separatedNodes) {
  12064. if (node.id instanceof Identifier &&
  12065. node.init &&
  12066. aggregatedSystemExports.length === 0 &&
  12067. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  12068. singleSystemExport = node.id.variable;
  12069. aggregatedSystemExports.push(singleSystemExport);
  12070. }
  12071. else {
  12072. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  12073. }
  12074. }
  12075. if (aggregatedSystemExports.length > 1) {
  12076. singleSystemExport = null;
  12077. }
  12078. else if (singleSystemExport) {
  12079. aggregatedSystemExports.length = 0;
  12080. }
  12081. }
  12082. return singleSystemExport;
  12083. }
  12084. class VariableDeclarator extends NodeBase {
  12085. declareDeclarator(kind) {
  12086. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  12087. }
  12088. deoptimizePath(path) {
  12089. this.id.deoptimizePath(path);
  12090. }
  12091. hasEffects(context) {
  12092. if (!this.deoptimized)
  12093. this.applyDeoptimizations();
  12094. const initEffect = this.init?.hasEffects(context);
  12095. this.id.markDeclarationReached();
  12096. return initEffect || this.id.hasEffects(context);
  12097. }
  12098. include(context, includeChildrenRecursively) {
  12099. const { deoptimized, id, init } = this;
  12100. if (!deoptimized)
  12101. this.applyDeoptimizations();
  12102. this.included = true;
  12103. init?.include(context, includeChildrenRecursively);
  12104. id.markDeclarationReached();
  12105. if (includeChildrenRecursively || id.shouldBeIncluded(context)) {
  12106. id.include(context, includeChildrenRecursively);
  12107. }
  12108. }
  12109. render(code, options) {
  12110. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  12111. const { end, id, init, start } = this;
  12112. const renderId = id.included;
  12113. if (renderId) {
  12114. id.render(code, options);
  12115. }
  12116. else {
  12117. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  12118. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  12119. }
  12120. if (init) {
  12121. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  12122. const renderedVariable = id.variable.getName(getPropertyAccess);
  12123. if (renderedVariable !== id.name) {
  12124. code.appendLeft(init.start + 5, ` ${id.name}`);
  12125. }
  12126. }
  12127. init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  12128. }
  12129. else if (id instanceof Identifier &&
  12130. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  12131. code.appendLeft(end, `${_}=${_}void 0`);
  12132. }
  12133. }
  12134. applyDeoptimizations() {
  12135. this.deoptimized = true;
  12136. const { id, init } = this;
  12137. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  12138. const { name, variable } = id;
  12139. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  12140. if (accessedVariable !== variable) {
  12141. accessedVariable.forbidName(name);
  12142. }
  12143. }
  12144. }
  12145. }
  12146. }
  12147. class WhileStatement extends NodeBase {
  12148. hasEffects(context) {
  12149. if (this.test.hasEffects(context))
  12150. return true;
  12151. const { brokenFlow, ignore } = context;
  12152. const { breaks, continues } = ignore;
  12153. ignore.breaks = true;
  12154. ignore.continues = true;
  12155. if (this.body.hasEffects(context))
  12156. return true;
  12157. ignore.breaks = breaks;
  12158. ignore.continues = continues;
  12159. context.brokenFlow = brokenFlow;
  12160. return false;
  12161. }
  12162. include(context, includeChildrenRecursively) {
  12163. this.included = true;
  12164. this.test.include(context, includeChildrenRecursively);
  12165. const { brokenFlow } = context;
  12166. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  12167. context.brokenFlow = brokenFlow;
  12168. }
  12169. }
  12170. class YieldExpression extends NodeBase {
  12171. hasEffects(context) {
  12172. if (!this.deoptimized)
  12173. this.applyDeoptimizations();
  12174. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  12175. }
  12176. render(code, options) {
  12177. if (this.argument) {
  12178. this.argument.render(code, options, { preventASI: true });
  12179. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  12180. code.prependLeft(this.start + 5, ' ');
  12181. }
  12182. }
  12183. }
  12184. }
  12185. const nodeConstructors = {
  12186. ArrayExpression,
  12187. ArrayPattern,
  12188. ArrowFunctionExpression,
  12189. AssignmentExpression,
  12190. AssignmentPattern,
  12191. AwaitExpression,
  12192. BinaryExpression,
  12193. BlockStatement,
  12194. BreakStatement,
  12195. CallExpression,
  12196. CatchClause,
  12197. ChainExpression,
  12198. ClassBody,
  12199. ClassDeclaration,
  12200. ClassExpression,
  12201. ConditionalExpression,
  12202. ContinueStatement,
  12203. DoWhileStatement,
  12204. EmptyStatement,
  12205. ExportAllDeclaration,
  12206. ExportDefaultDeclaration,
  12207. ExportNamedDeclaration,
  12208. ExportSpecifier,
  12209. ExpressionStatement,
  12210. ForInStatement,
  12211. ForOfStatement,
  12212. ForStatement,
  12213. FunctionDeclaration,
  12214. FunctionExpression,
  12215. Identifier,
  12216. IfStatement,
  12217. ImportAttribute,
  12218. ImportDeclaration,
  12219. ImportDefaultSpecifier,
  12220. ImportExpression,
  12221. ImportNamespaceSpecifier,
  12222. ImportSpecifier,
  12223. LabeledStatement,
  12224. Literal,
  12225. LogicalExpression,
  12226. MemberExpression,
  12227. MetaProperty,
  12228. MethodDefinition,
  12229. NewExpression,
  12230. ObjectExpression,
  12231. ObjectPattern,
  12232. PrivateIdentifier,
  12233. Program,
  12234. Property,
  12235. PropertyDefinition,
  12236. RestElement,
  12237. ReturnStatement,
  12238. SequenceExpression,
  12239. SpreadElement,
  12240. StaticBlock,
  12241. Super,
  12242. SwitchCase,
  12243. SwitchStatement,
  12244. TaggedTemplateExpression,
  12245. TemplateElement,
  12246. TemplateLiteral,
  12247. ThisExpression,
  12248. ThrowStatement,
  12249. TryStatement,
  12250. UnaryExpression,
  12251. UnknownNode,
  12252. UpdateExpression,
  12253. VariableDeclaration,
  12254. VariableDeclarator,
  12255. WhileStatement,
  12256. YieldExpression
  12257. };
  12258. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  12259. class ExportShimVariable extends Variable {
  12260. constructor(module) {
  12261. super(MISSING_EXPORT_SHIM_VARIABLE);
  12262. this.module = module;
  12263. }
  12264. include() {
  12265. super.include();
  12266. this.module.needsExportShim = true;
  12267. }
  12268. }
  12269. class NamespaceVariable extends Variable {
  12270. constructor(context) {
  12271. super(context.getModuleName());
  12272. this.memberVariables = null;
  12273. this.mergedNamespaces = [];
  12274. this.referencedEarly = false;
  12275. this.references = [];
  12276. this.context = context;
  12277. this.module = context.module;
  12278. }
  12279. addReference(identifier) {
  12280. this.references.push(identifier);
  12281. this.name = identifier.name;
  12282. }
  12283. deoptimizePath(path) {
  12284. if (path.length > 1) {
  12285. const key = path[0];
  12286. if (typeof key === 'string') {
  12287. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  12288. }
  12289. }
  12290. }
  12291. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  12292. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  12293. const key = path[0];
  12294. if (typeof key === 'string') {
  12295. this.getMemberVariables()[key]?.deoptimizeThisOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  12296. }
  12297. else {
  12298. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  12299. }
  12300. }
  12301. }
  12302. getLiteralValueAtPath(path) {
  12303. if (path[0] === SymbolToStringTag) {
  12304. return 'Module';
  12305. }
  12306. return UnknownValue;
  12307. }
  12308. getMemberVariables() {
  12309. if (this.memberVariables) {
  12310. return this.memberVariables;
  12311. }
  12312. const memberVariables = Object.create(null);
  12313. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  12314. for (const name of sortedExports) {
  12315. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  12316. const exportedVariable = this.context.traceExport(name);
  12317. if (exportedVariable) {
  12318. memberVariables[name] = exportedVariable;
  12319. }
  12320. }
  12321. }
  12322. return (this.memberVariables = memberVariables);
  12323. }
  12324. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12325. const { type } = interaction;
  12326. if (path.length === 0) {
  12327. // This can only be a call anyway
  12328. return true;
  12329. }
  12330. if (path.length === 1 && type !== INTERACTION_CALLED) {
  12331. return type === INTERACTION_ASSIGNED;
  12332. }
  12333. const key = path[0];
  12334. if (typeof key !== 'string') {
  12335. return true;
  12336. }
  12337. const memberVariable = this.getMemberVariables()[key];
  12338. return (!memberVariable ||
  12339. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  12340. }
  12341. include() {
  12342. this.included = true;
  12343. this.context.includeAllExports();
  12344. }
  12345. prepare(accessedGlobalsByScope) {
  12346. if (this.mergedNamespaces.length > 0) {
  12347. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  12348. }
  12349. }
  12350. renderBlock(options) {
  12351. const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  12352. const memberVariables = this.getMemberVariables();
  12353. const members = Object.entries(memberVariables).map(([name, original]) => {
  12354. if (this.referencedEarly || original.isReassigned) {
  12355. return [
  12356. null,
  12357. `get ${name}${_}()${_}{${_}return ${original.getName(getPropertyAccess)}${s}${_}}`
  12358. ];
  12359. }
  12360. return [name, original.getName(getPropertyAccess)];
  12361. });
  12362. members.unshift([null, `__proto__:${_}null`]);
  12363. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  12364. if (this.mergedNamespaces.length > 0) {
  12365. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  12366. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  12367. }
  12368. else {
  12369. // The helper to merge namespaces will also take care of freezing and toStringTag
  12370. if (namespaceToStringTag) {
  12371. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  12372. }
  12373. if (freeze) {
  12374. output = `/*#__PURE__*/Object.freeze(${output})`;
  12375. }
  12376. }
  12377. const name = this.getName(getPropertyAccess);
  12378. output = `${cnst} ${name}${_}=${_}${output};`;
  12379. if (format === 'system' && exportNamesByVariable.has(this)) {
  12380. output += `${n}${getSystemExportStatement([this], options)};`;
  12381. }
  12382. return output;
  12383. }
  12384. renderFirst() {
  12385. return this.referencedEarly;
  12386. }
  12387. setMergedNamespaces(mergedNamespaces) {
  12388. this.mergedNamespaces = mergedNamespaces;
  12389. const moduleExecIndex = this.context.getModuleExecIndex();
  12390. for (const identifier of this.references) {
  12391. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  12392. this.referencedEarly = true;
  12393. break;
  12394. }
  12395. }
  12396. }
  12397. }
  12398. NamespaceVariable.prototype.isNamespace = true;
  12399. class SyntheticNamedExportVariable extends Variable {
  12400. constructor(context, name, syntheticNamespace) {
  12401. super(name);
  12402. this.baseVariable = null;
  12403. this.context = context;
  12404. this.module = context.module;
  12405. this.syntheticNamespace = syntheticNamespace;
  12406. }
  12407. getBaseVariable() {
  12408. if (this.baseVariable)
  12409. return this.baseVariable;
  12410. let baseVariable = this.syntheticNamespace;
  12411. while (baseVariable instanceof ExportDefaultVariable ||
  12412. baseVariable instanceof SyntheticNamedExportVariable) {
  12413. if (baseVariable instanceof ExportDefaultVariable) {
  12414. const original = baseVariable.getOriginalVariable();
  12415. if (original === baseVariable)
  12416. break;
  12417. baseVariable = original;
  12418. }
  12419. if (baseVariable instanceof SyntheticNamedExportVariable) {
  12420. baseVariable = baseVariable.syntheticNamespace;
  12421. }
  12422. }
  12423. return (this.baseVariable = baseVariable);
  12424. }
  12425. getBaseVariableName() {
  12426. return this.syntheticNamespace.getBaseVariableName();
  12427. }
  12428. getName(getPropertyAccess) {
  12429. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  12430. }
  12431. include() {
  12432. this.included = true;
  12433. this.context.includeVariableInModule(this.syntheticNamespace);
  12434. }
  12435. setRenderNames(baseName, name) {
  12436. super.setRenderNames(baseName, name);
  12437. }
  12438. }
  12439. var BuildPhase;
  12440. (function (BuildPhase) {
  12441. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  12442. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  12443. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  12444. })(BuildPhase || (BuildPhase = {}));
  12445. function getId(m) {
  12446. return m.id;
  12447. }
  12448. function getAssertionsFromImportExpression(node) {
  12449. const assertProperty = node.arguments?.[0]?.properties.find((property) => getPropertyKey(property) === 'assert')?.value;
  12450. if (!assertProperty) {
  12451. return EMPTY_OBJECT;
  12452. }
  12453. const assertFields = assertProperty.properties
  12454. .map(property => {
  12455. const key = getPropertyKey(property);
  12456. if (typeof key === 'string' &&
  12457. typeof property.value.value === 'string') {
  12458. return [key, property.value.value];
  12459. }
  12460. return null;
  12461. })
  12462. .filter((property) => !!property);
  12463. if (assertFields.length > 0) {
  12464. return Object.fromEntries(assertFields);
  12465. }
  12466. return EMPTY_OBJECT;
  12467. }
  12468. const getPropertyKey = (property) => {
  12469. const key = property.key;
  12470. return key && (key.name || key.value);
  12471. };
  12472. function getAssertionsFromImportExportDeclaration(assertions) {
  12473. return assertions?.length
  12474. ? Object.fromEntries(assertions.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  12475. : EMPTY_OBJECT;
  12476. }
  12477. function doAssertionsDiffer(assertionA, assertionB) {
  12478. const keysA = Object.keys(assertionA);
  12479. return (keysA.length !== Object.keys(assertionB).length ||
  12480. keysA.some(key => assertionA[key] !== assertionB[key]));
  12481. }
  12482. const NOOP = () => { };
  12483. let timers = new Map();
  12484. function getPersistedLabel(label, level) {
  12485. switch (level) {
  12486. case 1: {
  12487. return `# ${label}`;
  12488. }
  12489. case 2: {
  12490. return `## ${label}`;
  12491. }
  12492. case 3: {
  12493. return label;
  12494. }
  12495. default: {
  12496. return `${' '.repeat(level - 4)}- ${label}`;
  12497. }
  12498. }
  12499. }
  12500. function timeStartImpl(label, level = 3) {
  12501. label = getPersistedLabel(label, level);
  12502. const startMemory = process$1.memoryUsage().heapUsed;
  12503. const startTime = node_perf_hooks.performance.now();
  12504. const timer = timers.get(label);
  12505. if (timer === undefined) {
  12506. timers.set(label, {
  12507. memory: 0,
  12508. startMemory,
  12509. startTime,
  12510. time: 0,
  12511. totalMemory: 0
  12512. });
  12513. }
  12514. else {
  12515. timer.startMemory = startMemory;
  12516. timer.startTime = startTime;
  12517. }
  12518. }
  12519. function timeEndImpl(label, level = 3) {
  12520. label = getPersistedLabel(label, level);
  12521. const timer = timers.get(label);
  12522. if (timer !== undefined) {
  12523. const currentMemory = process$1.memoryUsage().heapUsed;
  12524. timer.memory += currentMemory - timer.startMemory;
  12525. timer.time += node_perf_hooks.performance.now() - timer.startTime;
  12526. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  12527. }
  12528. }
  12529. function getTimings() {
  12530. const newTimings = {};
  12531. for (const [label, { memory, time, totalMemory }] of timers) {
  12532. newTimings[label] = [time, memory, totalMemory];
  12533. }
  12534. return newTimings;
  12535. }
  12536. let timeStart = NOOP;
  12537. let timeEnd = NOOP;
  12538. const TIMED_PLUGIN_HOOKS = [
  12539. 'augmentChunkHash',
  12540. 'buildEnd',
  12541. 'buildStart',
  12542. 'generateBundle',
  12543. 'load',
  12544. 'moduleParsed',
  12545. 'options',
  12546. 'outputOptions',
  12547. 'renderChunk',
  12548. 'renderDynamicImport',
  12549. 'renderStart',
  12550. 'resolveDynamicImport',
  12551. 'resolveFileUrl',
  12552. 'resolveId',
  12553. 'resolveImportMeta',
  12554. 'shouldTransformCachedModule',
  12555. 'transform',
  12556. 'writeBundle'
  12557. ];
  12558. function getPluginWithTimers(plugin, index) {
  12559. for (const hook of TIMED_PLUGIN_HOOKS) {
  12560. if (hook in plugin) {
  12561. let timerLabel = `plugin ${index}`;
  12562. if (plugin.name) {
  12563. timerLabel += ` (${plugin.name})`;
  12564. }
  12565. timerLabel += ` - ${hook}`;
  12566. const handler = function (...parameters) {
  12567. timeStart(timerLabel, 4);
  12568. const result = hookFunction.apply(this, parameters);
  12569. timeEnd(timerLabel, 4);
  12570. return result;
  12571. };
  12572. let hookFunction;
  12573. if (typeof plugin[hook].handler === 'function') {
  12574. hookFunction = plugin[hook].handler;
  12575. plugin[hook].handler = handler;
  12576. }
  12577. else {
  12578. hookFunction = plugin[hook];
  12579. plugin[hook] = handler;
  12580. }
  12581. }
  12582. }
  12583. return plugin;
  12584. }
  12585. function initialiseTimers(inputOptions) {
  12586. if (inputOptions.perf) {
  12587. timers = new Map();
  12588. timeStart = timeStartImpl;
  12589. timeEnd = timeEndImpl;
  12590. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  12591. }
  12592. else {
  12593. timeStart = NOOP;
  12594. timeEnd = NOOP;
  12595. }
  12596. }
  12597. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  12598. baseModule.isExecuted = true;
  12599. const modules = [baseModule];
  12600. const visitedModules = new Set();
  12601. for (const module of modules) {
  12602. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  12603. if (!(dependency instanceof ExternalModule) &&
  12604. !dependency.isExecuted &&
  12605. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  12606. !visitedModules.has(dependency.id)) {
  12607. dependency.isExecuted = true;
  12608. visitedModules.add(dependency.id);
  12609. modules.push(dependency);
  12610. }
  12611. }
  12612. }
  12613. }
  12614. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  12615. identifier: null,
  12616. localName: MISSING_EXPORT_SHIM_VARIABLE
  12617. };
  12618. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  12619. const searchedModules = searchedNamesAndModules.get(name);
  12620. if (searchedModules) {
  12621. if (searchedModules.has(target)) {
  12622. return isExportAllSearch ? [null] : error(errorCircularReexport(name, target.id));
  12623. }
  12624. searchedModules.add(target);
  12625. }
  12626. else {
  12627. searchedNamesAndModules.set(name, new Set([target]));
  12628. }
  12629. return target.getVariableForExportName(name, {
  12630. importerForSideEffects,
  12631. isExportAllSearch,
  12632. searchedNamesAndModules
  12633. });
  12634. }
  12635. function getAndExtendSideEffectModules(variable, module) {
  12636. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  12637. let currentVariable = variable;
  12638. const referencedVariables = new Set([currentVariable]);
  12639. while (true) {
  12640. const importingModule = currentVariable.module;
  12641. currentVariable =
  12642. currentVariable instanceof ExportDefaultVariable
  12643. ? currentVariable.getDirectOriginalVariable()
  12644. : currentVariable instanceof SyntheticNamedExportVariable
  12645. ? currentVariable.syntheticNamespace
  12646. : null;
  12647. if (!currentVariable || referencedVariables.has(currentVariable)) {
  12648. break;
  12649. }
  12650. referencedVariables.add(currentVariable);
  12651. sideEffectModules.add(importingModule);
  12652. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  12653. if (originalSideEffects) {
  12654. for (const module of originalSideEffects) {
  12655. sideEffectModules.add(module);
  12656. }
  12657. }
  12658. }
  12659. return sideEffectModules;
  12660. }
  12661. class Module {
  12662. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, assertions) {
  12663. this.graph = graph;
  12664. this.id = id;
  12665. this.options = options;
  12666. this.alternativeReexportModules = new Map();
  12667. this.chunkFileNames = new Set();
  12668. this.chunkNames = [];
  12669. this.cycles = new Set();
  12670. this.dependencies = new Set();
  12671. this.dynamicDependencies = new Set();
  12672. this.dynamicImporters = [];
  12673. this.dynamicImports = [];
  12674. this.execIndex = Infinity;
  12675. this.implicitlyLoadedAfter = new Set();
  12676. this.implicitlyLoadedBefore = new Set();
  12677. this.importDescriptions = new Map();
  12678. this.importMetas = [];
  12679. this.importedFromNotTreeshaken = false;
  12680. this.importers = [];
  12681. this.includedDynamicImporters = [];
  12682. this.includedImports = new Set();
  12683. this.isExecuted = false;
  12684. this.isUserDefinedEntryPoint = false;
  12685. this.needsExportShim = false;
  12686. this.sideEffectDependenciesByVariable = new Map();
  12687. this.sourcesWithAssertions = new Map();
  12688. this.allExportNames = null;
  12689. this.ast = null;
  12690. this.exportAllModules = [];
  12691. this.exportAllSources = new Set();
  12692. this.exportNamesByVariable = null;
  12693. this.exportShimVariable = new ExportShimVariable(this);
  12694. this.exports = new Map();
  12695. this.namespaceReexportsByName = new Map();
  12696. this.reexportDescriptions = new Map();
  12697. this.relevantDependencies = null;
  12698. this.syntheticExports = new Map();
  12699. this.syntheticNamespace = null;
  12700. this.transformDependencies = [];
  12701. this.transitiveReexports = null;
  12702. this.excludeFromSourcemap = /\0/.test(id);
  12703. this.context = options.moduleContext(id);
  12704. this.preserveSignature = this.options.preserveEntrySignatures;
  12705. // eslint-disable-next-line @typescript-eslint/no-this-alias
  12706. const module = this;
  12707. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAssertions } = this;
  12708. this.info = {
  12709. assertions,
  12710. ast: null,
  12711. code: null,
  12712. get dynamicallyImportedIdResolutions() {
  12713. return dynamicImports
  12714. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  12715. .filter(Boolean);
  12716. },
  12717. get dynamicallyImportedIds() {
  12718. // We cannot use this.dynamicDependencies because this is needed before
  12719. // dynamicDependencies are populated
  12720. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  12721. },
  12722. get dynamicImporters() {
  12723. return dynamicImporters.sort();
  12724. },
  12725. get exportedBindings() {
  12726. const exportBindings = { '.': [...exports.keys()] };
  12727. for (const [name, { source }] of reexportDescriptions) {
  12728. (exportBindings[source] ?? (exportBindings[source] = [])).push(name);
  12729. }
  12730. for (const source of exportAllSources) {
  12731. (exportBindings[source] ?? (exportBindings[source] = [])).push('*');
  12732. }
  12733. return exportBindings;
  12734. },
  12735. get exports() {
  12736. return [
  12737. ...exports.keys(),
  12738. ...reexportDescriptions.keys(),
  12739. ...[...exportAllSources].map(() => '*')
  12740. ];
  12741. },
  12742. get hasDefaultExport() {
  12743. // This information is only valid after parsing
  12744. if (!module.ast) {
  12745. return null;
  12746. }
  12747. return module.exports.has('default') || reexportDescriptions.has('default');
  12748. },
  12749. get hasModuleSideEffects() {
  12750. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options);
  12751. return this.moduleSideEffects;
  12752. },
  12753. id,
  12754. get implicitlyLoadedAfterOneOf() {
  12755. // eslint-disable-next-line unicorn/prefer-spread
  12756. return Array.from(implicitlyLoadedAfter, getId).sort();
  12757. },
  12758. get implicitlyLoadedBefore() {
  12759. // eslint-disable-next-line unicorn/prefer-spread
  12760. return Array.from(implicitlyLoadedBefore, getId).sort();
  12761. },
  12762. get importedIdResolutions() {
  12763. // eslint-disable-next-line unicorn/prefer-spread
  12764. return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]).filter(Boolean);
  12765. },
  12766. get importedIds() {
  12767. // We cannot use this.dependencies because this is needed before
  12768. // dependencies are populated
  12769. // eslint-disable-next-line unicorn/prefer-spread
  12770. return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  12771. },
  12772. get importers() {
  12773. return importers.sort();
  12774. },
  12775. isEntry,
  12776. isExternal: false,
  12777. get isIncluded() {
  12778. if (graph.phase !== BuildPhase.GENERATE) {
  12779. return null;
  12780. }
  12781. return module.isIncluded();
  12782. },
  12783. meta: { ...meta },
  12784. moduleSideEffects,
  12785. syntheticNamedExports
  12786. };
  12787. // Hide the deprecated key so that it only warns when accessed explicitly
  12788. // eslint-disable-next-line unicorn/consistent-destructuring
  12789. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  12790. enumerable: false
  12791. });
  12792. }
  12793. basename() {
  12794. const base = node_path.basename(this.id);
  12795. const extension = node_path.extname(this.id);
  12796. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  12797. }
  12798. bindReferences() {
  12799. this.ast.bind();
  12800. }
  12801. error(properties, pos) {
  12802. this.addLocationToLogProps(properties, pos);
  12803. return error(properties);
  12804. }
  12805. getAllExportNames() {
  12806. if (this.allExportNames) {
  12807. return this.allExportNames;
  12808. }
  12809. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  12810. for (const module of this.exportAllModules) {
  12811. if (module instanceof ExternalModule) {
  12812. this.allExportNames.add(`*${module.id}`);
  12813. continue;
  12814. }
  12815. for (const name of module.getAllExportNames()) {
  12816. if (name !== 'default')
  12817. this.allExportNames.add(name);
  12818. }
  12819. }
  12820. // We do not count the synthetic namespace as a regular export to hide it
  12821. // from entry signatures and namespace objects
  12822. if (typeof this.info.syntheticNamedExports === 'string') {
  12823. this.allExportNames.delete(this.info.syntheticNamedExports);
  12824. }
  12825. return this.allExportNames;
  12826. }
  12827. getDependenciesToBeIncluded() {
  12828. if (this.relevantDependencies)
  12829. return this.relevantDependencies;
  12830. this.relevantDependencies = new Set();
  12831. const necessaryDependencies = new Set();
  12832. const alwaysCheckedDependencies = new Set();
  12833. const dependencyVariables = new Set(this.includedImports);
  12834. if (this.info.isEntry ||
  12835. this.includedDynamicImporters.length > 0 ||
  12836. this.namespace.included ||
  12837. this.implicitlyLoadedAfter.size > 0) {
  12838. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  12839. const [exportedVariable] = this.getVariableForExportName(exportName);
  12840. if (exportedVariable) {
  12841. dependencyVariables.add(exportedVariable);
  12842. }
  12843. }
  12844. }
  12845. for (let variable of dependencyVariables) {
  12846. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  12847. if (sideEffectDependencies) {
  12848. for (const module of sideEffectDependencies) {
  12849. alwaysCheckedDependencies.add(module);
  12850. }
  12851. }
  12852. if (variable instanceof SyntheticNamedExportVariable) {
  12853. variable = variable.getBaseVariable();
  12854. }
  12855. else if (variable instanceof ExportDefaultVariable) {
  12856. variable = variable.getOriginalVariable();
  12857. }
  12858. necessaryDependencies.add(variable.module);
  12859. }
  12860. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  12861. for (const dependency of this.dependencies) {
  12862. this.relevantDependencies.add(dependency);
  12863. }
  12864. }
  12865. else {
  12866. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  12867. }
  12868. for (const dependency of necessaryDependencies) {
  12869. this.relevantDependencies.add(dependency);
  12870. }
  12871. return this.relevantDependencies;
  12872. }
  12873. getExportNamesByVariable() {
  12874. if (this.exportNamesByVariable) {
  12875. return this.exportNamesByVariable;
  12876. }
  12877. const exportNamesByVariable = new Map();
  12878. for (const exportName of this.getAllExportNames()) {
  12879. let [tracedVariable] = this.getVariableForExportName(exportName);
  12880. if (tracedVariable instanceof ExportDefaultVariable) {
  12881. tracedVariable = tracedVariable.getOriginalVariable();
  12882. }
  12883. if (!tracedVariable ||
  12884. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  12885. continue;
  12886. }
  12887. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  12888. if (existingExportNames) {
  12889. existingExportNames.push(exportName);
  12890. }
  12891. else {
  12892. exportNamesByVariable.set(tracedVariable, [exportName]);
  12893. }
  12894. }
  12895. return (this.exportNamesByVariable = exportNamesByVariable);
  12896. }
  12897. getExports() {
  12898. return [...this.exports.keys()];
  12899. }
  12900. getReexports() {
  12901. if (this.transitiveReexports) {
  12902. return this.transitiveReexports;
  12903. }
  12904. // to avoid infinite recursion when using circular `export * from X`
  12905. this.transitiveReexports = [];
  12906. const reexports = new Set(this.reexportDescriptions.keys());
  12907. for (const module of this.exportAllModules) {
  12908. if (module instanceof ExternalModule) {
  12909. reexports.add(`*${module.id}`);
  12910. }
  12911. else {
  12912. for (const name of [...module.getReexports(), ...module.getExports()]) {
  12913. if (name !== 'default')
  12914. reexports.add(name);
  12915. }
  12916. }
  12917. }
  12918. return (this.transitiveReexports = [...reexports]);
  12919. }
  12920. getRenderedExports() {
  12921. // only direct exports are counted here, not reexports at all
  12922. const renderedExports = [];
  12923. const removedExports = [];
  12924. for (const exportName of this.exports.keys()) {
  12925. const [variable] = this.getVariableForExportName(exportName);
  12926. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  12927. }
  12928. return { removedExports, renderedExports };
  12929. }
  12930. getSyntheticNamespace() {
  12931. if (this.syntheticNamespace === null) {
  12932. this.syntheticNamespace = undefined;
  12933. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  12934. ? this.info.syntheticNamedExports
  12935. : 'default', { onlyExplicit: true });
  12936. }
  12937. if (!this.syntheticNamespace) {
  12938. return error(errorSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  12939. }
  12940. return this.syntheticNamespace;
  12941. }
  12942. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  12943. if (name[0] === '*') {
  12944. if (name.length === 1) {
  12945. // export * from './other'
  12946. return [this.namespace];
  12947. }
  12948. // export * from 'external'
  12949. const module = this.graph.modulesById.get(name.slice(1));
  12950. return module.getVariableForExportName('*');
  12951. }
  12952. // export { foo } from './other'
  12953. const reexportDeclaration = this.reexportDescriptions.get(name);
  12954. if (reexportDeclaration) {
  12955. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  12956. if (!variable) {
  12957. return this.error(errorMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  12958. }
  12959. if (importerForSideEffects) {
  12960. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  12961. if (this.info.moduleSideEffects) {
  12962. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  12963. }
  12964. }
  12965. return [variable];
  12966. }
  12967. const exportDeclaration = this.exports.get(name);
  12968. if (exportDeclaration) {
  12969. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  12970. return [this.exportShimVariable];
  12971. }
  12972. const name = exportDeclaration.localName;
  12973. const variable = this.traceVariable(name, {
  12974. importerForSideEffects,
  12975. searchedNamesAndModules
  12976. });
  12977. if (importerForSideEffects) {
  12978. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  12979. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  12980. }
  12981. return [variable];
  12982. }
  12983. if (onlyExplicit) {
  12984. return [null];
  12985. }
  12986. if (name !== 'default') {
  12987. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  12988. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  12989. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  12990. if (foundNamespaceReexport[0]) {
  12991. return foundNamespaceReexport;
  12992. }
  12993. }
  12994. if (this.info.syntheticNamedExports) {
  12995. return [
  12996. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  12997. ];
  12998. }
  12999. // we don't want to create shims when we are just
  13000. // probing export * modules for exports
  13001. if (!isExportAllSearch && this.options.shimMissingExports) {
  13002. this.shimMissingExport(name);
  13003. return [this.exportShimVariable];
  13004. }
  13005. return [null];
  13006. }
  13007. hasEffects() {
  13008. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  13009. }
  13010. include() {
  13011. const context = createInclusionContext();
  13012. if (this.ast.shouldBeIncluded(context))
  13013. this.ast.include(context, false);
  13014. }
  13015. includeAllExports(includeNamespaceMembers) {
  13016. if (!this.isExecuted) {
  13017. markModuleAndImpureDependenciesAsExecuted(this);
  13018. this.graph.needsTreeshakingPass = true;
  13019. }
  13020. for (const exportName of this.exports.keys()) {
  13021. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  13022. const variable = this.getVariableForExportName(exportName)[0];
  13023. variable.deoptimizePath(UNKNOWN_PATH);
  13024. if (!variable.included) {
  13025. this.includeVariable(variable);
  13026. }
  13027. }
  13028. }
  13029. for (const name of this.getReexports()) {
  13030. const [variable] = this.getVariableForExportName(name);
  13031. if (variable) {
  13032. variable.deoptimizePath(UNKNOWN_PATH);
  13033. if (!variable.included) {
  13034. this.includeVariable(variable);
  13035. }
  13036. if (variable instanceof ExternalVariable) {
  13037. variable.module.reexported = true;
  13038. }
  13039. }
  13040. }
  13041. if (includeNamespaceMembers) {
  13042. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  13043. }
  13044. }
  13045. includeAllInBundle() {
  13046. this.ast.include(createInclusionContext(), true);
  13047. this.includeAllExports(false);
  13048. }
  13049. isIncluded() {
  13050. // Modules where this.ast is missing have been loaded via this.load and are
  13051. // not yet fully processed, hence they cannot be included.
  13052. return (this.ast && (this.ast.included || this.namespace.included || this.importedFromNotTreeshaken));
  13053. }
  13054. linkImports() {
  13055. this.addModulesToImportDescriptions(this.importDescriptions);
  13056. this.addModulesToImportDescriptions(this.reexportDescriptions);
  13057. const externalExportAllModules = [];
  13058. for (const source of this.exportAllSources) {
  13059. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  13060. if (module instanceof ExternalModule) {
  13061. externalExportAllModules.push(module);
  13062. continue;
  13063. }
  13064. this.exportAllModules.push(module);
  13065. }
  13066. this.exportAllModules.push(...externalExportAllModules);
  13067. }
  13068. render(options) {
  13069. const source = this.magicString.clone();
  13070. this.ast.render(source, options);
  13071. source.trim();
  13072. const { usesTopLevelAwait } = this.astContext;
  13073. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  13074. return error(errorInvalidFormatForTopLevelAwait(this.id, options.format));
  13075. }
  13076. return { source, usesTopLevelAwait };
  13077. }
  13078. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  13079. timeStart('generate ast', 3);
  13080. this.info.code = code;
  13081. this.originalCode = originalCode;
  13082. this.originalSourcemap = originalSourcemap;
  13083. this.sourcemapChain = sourcemapChain;
  13084. if (transformFiles) {
  13085. this.transformFiles = transformFiles;
  13086. }
  13087. this.transformDependencies = transformDependencies;
  13088. this.customTransformCache = customTransformCache;
  13089. this.updateOptions(moduleOptions);
  13090. const moduleAst = ast ?? this.tryParse();
  13091. timeEnd('generate ast', 3);
  13092. timeStart('analyze ast', 3);
  13093. this.resolvedIds = resolvedIds ?? Object.create(null);
  13094. // By default, `id` is the file name. Custom resolvers and loaders
  13095. // can change that, but it makes sense to use it for the source file name
  13096. const fileName = this.id;
  13097. this.magicString = new MagicString(code, {
  13098. filename: (this.excludeFromSourcemap ? null : fileName),
  13099. indentExclusionRanges: []
  13100. });
  13101. this.astContext = {
  13102. addDynamicImport: this.addDynamicImport.bind(this),
  13103. addExport: this.addExport.bind(this),
  13104. addImport: this.addImport.bind(this),
  13105. addImportMeta: this.addImportMeta.bind(this),
  13106. code,
  13107. deoptimizationTracker: this.graph.deoptimizationTracker,
  13108. error: this.error.bind(this),
  13109. fileName,
  13110. getExports: this.getExports.bind(this),
  13111. getModuleExecIndex: () => this.execIndex,
  13112. getModuleName: this.basename.bind(this),
  13113. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  13114. getReexports: this.getReexports.bind(this),
  13115. importDescriptions: this.importDescriptions,
  13116. includeAllExports: () => this.includeAllExports(true),
  13117. includeDynamicImport: this.includeDynamicImport.bind(this),
  13118. includeVariableInModule: this.includeVariableInModule.bind(this),
  13119. magicString: this.magicString,
  13120. manualPureFunctions: this.graph.pureFunctions,
  13121. module: this,
  13122. moduleContext: this.context,
  13123. options: this.options,
  13124. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  13125. traceExport: (name) => this.getVariableForExportName(name)[0],
  13126. traceVariable: this.traceVariable.bind(this),
  13127. usesTopLevelAwait: false,
  13128. warn: this.warn.bind(this)
  13129. };
  13130. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  13131. this.namespace = new NamespaceVariable(this.astContext);
  13132. this.ast = new Program(moduleAst, { context: this.astContext, type: 'Module' }, this.scope);
  13133. // Assign AST directly if has existing one as there's no way to drop it from memory.
  13134. // If cache is enabled, also assign directly as otherwise it takes more CPU and memory to re-compute.
  13135. if (ast || this.options.cache !== false) {
  13136. this.info.ast = moduleAst;
  13137. }
  13138. else {
  13139. // Make lazy and apply LRU cache to not hog the memory
  13140. Object.defineProperty(this.info, 'ast', {
  13141. get: () => {
  13142. if (this.graph.astLru.has(fileName)) {
  13143. return this.graph.astLru.get(fileName);
  13144. }
  13145. else {
  13146. const parsedAst = this.tryParse();
  13147. this.graph.astLru.set(fileName, parsedAst);
  13148. return parsedAst;
  13149. }
  13150. }
  13151. });
  13152. }
  13153. timeEnd('analyze ast', 3);
  13154. }
  13155. toJSON() {
  13156. return {
  13157. assertions: this.info.assertions,
  13158. ast: this.info.ast,
  13159. code: this.info.code,
  13160. customTransformCache: this.customTransformCache,
  13161. // eslint-disable-next-line unicorn/prefer-spread
  13162. dependencies: Array.from(this.dependencies, getId),
  13163. id: this.id,
  13164. meta: this.info.meta,
  13165. moduleSideEffects: this.info.moduleSideEffects,
  13166. originalCode: this.originalCode,
  13167. originalSourcemap: this.originalSourcemap,
  13168. resolvedIds: this.resolvedIds,
  13169. sourcemapChain: this.sourcemapChain,
  13170. syntheticNamedExports: this.info.syntheticNamedExports,
  13171. transformDependencies: this.transformDependencies,
  13172. transformFiles: this.transformFiles
  13173. };
  13174. }
  13175. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  13176. const localVariable = this.scope.variables.get(name);
  13177. if (localVariable) {
  13178. return localVariable;
  13179. }
  13180. const importDescription = this.importDescriptions.get(name);
  13181. if (importDescription) {
  13182. const otherModule = importDescription.module;
  13183. if (otherModule instanceof Module && importDescription.name === '*') {
  13184. return otherModule.namespace;
  13185. }
  13186. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  13187. if (!declaration) {
  13188. return this.error(errorMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  13189. }
  13190. return declaration;
  13191. }
  13192. return null;
  13193. }
  13194. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  13195. if (moduleSideEffects != null) {
  13196. this.info.moduleSideEffects = moduleSideEffects;
  13197. }
  13198. if (syntheticNamedExports != null) {
  13199. this.info.syntheticNamedExports = syntheticNamedExports;
  13200. }
  13201. if (meta != null) {
  13202. Object.assign(this.info.meta, meta);
  13203. }
  13204. }
  13205. warn(properties, pos) {
  13206. this.addLocationToLogProps(properties, pos);
  13207. this.options.onwarn(properties);
  13208. }
  13209. addDynamicImport(node) {
  13210. let argument = node.source;
  13211. if (argument instanceof TemplateLiteral) {
  13212. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  13213. argument = argument.quasis[0].value.cooked;
  13214. }
  13215. }
  13216. else if (argument instanceof Literal && typeof argument.value === 'string') {
  13217. argument = argument.value;
  13218. }
  13219. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  13220. }
  13221. addExport(node) {
  13222. if (node instanceof ExportDefaultDeclaration) {
  13223. // export default foo;
  13224. this.exports.set('default', {
  13225. identifier: node.variable.getAssignedVariableName(),
  13226. localName: 'default'
  13227. });
  13228. }
  13229. else if (node instanceof ExportAllDeclaration) {
  13230. const source = node.source.value;
  13231. this.addSource(source, node);
  13232. if (node.exported) {
  13233. // export * as name from './other'
  13234. const name = node.exported.name;
  13235. this.reexportDescriptions.set(name, {
  13236. localName: '*',
  13237. module: null,
  13238. source,
  13239. start: node.start
  13240. });
  13241. }
  13242. else {
  13243. // export * from './other'
  13244. this.exportAllSources.add(source);
  13245. }
  13246. }
  13247. else if (node.source instanceof Literal) {
  13248. // export { name } from './other'
  13249. const source = node.source.value;
  13250. this.addSource(source, node);
  13251. for (const { exported, local, start } of node.specifiers) {
  13252. const name = exported instanceof Literal ? exported.value : exported.name;
  13253. this.reexportDescriptions.set(name, {
  13254. localName: local instanceof Literal ? local.value : local.name,
  13255. module: null,
  13256. source,
  13257. start
  13258. });
  13259. }
  13260. }
  13261. else if (node.declaration) {
  13262. const declaration = node.declaration;
  13263. if (declaration instanceof VariableDeclaration) {
  13264. // export var { foo, bar } = ...
  13265. // export var foo = 1, bar = 2;
  13266. for (const declarator of declaration.declarations) {
  13267. for (const localName of extractAssignedNames(declarator.id)) {
  13268. this.exports.set(localName, { identifier: null, localName });
  13269. }
  13270. }
  13271. }
  13272. else {
  13273. // export function foo () {}
  13274. const localName = declaration.id.name;
  13275. this.exports.set(localName, { identifier: null, localName });
  13276. }
  13277. }
  13278. else {
  13279. // export { foo, bar, baz }
  13280. for (const { local, exported } of node.specifiers) {
  13281. // except for reexports, local must be an Identifier
  13282. const localName = local.name;
  13283. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  13284. this.exports.set(exportedName, { identifier: null, localName });
  13285. }
  13286. }
  13287. }
  13288. addImport(node) {
  13289. const source = node.source.value;
  13290. this.addSource(source, node);
  13291. for (const specifier of node.specifiers) {
  13292. const name = specifier instanceof ImportDefaultSpecifier
  13293. ? 'default'
  13294. : specifier instanceof ImportNamespaceSpecifier
  13295. ? '*'
  13296. : specifier.imported instanceof Identifier
  13297. ? specifier.imported.name
  13298. : specifier.imported.value;
  13299. this.importDescriptions.set(specifier.local.name, {
  13300. module: null,
  13301. name,
  13302. source,
  13303. start: specifier.start
  13304. });
  13305. }
  13306. }
  13307. addImportMeta(node) {
  13308. this.importMetas.push(node);
  13309. }
  13310. addLocationToLogProps(properties, pos) {
  13311. properties.id = this.id;
  13312. properties.pos = pos;
  13313. let code = this.info.code;
  13314. const location = locate(code, pos, { offsetLine: 1 });
  13315. if (location) {
  13316. let { column, line } = location;
  13317. try {
  13318. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  13319. code = this.originalCode;
  13320. }
  13321. catch (error_) {
  13322. this.options.onwarn(errorInvalidSourcemapForError(error_, this.id, column, line, pos));
  13323. }
  13324. augmentCodeLocation(properties, { column, line }, code, this.id);
  13325. }
  13326. }
  13327. addModulesToImportDescriptions(importDescription) {
  13328. for (const specifier of importDescription.values()) {
  13329. const { id } = this.resolvedIds[specifier.source];
  13330. specifier.module = this.graph.modulesById.get(id);
  13331. }
  13332. }
  13333. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  13334. const handledDependencies = new Set();
  13335. const addSideEffectDependencies = (possibleDependencies) => {
  13336. for (const dependency of possibleDependencies) {
  13337. if (handledDependencies.has(dependency)) {
  13338. continue;
  13339. }
  13340. handledDependencies.add(dependency);
  13341. if (necessaryDependencies.has(dependency)) {
  13342. relevantDependencies.add(dependency);
  13343. continue;
  13344. }
  13345. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  13346. continue;
  13347. }
  13348. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  13349. relevantDependencies.add(dependency);
  13350. continue;
  13351. }
  13352. addSideEffectDependencies(dependency.dependencies);
  13353. }
  13354. };
  13355. addSideEffectDependencies(this.dependencies);
  13356. addSideEffectDependencies(alwaysCheckedDependencies);
  13357. }
  13358. addSource(source, declaration) {
  13359. const parsedAssertions = getAssertionsFromImportExportDeclaration(declaration.assertions);
  13360. const existingAssertions = this.sourcesWithAssertions.get(source);
  13361. if (existingAssertions) {
  13362. if (doAssertionsDiffer(existingAssertions, parsedAssertions)) {
  13363. this.warn(errorInconsistentImportAssertions(existingAssertions, parsedAssertions, source, this.id), declaration.start);
  13364. }
  13365. }
  13366. else {
  13367. this.sourcesWithAssertions.set(source, parsedAssertions);
  13368. }
  13369. }
  13370. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  13371. let foundSyntheticDeclaration = null;
  13372. const foundInternalDeclarations = new Map();
  13373. const foundExternalDeclarations = new Set();
  13374. for (const module of this.exportAllModules) {
  13375. // Synthetic namespaces should not hide "regular" exports of the same name
  13376. if (module.info.syntheticNamedExports === name) {
  13377. continue;
  13378. }
  13379. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  13380. // We are creating a copy to handle the case where the same binding is
  13381. // imported through different namespace reexports gracefully
  13382. copyNameToModulesMap(searchedNamesAndModules));
  13383. if (module instanceof ExternalModule || indirectExternal) {
  13384. foundExternalDeclarations.add(variable);
  13385. }
  13386. else if (variable instanceof SyntheticNamedExportVariable) {
  13387. if (!foundSyntheticDeclaration) {
  13388. foundSyntheticDeclaration = variable;
  13389. }
  13390. }
  13391. else if (variable) {
  13392. foundInternalDeclarations.set(variable, module);
  13393. }
  13394. }
  13395. if (foundInternalDeclarations.size > 0) {
  13396. const foundDeclarationList = [...foundInternalDeclarations];
  13397. const usedDeclaration = foundDeclarationList[0][0];
  13398. if (foundDeclarationList.length === 1) {
  13399. return [usedDeclaration];
  13400. }
  13401. this.options.onwarn(errorNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  13402. // TODO we are pretending it was not found while it should behave like "undefined"
  13403. return [null];
  13404. }
  13405. if (foundExternalDeclarations.size > 0) {
  13406. const foundDeclarationList = [...foundExternalDeclarations];
  13407. const usedDeclaration = foundDeclarationList[0];
  13408. if (foundDeclarationList.length > 1) {
  13409. this.options.onwarn(errorAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  13410. }
  13411. return [usedDeclaration, true];
  13412. }
  13413. if (foundSyntheticDeclaration) {
  13414. return [foundSyntheticDeclaration];
  13415. }
  13416. return [null];
  13417. }
  13418. includeAndGetAdditionalMergedNamespaces() {
  13419. const externalNamespaces = new Set();
  13420. const syntheticNamespaces = new Set();
  13421. for (const module of [this, ...this.exportAllModules]) {
  13422. if (module instanceof ExternalModule) {
  13423. const [externalVariable] = module.getVariableForExportName('*');
  13424. externalVariable.include();
  13425. this.includedImports.add(externalVariable);
  13426. externalNamespaces.add(externalVariable);
  13427. }
  13428. else if (module.info.syntheticNamedExports) {
  13429. const syntheticNamespace = module.getSyntheticNamespace();
  13430. syntheticNamespace.include();
  13431. this.includedImports.add(syntheticNamespace);
  13432. syntheticNamespaces.add(syntheticNamespace);
  13433. }
  13434. }
  13435. return [...syntheticNamespaces, ...externalNamespaces];
  13436. }
  13437. includeDynamicImport(node) {
  13438. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  13439. if (resolution instanceof Module) {
  13440. resolution.includedDynamicImporters.push(this);
  13441. resolution.includeAllExports(true);
  13442. }
  13443. }
  13444. includeVariable(variable) {
  13445. if (!variable.included) {
  13446. variable.include();
  13447. this.graph.needsTreeshakingPass = true;
  13448. const variableModule = variable.module;
  13449. if (variableModule instanceof Module) {
  13450. if (!variableModule.isExecuted) {
  13451. markModuleAndImpureDependenciesAsExecuted(variableModule);
  13452. }
  13453. if (variableModule !== this) {
  13454. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  13455. for (const module of sideEffectModules) {
  13456. if (!module.isExecuted) {
  13457. markModuleAndImpureDependenciesAsExecuted(module);
  13458. }
  13459. }
  13460. }
  13461. }
  13462. }
  13463. }
  13464. includeVariableInModule(variable) {
  13465. this.includeVariable(variable);
  13466. const variableModule = variable.module;
  13467. if (variableModule && variableModule !== this) {
  13468. this.includedImports.add(variable);
  13469. }
  13470. }
  13471. shimMissingExport(name) {
  13472. this.options.onwarn(errorShimmedExport(this.id, name));
  13473. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  13474. }
  13475. tryParse() {
  13476. try {
  13477. return this.graph.contextParse(this.info.code);
  13478. }
  13479. catch (error_) {
  13480. return this.error(errorParseError(error_, this.id), error_.pos);
  13481. }
  13482. }
  13483. }
  13484. // if there is a cyclic import in the reexport chain, we should not
  13485. // import from the original module but from the cyclic module to not
  13486. // mess up execution order.
  13487. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  13488. if (variable.module instanceof Module && variable.module !== reexporter) {
  13489. const exporterCycles = variable.module.cycles;
  13490. if (exporterCycles.size > 0) {
  13491. const importerCycles = reexporter.cycles;
  13492. for (const cycleSymbol of importerCycles) {
  13493. if (exporterCycles.has(cycleSymbol)) {
  13494. importer.alternativeReexportModules.set(variable, reexporter);
  13495. break;
  13496. }
  13497. }
  13498. }
  13499. }
  13500. }
  13501. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  13502. // eslint-disable-next-line unicorn/prefer-spread
  13503. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  13504. function removeJsExtension(name) {
  13505. return name.endsWith('.js') ? name.slice(0, -3) : name;
  13506. }
  13507. function getCompleteAmdId(options, chunkId) {
  13508. if (options.autoId) {
  13509. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  13510. }
  13511. return options.id ?? '';
  13512. }
  13513. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
  13514. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  13515. if (!namedExportsMode) {
  13516. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  13517. }
  13518. let exportBlock = '';
  13519. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13520. if (reexports && namedExportsMode) {
  13521. for (const specifier of reexports) {
  13522. if (specifier.reexported !== '*') {
  13523. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  13524. if (exportBlock)
  13525. exportBlock += n;
  13526. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  13527. const [left, right] = getDirectReturnFunction([], {
  13528. functionReturn: true,
  13529. lineBreakIndent: null,
  13530. name: null
  13531. });
  13532. exportBlock +=
  13533. `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  13534. `${t}enumerable:${_}true,${n}` +
  13535. `${t}get:${_}${left}${importName}${right}${n}});`;
  13536. }
  13537. else {
  13538. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  13539. }
  13540. }
  13541. }
  13542. }
  13543. }
  13544. for (const { exported, local } of exports) {
  13545. const lhs = `exports${getPropertyAccess(exported)}`;
  13546. const rhs = local;
  13547. if (lhs !== rhs) {
  13548. if (exportBlock)
  13549. exportBlock += n;
  13550. exportBlock += `${lhs}${_}=${_}${rhs};`;
  13551. }
  13552. }
  13553. for (const { name, reexports } of dependencies) {
  13554. if (reexports && namedExportsMode) {
  13555. for (const specifier of reexports) {
  13556. if (specifier.reexported === '*') {
  13557. if (exportBlock)
  13558. exportBlock += n;
  13559. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  13560. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  13561. isAsync: false,
  13562. name: null
  13563. })}${copyPropertyIfNecessary});`;
  13564. }
  13565. }
  13566. }
  13567. }
  13568. if (exportBlock) {
  13569. return `${n}${n}${exportBlock}`;
  13570. }
  13571. return '';
  13572. }
  13573. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  13574. if (exports.length > 0) {
  13575. return exports[0].local;
  13576. }
  13577. else {
  13578. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13579. if (reexports) {
  13580. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  13581. }
  13582. }
  13583. }
  13584. }
  13585. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  13586. if (imported === 'default') {
  13587. if (!isChunk) {
  13588. const moduleInterop = interop(moduleId);
  13589. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  13590. ? defaultVariableName
  13591. : moduleVariableName;
  13592. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  13593. ? `${variableName}${getPropertyAccess('default')}`
  13594. : variableName;
  13595. }
  13596. return depNamedExportsMode
  13597. ? `${moduleVariableName}${getPropertyAccess('default')}`
  13598. : moduleVariableName;
  13599. }
  13600. if (imported === '*') {
  13601. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  13602. ? namespaceVariableName
  13603. : moduleVariableName;
  13604. }
  13605. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  13606. }
  13607. function getEsModuleValue(getObject) {
  13608. return getObject([['value', 'true']], {
  13609. lineBreakIndent: null
  13610. });
  13611. }
  13612. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  13613. if (hasNamedExports) {
  13614. if (addEsModule) {
  13615. if (addNamespaceToStringTag) {
  13616. return `Object.defineProperties(exports,${_}${getObject([
  13617. ['__esModule', getEsModuleValue(getObject)],
  13618. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  13619. ], {
  13620. lineBreakIndent: null
  13621. })});`;
  13622. }
  13623. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  13624. }
  13625. if (addNamespaceToStringTag) {
  13626. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  13627. }
  13628. }
  13629. return '';
  13630. }
  13631. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  13632. if (needsLiveBinding) {
  13633. const [left, right] = getDirectReturnFunction([], {
  13634. functionReturn: true,
  13635. lineBreakIndent: null,
  13636. name: null
  13637. });
  13638. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  13639. `${t}${t}enumerable:${_}true,${n}` +
  13640. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  13641. }
  13642. return `exports[k]${_}=${_}${name}[k]`;
  13643. };
  13644. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
  13645. const { _, cnst, n } = snippets;
  13646. const neededInteropHelpers = new Set();
  13647. const interopStatements = [];
  13648. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  13649. neededInteropHelpers.add(helper);
  13650. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  13651. };
  13652. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13653. if (isChunk) {
  13654. for (const { imported, reexported } of [
  13655. ...(imports || []),
  13656. ...(reexports || [])
  13657. ]) {
  13658. if (imported === '*' && reexported !== '*') {
  13659. if (!namedExportsMode) {
  13660. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  13661. }
  13662. break;
  13663. }
  13664. }
  13665. }
  13666. else {
  13667. const moduleInterop = interop(importPath);
  13668. let hasDefault = false;
  13669. let hasNamespace = false;
  13670. for (const { imported, reexported } of [
  13671. ...(imports || []),
  13672. ...(reexports || [])
  13673. ]) {
  13674. let helper;
  13675. let variableName;
  13676. if (imported === 'default') {
  13677. if (!hasDefault) {
  13678. hasDefault = true;
  13679. if (defaultVariableName !== namespaceVariableName) {
  13680. variableName = defaultVariableName;
  13681. helper = defaultInteropHelpersByInteropType[moduleInterop];
  13682. }
  13683. }
  13684. }
  13685. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  13686. hasNamespace = true;
  13687. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  13688. variableName = namespaceVariableName;
  13689. }
  13690. if (helper) {
  13691. addInteropStatement(variableName, helper, name);
  13692. }
  13693. }
  13694. }
  13695. }
  13696. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  13697. }
  13698. function addJsExtension(name) {
  13699. return name.endsWith('.js') ? name : name + '.js';
  13700. }
  13701. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  13702. // The assumption is that this makes sense for all relative ids:
  13703. // https://requirejs.org/docs/api.html#jsfiles
  13704. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  13705. if (id[0] !== '.') {
  13706. return id;
  13707. }
  13708. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  13709. }
  13710. var _staticExports = {};
  13711. var _static = {
  13712. get exports(){ return _staticExports; },
  13713. set exports(v){ _staticExports = v; },
  13714. };
  13715. const require$$0 = [
  13716. "assert",
  13717. "async_hooks",
  13718. "buffer",
  13719. "child_process",
  13720. "cluster",
  13721. "console",
  13722. "constants",
  13723. "crypto",
  13724. "dgram",
  13725. "diagnostics_channel",
  13726. "dns",
  13727. "domain",
  13728. "events",
  13729. "fs",
  13730. "http",
  13731. "http2",
  13732. "https",
  13733. "inspector",
  13734. "module",
  13735. "net",
  13736. "os",
  13737. "path",
  13738. "perf_hooks",
  13739. "process",
  13740. "punycode",
  13741. "querystring",
  13742. "readline",
  13743. "repl",
  13744. "stream",
  13745. "string_decoder",
  13746. "timers",
  13747. "tls",
  13748. "trace_events",
  13749. "tty",
  13750. "url",
  13751. "util",
  13752. "v8",
  13753. "vm",
  13754. "wasi",
  13755. "worker_threads",
  13756. "zlib"
  13757. ];
  13758. (function (module) {
  13759. module.exports = require$$0;
  13760. } (_static));
  13761. const builtinModules = /*@__PURE__*/getDefaultExportFromCjs(_staticExports);
  13762. const nodeBuiltins = new Set([
  13763. ...builtinModules,
  13764. // TODO
  13765. // remove once builtin-modules includes PR: https://github.com/sindresorhus/builtin-modules/pull/17
  13766. 'assert/strict',
  13767. 'dns/promises',
  13768. 'fs/promises',
  13769. 'path/posix',
  13770. 'path/win32',
  13771. 'readline/promises',
  13772. 'stream/consumers',
  13773. 'stream/promises',
  13774. 'stream/web',
  13775. 'timers/promises',
  13776. 'util/types'
  13777. ]);
  13778. function warnOnBuiltins(warn, dependencies) {
  13779. const externalBuiltins = dependencies
  13780. .map(({ importPath }) => importPath)
  13781. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  13782. if (externalBuiltins.length === 0)
  13783. return;
  13784. warn(errorMissingNodeBuiltins(externalBuiltins));
  13785. }
  13786. function amd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, onwarn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  13787. warnOnBuiltins(onwarn, dependencies);
  13788. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  13789. const parameters = dependencies.map(m => m.name);
  13790. const { n, getNonArrowFunctionIntro, _ } = snippets;
  13791. if (namedExportsMode && hasExports) {
  13792. parameters.unshift(`exports`);
  13793. deps.unshift(`'exports'`);
  13794. }
  13795. if (accessedGlobals.has('require')) {
  13796. parameters.unshift('require');
  13797. deps.unshift(`'require'`);
  13798. }
  13799. if (accessedGlobals.has('module')) {
  13800. parameters.unshift('module');
  13801. deps.unshift(`'module'`);
  13802. }
  13803. const completeAmdId = getCompleteAmdId(amd, id);
  13804. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  13805. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  13806. const useStrict = strict ? `${_}'use strict';` : '';
  13807. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  13808. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  13809. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets);
  13810. if (namespaceMarkers) {
  13811. namespaceMarkers = n + n + namespaceMarkers;
  13812. }
  13813. magicString
  13814. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  13815. .indent(t)
  13816. // factory function should be wrapped by parentheses to avoid lazy parsing,
  13817. // cf. https://v8.dev/blog/preparser#pife
  13818. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  13819. isAsync: false,
  13820. name: null
  13821. })}{${useStrict}${n}${n}`)
  13822. .append(`${n}${n}}));`);
  13823. }
  13824. function cjs(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  13825. const { _, n } = snippets;
  13826. const useStrict = strict ? `'use strict';${n}${n}` : '';
  13827. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets);
  13828. if (namespaceMarkers) {
  13829. namespaceMarkers += n + n;
  13830. }
  13831. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  13832. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  13833. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  13834. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
  13835. magicString.append(`${exportBlock}${outro}`);
  13836. }
  13837. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  13838. let importBlock = '';
  13839. let definingVariable = false;
  13840. for (const { importPath, name, reexports, imports } of dependencies) {
  13841. if (!reexports && !imports) {
  13842. if (importBlock) {
  13843. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  13844. }
  13845. definingVariable = false;
  13846. importBlock += `require('${importPath}')`;
  13847. }
  13848. else {
  13849. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  13850. definingVariable = true;
  13851. importBlock += `${name}${_}=${_}require('${importPath}')`;
  13852. }
  13853. }
  13854. if (importBlock) {
  13855. return `${importBlock};${n}${n}`;
  13856. }
  13857. return '';
  13858. }
  13859. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
  13860. const { n } = snippets;
  13861. const importBlock = getImportBlock(dependencies, snippets);
  13862. if (importBlock.length > 0)
  13863. intro += importBlock.join(n) + n + n;
  13864. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
  13865. if (intro)
  13866. magicString.prepend(intro);
  13867. const exportBlock = getExportBlock(exports, snippets);
  13868. if (exportBlock.length > 0)
  13869. magicString.append(n + n + exportBlock.join(n).trim());
  13870. if (outro)
  13871. magicString.append(outro);
  13872. magicString.trim();
  13873. }
  13874. function getImportBlock(dependencies, { _ }) {
  13875. const importBlock = [];
  13876. for (const { importPath, reexports, imports, name, assertions } of dependencies) {
  13877. const assertion = assertions ? `${_}assert${_}${assertions}` : '';
  13878. const pathWithAssertion = `'${importPath}'${assertion};`;
  13879. if (!reexports && !imports) {
  13880. importBlock.push(`import${_}${pathWithAssertion}`);
  13881. continue;
  13882. }
  13883. if (imports) {
  13884. let defaultImport = null;
  13885. let starImport = null;
  13886. const importedNames = [];
  13887. for (const specifier of imports) {
  13888. if (specifier.imported === 'default') {
  13889. defaultImport = specifier;
  13890. }
  13891. else if (specifier.imported === '*') {
  13892. starImport = specifier;
  13893. }
  13894. else {
  13895. importedNames.push(specifier);
  13896. }
  13897. }
  13898. if (starImport) {
  13899. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  13900. }
  13901. if (defaultImport && importedNames.length === 0) {
  13902. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  13903. }
  13904. else if (importedNames.length > 0) {
  13905. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  13906. .map(specifier => specifier.imported === specifier.local
  13907. ? specifier.imported
  13908. : `${specifier.imported} as ${specifier.local}`)
  13909. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  13910. }
  13911. }
  13912. if (reexports) {
  13913. let starExport = null;
  13914. const namespaceReexports = [];
  13915. const namedReexports = [];
  13916. for (const specifier of reexports) {
  13917. if (specifier.reexported === '*') {
  13918. starExport = specifier;
  13919. }
  13920. else if (specifier.imported === '*') {
  13921. namespaceReexports.push(specifier);
  13922. }
  13923. else {
  13924. namedReexports.push(specifier);
  13925. }
  13926. }
  13927. if (starExport) {
  13928. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  13929. }
  13930. if (namespaceReexports.length > 0) {
  13931. if (!imports ||
  13932. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  13933. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  13934. }
  13935. for (const specifier of namespaceReexports) {
  13936. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  13937. }
  13938. }
  13939. if (namedReexports.length > 0) {
  13940. importBlock.push(`export${_}{${_}${namedReexports
  13941. .map(specifier => specifier.imported === specifier.reexported
  13942. ? specifier.imported
  13943. : `${specifier.imported} as ${specifier.reexported}`)
  13944. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  13945. }
  13946. }
  13947. }
  13948. return importBlock;
  13949. }
  13950. function getExportBlock(exports, { _, cnst }) {
  13951. const exportBlock = [];
  13952. const exportDeclaration = [];
  13953. for (const specifier of exports) {
  13954. if (specifier.expression) {
  13955. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  13956. }
  13957. exportDeclaration.push(specifier.exported === specifier.local
  13958. ? specifier.local
  13959. : `${specifier.local} as ${specifier.exported}`);
  13960. }
  13961. if (exportDeclaration.length > 0) {
  13962. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  13963. }
  13964. return exportBlock;
  13965. }
  13966. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  13967. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
  13968. const parts = name.split('.');
  13969. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  13970. parts.pop();
  13971. let propertyPath = root;
  13972. return (parts
  13973. .map(part => {
  13974. propertyPath += getPropertyAccess(part);
  13975. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  13976. })
  13977. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  13978. }
  13979. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
  13980. const parts = deepName.split('.');
  13981. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  13982. const last = parts.pop();
  13983. let propertyPath = root;
  13984. let deepAssignment = [
  13985. ...parts.map(part => {
  13986. propertyPath += getPropertyAccess(part);
  13987. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  13988. }),
  13989. `${propertyPath}${getPropertyAccess(last)}`
  13990. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  13991. if (parts.length > 0) {
  13992. deepAssignment = `(${deepAssignment})`;
  13993. }
  13994. return deepAssignment;
  13995. }
  13996. function trimEmptyImports(dependencies) {
  13997. let index = dependencies.length;
  13998. while (index--) {
  13999. const { imports, reexports } = dependencies[index];
  14000. if (imports || reexports) {
  14001. return dependencies.slice(0, index + 1);
  14002. }
  14003. }
  14004. return [];
  14005. }
  14006. function iife(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, namedExportsMode, outro, snippets, onwarn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  14007. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  14008. const isNamespaced = name && name.includes('.');
  14009. const useVariableAssignment = !extend && !isNamespaced;
  14010. if (name && useVariableAssignment && !isLegal(name)) {
  14011. return error(errorIllegalIdentifierAsName(name));
  14012. }
  14013. warnOnBuiltins(onwarn, dependencies);
  14014. const external = trimEmptyImports(dependencies);
  14015. const deps = external.map(dep => dep.globalName || 'null');
  14016. const parameters = external.map(m => m.name);
  14017. if (hasExports && !name) {
  14018. onwarn(errorMissingNameOptionForIifeExport());
  14019. }
  14020. if (namedExportsMode && hasExports) {
  14021. if (extend) {
  14022. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  14023. parameters.unshift('exports');
  14024. }
  14025. else {
  14026. deps.unshift('{}');
  14027. parameters.unshift('exports');
  14028. }
  14029. }
  14030. const useStrict = strict ? `${t}'use strict';${n}` : '';
  14031. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  14032. magicString.prepend(`${intro}${interopBlock}`);
  14033. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  14034. isAsync: false,
  14035. name: null
  14036. })}{${n}${useStrict}${n}`;
  14037. if (hasExports) {
  14038. if (name && !(extend && namedExportsMode)) {
  14039. wrapperIntro =
  14040. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  14041. `${_}=${_}${wrapperIntro}`;
  14042. }
  14043. if (isNamespaced) {
  14044. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
  14045. }
  14046. }
  14047. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  14048. if (hasExports && !extend && namedExportsMode) {
  14049. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  14050. }
  14051. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  14052. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets);
  14053. if (namespaceMarkers) {
  14054. namespaceMarkers = n + n + namespaceMarkers;
  14055. }
  14056. magicString
  14057. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  14058. .indent(t)
  14059. .prepend(wrapperIntro)
  14060. .append(wrapperOutro);
  14061. }
  14062. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
  14063. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  14064. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  14065. const registeredName = name ? `'${name}',${_}` : '';
  14066. const wrapperParameters = accessedGlobals.has('module')
  14067. ? ['exports', 'module']
  14068. : hasExports
  14069. ? ['exports']
  14070. : [];
  14071. // factory function should be wrapped by parentheses to avoid lazy parsing,
  14072. // cf. https://v8.dev/blog/preparser#pife
  14073. let wrapperStart = `System.register(${registeredName}[` +
  14074. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  14075. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  14076. isAsync: false,
  14077. name: null
  14078. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  14079. getStarExcludesBlock(starExcludes, t, snippets) +
  14080. getImportBindingsBlock(importBindings, t, snippets) +
  14081. `${n}${t}return${_}{${setters.length > 0
  14082. ? `${n}${t}${t}setters:${_}[${setters
  14083. .map(setter => setter
  14084. ? `${getFunctionIntro(['module'], {
  14085. isAsync: false,
  14086. name: null
  14087. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  14088. : systemNullSetters
  14089. ? `null`
  14090. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  14091. .join(`,${_}`)}],`
  14092. : ''}${n}`;
  14093. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  14094. isAsync: usesTopLevelAwait,
  14095. name: null
  14096. })}{${n}${n}`;
  14097. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  14098. magicString
  14099. .prepend(intro +
  14100. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
  14101. getHoistedExportsBlock(exports, t, snippets))
  14102. .append(`${outro}${n}${n}` +
  14103. getSyntheticExportsBlock(exports, t, snippets) +
  14104. getMissingExportsBlock(exports, t, snippets))
  14105. .indent(`${t}${t}${t}`)
  14106. .append(wrapperEnd)
  14107. .prepend(wrapperStart);
  14108. }
  14109. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  14110. const importBindings = [];
  14111. const setters = [];
  14112. let starExcludes = null;
  14113. for (const { imports, reexports } of dependencies) {
  14114. const setter = [];
  14115. if (imports) {
  14116. for (const specifier of imports) {
  14117. importBindings.push(specifier.local);
  14118. if (specifier.imported === '*') {
  14119. setter.push(`${specifier.local}${_}=${_}module;`);
  14120. }
  14121. else {
  14122. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  14123. }
  14124. }
  14125. }
  14126. if (reexports) {
  14127. const reexportedNames = [];
  14128. let hasStarReexport = false;
  14129. for (const { imported, reexported } of reexports) {
  14130. if (reexported === '*') {
  14131. hasStarReexport = true;
  14132. }
  14133. else {
  14134. reexportedNames.push([
  14135. reexported,
  14136. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  14137. ]);
  14138. }
  14139. }
  14140. if (reexportedNames.length > 1 || hasStarReexport) {
  14141. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  14142. if (hasStarReexport) {
  14143. if (!starExcludes) {
  14144. starExcludes = getStarExcludes({ dependencies, exports });
  14145. }
  14146. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  14147. }
  14148. else {
  14149. setter.push(`exports(${exportMapping});`);
  14150. }
  14151. }
  14152. else {
  14153. const [key, value] = reexportedNames[0];
  14154. setter.push(`exports('${key}',${_}${value});`);
  14155. }
  14156. }
  14157. setters.push(setter.join(`${n}${t}${t}${t}`));
  14158. }
  14159. return { importBindings, setters, starExcludes };
  14160. }
  14161. const getStarExcludes = ({ dependencies, exports }) => {
  14162. const starExcludes = new Set(exports.map(expt => expt.exported));
  14163. starExcludes.add('default');
  14164. for (const { reexports } of dependencies) {
  14165. if (reexports) {
  14166. for (const reexport of reexports) {
  14167. if (reexport.reexported !== '*')
  14168. starExcludes.add(reexport.reexported);
  14169. }
  14170. }
  14171. }
  14172. return starExcludes;
  14173. };
  14174. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
  14175. ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(property => [property, '1']), { lineBreakIndent: { base: t, t } })};`
  14176. : '';
  14177. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  14178. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  14179. function getExportsBlock(exports, t, { _, n }) {
  14180. if (exports.length === 0) {
  14181. return '';
  14182. }
  14183. if (exports.length === 1) {
  14184. return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  14185. }
  14186. return (`exports({${n}` +
  14187. exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
  14188. `${n}});${n}${n}`);
  14189. }
  14190. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  14191. .filter(expt => expt.expression)
  14192. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  14193. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  14194. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  14195. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  14196. function globalProperty(name, globalVariable, getPropertyAccess) {
  14197. if (!name)
  14198. return 'null';
  14199. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  14200. }
  14201. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  14202. let propertyPath = globalVariable;
  14203. return name
  14204. .split('.')
  14205. .map(part => (propertyPath += getPropertyAccess(part)))
  14206. .join(`${_}&&${_}`);
  14207. }
  14208. function umd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, outro, snippets, onwarn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
  14209. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  14210. const factoryVariable = compact ? 'f' : 'factory';
  14211. const globalVariable = compact ? 'g' : 'global';
  14212. if (hasExports && !name) {
  14213. return error(errorMissingNameOptionForUmdExport());
  14214. }
  14215. warnOnBuiltins(onwarn, dependencies);
  14216. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  14217. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  14218. const trimmedImports = trimEmptyImports(dependencies);
  14219. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  14220. const factoryParameters = trimmedImports.map(m => m.name);
  14221. if (namedExportsMode && (hasExports || noConflict)) {
  14222. amdDeps.unshift(`'exports'`);
  14223. cjsDeps.unshift(`exports`);
  14224. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
  14225. factoryParameters.unshift('exports');
  14226. }
  14227. const completeAmdId = getCompleteAmdId(amd, id);
  14228. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  14229. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  14230. const define = amd.define;
  14231. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  14232. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  14233. let iifeExport;
  14234. if (noConflict) {
  14235. const noConflictExportsVariable = compact ? 'e' : 'exports';
  14236. let factory;
  14237. if (!namedExportsMode && hasExports) {
  14238. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets)};`;
  14239. }
  14240. else {
  14241. const module = globalDeps.shift();
  14242. factory =
  14243. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  14244. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  14245. }
  14246. iifeExport =
  14247. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  14248. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  14249. `${t}${t}${factory}${n}` +
  14250. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  14251. isAsync: false,
  14252. name: null
  14253. })}{${_}` +
  14254. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  14255. `${t}})()`;
  14256. }
  14257. else {
  14258. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  14259. if (!namedExportsMode && hasExports) {
  14260. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets);
  14261. }
  14262. }
  14263. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  14264. const wrapperParameters = [factoryVariable];
  14265. if (iifeNeedsGlobal) {
  14266. wrapperParameters.unshift(globalVariable);
  14267. }
  14268. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  14269. const iifeStart = iifeNeedsGlobal
  14270. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  14271. : '';
  14272. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  14273. const cjsIntro = iifeNeedsGlobal
  14274. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  14275. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  14276. : '';
  14277. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  14278. cjsIntro +
  14279. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  14280. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  14281. // factory function should be wrapped by parentheses to avoid lazy parsing,
  14282. // cf. https://v8.dev/blog/preparser#pife
  14283. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  14284. isAsync: false,
  14285. name: null
  14286. })}{${useStrict}${n}`;
  14287. const wrapperOutro = n + n + '}));';
  14288. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  14289. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  14290. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets);
  14291. if (namespaceMarkers) {
  14292. namespaceMarkers = n + n + namespaceMarkers;
  14293. }
  14294. magicString
  14295. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  14296. .trim()
  14297. .indent(t)
  14298. .append(wrapperOutro)
  14299. .prepend(wrapperIntro);
  14300. }
  14301. const finalisers = { amd, cjs, es, iife, system, umd };
  14302. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  14303. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  14304. async function createAddons(options, outputPluginDriver, chunk) {
  14305. try {
  14306. let [banner, footer, intro, outro] = await Promise.all([
  14307. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  14308. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  14309. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  14310. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  14311. ]);
  14312. if (intro)
  14313. intro += '\n\n';
  14314. if (outro)
  14315. outro = `\n\n${outro}`;
  14316. if (banner)
  14317. banner += '\n';
  14318. if (footer)
  14319. footer = '\n' + footer;
  14320. return { banner, footer, intro, outro };
  14321. }
  14322. catch (error_) {
  14323. return error(errorAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  14324. }
  14325. }
  14326. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  14327. amd: deconflictImportsOther,
  14328. cjs: deconflictImportsOther,
  14329. es: deconflictImportsEsmOrSystem,
  14330. iife: deconflictImportsOther,
  14331. system: deconflictImportsEsmOrSystem,
  14332. umd: deconflictImportsOther
  14333. };
  14334. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  14335. const reversedModules = [...modules].reverse();
  14336. for (const module of reversedModules) {
  14337. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  14338. }
  14339. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  14340. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  14341. for (const module of reversedModules) {
  14342. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  14343. }
  14344. }
  14345. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  14346. // This is needed for namespace reexports
  14347. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  14348. if (preserveModules || dependency instanceof ExternalChunk) {
  14349. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  14350. }
  14351. }
  14352. for (const variable of imports) {
  14353. const module = variable.module;
  14354. const name = variable.name;
  14355. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  14356. variable.setRenderNames(null, (module instanceof ExternalModule
  14357. ? externalChunkByModule.get(module)
  14358. : chunkByModule.get(module)).variableName);
  14359. }
  14360. else if (module instanceof ExternalModule && name === 'default') {
  14361. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  14362. ? module.suggestedVariableName + '__default'
  14363. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  14364. }
  14365. else {
  14366. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  14367. }
  14368. }
  14369. for (const variable of syntheticExports) {
  14370. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  14371. }
  14372. }
  14373. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  14374. for (const chunk of dependencies) {
  14375. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  14376. }
  14377. for (const chunk of deconflictedNamespace) {
  14378. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  14379. }
  14380. for (const externalModule of deconflictedDefault) {
  14381. externalModule.defaultVariableName =
  14382. deconflictedNamespace.has(externalModule) &&
  14383. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  14384. ? externalModule.namespaceVariableName
  14385. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  14386. }
  14387. for (const variable of imports) {
  14388. const module = variable.module;
  14389. if (module instanceof ExternalModule) {
  14390. const chunk = externalChunkByModule.get(module);
  14391. const name = variable.name;
  14392. if (name === 'default') {
  14393. const moduleInterop = interop(module.id);
  14394. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  14395. ? chunk.defaultVariableName
  14396. : chunk.variableName;
  14397. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  14398. variable.setRenderNames(variableName, 'default');
  14399. }
  14400. else {
  14401. variable.setRenderNames(null, variableName);
  14402. }
  14403. }
  14404. else if (name === '*') {
  14405. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  14406. ? chunk.namespaceVariableName
  14407. : chunk.variableName);
  14408. }
  14409. else {
  14410. // if the second parameter is `null`, it uses its "name" for the property name
  14411. variable.setRenderNames(chunk.variableName, null);
  14412. }
  14413. }
  14414. else {
  14415. const chunk = chunkByModule.get(module);
  14416. if (preserveModules && variable.isNamespace) {
  14417. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  14418. }
  14419. else if (chunk.exportMode === 'default') {
  14420. variable.setRenderNames(null, chunk.variableName);
  14421. }
  14422. else {
  14423. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  14424. }
  14425. }
  14426. }
  14427. }
  14428. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  14429. for (const module of modules) {
  14430. for (const variable of module.scope.variables.values()) {
  14431. if (variable.included &&
  14432. // this will only happen for exports in some formats
  14433. !(variable.renderBaseName ||
  14434. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  14435. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  14436. }
  14437. }
  14438. if (includedNamespaces.has(module)) {
  14439. const namespace = module.namespace;
  14440. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  14441. }
  14442. }
  14443. }
  14444. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  14445. let nameIndex = 0;
  14446. for (const variable of exports) {
  14447. let [exportName] = variable.name;
  14448. if (exportsByName.has(exportName)) {
  14449. do {
  14450. exportName = toBase64(++nameIndex);
  14451. // skip past leading number identifiers
  14452. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  14453. nameIndex += 9 * 64 ** (exportName.length - 1);
  14454. exportName = toBase64(nameIndex);
  14455. }
  14456. } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
  14457. }
  14458. exportsByName.set(exportName, variable);
  14459. exportNamesByVariable.set(variable, [exportName]);
  14460. }
  14461. }
  14462. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  14463. for (const variable of exports) {
  14464. let nameIndex = 0;
  14465. let exportName = variable.name;
  14466. while (exportsByName.has(exportName)) {
  14467. exportName = variable.name + '$' + ++nameIndex;
  14468. }
  14469. exportsByName.set(exportName, variable);
  14470. exportNamesByVariable.set(variable, [exportName]);
  14471. }
  14472. }
  14473. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, warn) {
  14474. const exportKeys = chunk.getExportNames();
  14475. if (exportMode === 'default') {
  14476. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  14477. return error(errorIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  14478. }
  14479. }
  14480. else if (exportMode === 'none' && exportKeys.length > 0) {
  14481. return error(errorIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  14482. }
  14483. if (exportMode === 'auto') {
  14484. if (exportKeys.length === 0) {
  14485. exportMode = 'none';
  14486. }
  14487. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  14488. exportMode = 'default';
  14489. }
  14490. else {
  14491. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  14492. warn(errorMixedExport(facadeModuleId, name));
  14493. }
  14494. exportMode = 'named';
  14495. }
  14496. }
  14497. return exportMode;
  14498. }
  14499. function guessIndentString(code) {
  14500. const lines = code.split('\n');
  14501. const tabbed = lines.filter(line => /^\t+/.test(line));
  14502. const spaced = lines.filter(line => /^ {2,}/.test(line));
  14503. if (tabbed.length === 0 && spaced.length === 0) {
  14504. return null;
  14505. }
  14506. // More lines tabbed than spaced? Assume tabs, and
  14507. // default to tabs in the case of a tie (or nothing
  14508. // to go on)
  14509. if (tabbed.length >= spaced.length) {
  14510. return '\t';
  14511. }
  14512. // Otherwise, we need to guess the multiple
  14513. const min = spaced.reduce((previous, current) => {
  14514. const numberSpaces = /^ +/.exec(current)[0].length;
  14515. return Math.min(numberSpaces, previous);
  14516. }, Infinity);
  14517. return ' '.repeat(min);
  14518. }
  14519. function getIndentString(modules, options) {
  14520. if (options.indent !== true)
  14521. return options.indent;
  14522. for (const module of modules) {
  14523. const indent = guessIndentString(module.originalCode);
  14524. if (indent !== null)
  14525. return indent;
  14526. }
  14527. return '\t';
  14528. }
  14529. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  14530. const staticDependencyBlocks = [];
  14531. const handledDependencies = new Set();
  14532. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  14533. const module = orderedModules[modulePos];
  14534. if (!handledDependencies.has(module)) {
  14535. const staticDependencies = [];
  14536. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  14537. staticDependencyBlocks.unshift(staticDependencies);
  14538. }
  14539. }
  14540. const dependencies = new Set();
  14541. for (const block of staticDependencyBlocks) {
  14542. for (const dependency of block) {
  14543. dependencies.add(dependency);
  14544. }
  14545. }
  14546. return dependencies;
  14547. }
  14548. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  14549. const dependencies = module.getDependenciesToBeIncluded();
  14550. for (const dependency of dependencies) {
  14551. if (dependency instanceof ExternalModule) {
  14552. staticDependencies.push(externalChunkByModule.get(dependency));
  14553. continue;
  14554. }
  14555. const dependencyChunk = chunkByModule.get(dependency);
  14556. if (dependencyChunk !== chunk) {
  14557. staticDependencies.push(dependencyChunk);
  14558. continue;
  14559. }
  14560. if (!handledModules.has(dependency)) {
  14561. handledModules.add(dependency);
  14562. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  14563. }
  14564. }
  14565. }
  14566. // Four random characters from the private use area to minimize risk of conflicts
  14567. const hashPlaceholderLeft = '!~{';
  14568. const hashPlaceholderRight = '}~';
  14569. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  14570. // This is the size of a sha256
  14571. const maxHashSize = 64;
  14572. const defaultHashSize = 8;
  14573. const getHashPlaceholderGenerator = () => {
  14574. let nextIndex = 0;
  14575. return (optionName, hashSize = defaultHashSize) => {
  14576. if (hashSize > maxHashSize) {
  14577. return error(errorFailedValidation(`Hashes cannot be longer than ${maxHashSize} characters, received ${hashSize}. Check the "${optionName}" option.`));
  14578. }
  14579. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  14580. if (placeholder.length > hashSize) {
  14581. return error(errorFailedValidation(`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.`));
  14582. }
  14583. return placeholder;
  14584. };
  14585. };
  14586. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${maxHashSize - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  14587. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  14588. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  14589. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  14590. const containedPlaceholders = new Set();
  14591. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  14592. if (placeholders.has(placeholder)) {
  14593. containedPlaceholders.add(placeholder);
  14594. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  14595. }
  14596. return placeholder;
  14597. });
  14598. return { containedPlaceholders, transformedCode };
  14599. };
  14600. const lowercaseBundleKeys = Symbol('bundleKeys');
  14601. const FILE_PLACEHOLDER = {
  14602. type: 'placeholder'
  14603. };
  14604. const getOutputBundle = (outputBundleBase) => {
  14605. const reservedLowercaseBundleKeys = new Set();
  14606. return new Proxy(outputBundleBase, {
  14607. deleteProperty(target, key) {
  14608. if (typeof key === 'string') {
  14609. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  14610. }
  14611. return Reflect.deleteProperty(target, key);
  14612. },
  14613. get(target, key) {
  14614. if (key === lowercaseBundleKeys) {
  14615. return reservedLowercaseBundleKeys;
  14616. }
  14617. return Reflect.get(target, key);
  14618. },
  14619. set(target, key, value) {
  14620. if (typeof key === 'string') {
  14621. reservedLowercaseBundleKeys.add(key.toLowerCase());
  14622. }
  14623. return Reflect.set(target, key, value);
  14624. }
  14625. });
  14626. };
  14627. const removeUnreferencedAssets = (outputBundle) => {
  14628. const unreferencedAssets = new Set();
  14629. const bundleEntries = Object.values(outputBundle);
  14630. for (const asset of bundleEntries) {
  14631. asset.type === 'asset' && asset.needsCodeReference && unreferencedAssets.add(asset.fileName);
  14632. }
  14633. for (const chunk of bundleEntries) {
  14634. if (chunk.type === 'chunk') {
  14635. for (const referencedFile of chunk.referencedFiles) {
  14636. unreferencedAssets.has(referencedFile) && unreferencedAssets.delete(referencedFile);
  14637. }
  14638. }
  14639. }
  14640. for (const file of unreferencedAssets) {
  14641. delete outputBundle[file];
  14642. }
  14643. };
  14644. function renderNamePattern(pattern, patternName, replacements) {
  14645. if (isPathFragment(pattern))
  14646. return error(errorFailedValidation(`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.`));
  14647. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  14648. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  14649. return error(errorFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  14650. }
  14651. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  14652. if (isPathFragment(replacement))
  14653. return error(errorFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  14654. return replacement;
  14655. });
  14656. }
  14657. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  14658. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  14659. return name;
  14660. const extension = node_path.extname(name);
  14661. name = name.slice(0, Math.max(0, name.length - extension.length));
  14662. let uniqueName, uniqueIndex = 1;
  14663. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  14664. ;
  14665. return uniqueName;
  14666. }
  14667. const NON_ASSET_EXTENSIONS = new Set([
  14668. '.js',
  14669. '.jsx',
  14670. '.ts',
  14671. '.tsx',
  14672. '.mjs',
  14673. '.mts',
  14674. '.cjs',
  14675. '.cts'
  14676. ]);
  14677. function getGlobalName(chunk, globals, hasExports, warn) {
  14678. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  14679. if (globalName) {
  14680. return globalName;
  14681. }
  14682. if (hasExports) {
  14683. warn(errorMissingGlobalName(chunk.id, chunk.variableName));
  14684. return chunk.variableName;
  14685. }
  14686. }
  14687. class Chunk {
  14688. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  14689. this.orderedModules = orderedModules;
  14690. this.inputOptions = inputOptions;
  14691. this.outputOptions = outputOptions;
  14692. this.unsetOptions = unsetOptions;
  14693. this.pluginDriver = pluginDriver;
  14694. this.modulesById = modulesById;
  14695. this.chunkByModule = chunkByModule;
  14696. this.externalChunkByModule = externalChunkByModule;
  14697. this.facadeChunkByModule = facadeChunkByModule;
  14698. this.includedNamespaces = includedNamespaces;
  14699. this.manualChunkAlias = manualChunkAlias;
  14700. this.getPlaceholder = getPlaceholder;
  14701. this.bundle = bundle;
  14702. this.inputBase = inputBase;
  14703. this.snippets = snippets;
  14704. this.entryModules = [];
  14705. this.exportMode = 'named';
  14706. this.facadeModule = null;
  14707. this.namespaceVariableName = '';
  14708. this.variableName = '';
  14709. this.accessedGlobalsByScope = new Map();
  14710. this.dependencies = new Set();
  14711. this.dynamicEntryModules = [];
  14712. this.dynamicName = null;
  14713. this.exportNamesByVariable = new Map();
  14714. this.exports = new Set();
  14715. this.exportsByName = new Map();
  14716. this.fileName = null;
  14717. this.implicitEntryModules = [];
  14718. this.implicitlyLoadedBefore = new Set();
  14719. this.imports = new Set();
  14720. this.includedDynamicImports = null;
  14721. this.includedReexportsByModule = new Map();
  14722. // This may be updated in the constructor
  14723. this.isEmpty = true;
  14724. this.name = null;
  14725. this.needsExportsShim = false;
  14726. this.preRenderedChunkInfo = null;
  14727. this.preliminaryFileName = null;
  14728. this.renderedChunkInfo = null;
  14729. this.renderedDependencies = null;
  14730. this.renderedModules = Object.create(null);
  14731. this.sortedExportNames = null;
  14732. this.strictFacade = false;
  14733. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  14734. const chunkModules = new Set(orderedModules);
  14735. for (const module of orderedModules) {
  14736. chunkByModule.set(module, this);
  14737. if (module.namespace.included) {
  14738. includedNamespaces.add(module);
  14739. }
  14740. if (this.isEmpty && module.isIncluded()) {
  14741. this.isEmpty = false;
  14742. }
  14743. if (module.info.isEntry || outputOptions.preserveModules) {
  14744. this.entryModules.push(module);
  14745. }
  14746. for (const importer of module.includedDynamicImporters) {
  14747. if (!chunkModules.has(importer)) {
  14748. this.dynamicEntryModules.push(module);
  14749. // Modules with synthetic exports need an artificial namespace for dynamic imports
  14750. if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
  14751. includedNamespaces.add(module);
  14752. this.exports.add(module.namespace);
  14753. }
  14754. }
  14755. }
  14756. if (module.implicitlyLoadedAfter.size > 0) {
  14757. this.implicitEntryModules.push(module);
  14758. }
  14759. }
  14760. this.suggestedVariableName = makeLegal(this.generateVariableName());
  14761. }
  14762. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  14763. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  14764. chunk.assignFacadeName(facadeName, facadedModule);
  14765. if (!facadeChunkByModule.has(facadedModule)) {
  14766. facadeChunkByModule.set(facadedModule, chunk);
  14767. }
  14768. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  14769. chunk.dependencies.add(dependency instanceof Module
  14770. ? chunkByModule.get(dependency)
  14771. : externalChunkByModule.get(dependency));
  14772. }
  14773. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  14774. facadedModule.info.moduleSideEffects &&
  14775. facadedModule.hasEffects()) {
  14776. chunk.dependencies.add(chunkByModule.get(facadedModule));
  14777. }
  14778. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  14779. chunk.facadeModule = facadedModule;
  14780. chunk.strictFacade = true;
  14781. return chunk;
  14782. }
  14783. canModuleBeFacade(module, exposedVariables) {
  14784. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  14785. for (const exposedVariable of this.exports) {
  14786. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  14787. return false;
  14788. }
  14789. }
  14790. for (const exposedVariable of exposedVariables) {
  14791. if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
  14792. return false;
  14793. }
  14794. }
  14795. return true;
  14796. }
  14797. finalizeChunk(code, map, hashesByPlaceholder) {
  14798. const renderedChunkInfo = this.getRenderedChunkInfo();
  14799. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  14800. const fileName = (this.fileName = finalize(renderedChunkInfo.fileName));
  14801. return {
  14802. ...renderedChunkInfo,
  14803. code,
  14804. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  14805. fileName,
  14806. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  14807. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  14808. finalize(fileName),
  14809. bindings
  14810. ])),
  14811. imports: renderedChunkInfo.imports.map(finalize),
  14812. map,
  14813. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize)
  14814. };
  14815. }
  14816. generateExports() {
  14817. this.sortedExportNames = null;
  14818. const remainingExports = new Set(this.exports);
  14819. if (this.facadeModule !== null &&
  14820. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  14821. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  14822. for (const [variable, exportNames] of exportNamesByVariable) {
  14823. this.exportNamesByVariable.set(variable, [...exportNames]);
  14824. for (const exportName of exportNames) {
  14825. this.exportsByName.set(exportName, variable);
  14826. }
  14827. remainingExports.delete(variable);
  14828. }
  14829. }
  14830. if (this.outputOptions.minifyInternalExports) {
  14831. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  14832. }
  14833. else {
  14834. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  14835. }
  14836. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  14837. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onwarn);
  14838. }
  14839. generateFacades() {
  14840. const facades = [];
  14841. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  14842. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  14843. for (const module of entryModules) {
  14844. if (module.preserveSignature) {
  14845. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  14846. exposedVariables.add(exportedVariable);
  14847. }
  14848. }
  14849. }
  14850. for (const module of entryModules) {
  14851. // eslint-disable-next-line unicorn/prefer-spread
  14852. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  14853. // mapping must run after Set 'name' dedupe
  14854. name => ({
  14855. name
  14856. }));
  14857. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  14858. requiredFacades.push({});
  14859. }
  14860. // eslint-disable-next-line unicorn/prefer-spread
  14861. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  14862. if (requiredFacades.length === 0) {
  14863. requiredFacades.push({});
  14864. }
  14865. if (!this.facadeModule) {
  14866. const needsStrictFacade = module.preserveSignature === 'strict' ||
  14867. (module.preserveSignature === 'exports-only' &&
  14868. module.getExportNamesByVariable().size > 0);
  14869. if (!needsStrictFacade ||
  14870. this.outputOptions.preserveModules ||
  14871. this.canModuleBeFacade(module, exposedVariables)) {
  14872. this.facadeModule = module;
  14873. this.facadeChunkByModule.set(module, this);
  14874. if (module.preserveSignature) {
  14875. this.strictFacade = needsStrictFacade;
  14876. }
  14877. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  14878. }
  14879. }
  14880. for (const facadeName of requiredFacades) {
  14881. 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));
  14882. }
  14883. }
  14884. for (const module of this.dynamicEntryModules) {
  14885. if (module.info.syntheticNamedExports)
  14886. continue;
  14887. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  14888. this.facadeModule = module;
  14889. this.facadeChunkByModule.set(module, this);
  14890. this.strictFacade = true;
  14891. this.dynamicName = getChunkNameFromModule(module);
  14892. }
  14893. else if (this.facadeModule === module &&
  14894. !this.strictFacade &&
  14895. this.canModuleBeFacade(module, exposedVariables)) {
  14896. this.strictFacade = true;
  14897. }
  14898. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  14899. this.includedNamespaces.add(module);
  14900. this.exports.add(module.namespace);
  14901. }
  14902. }
  14903. if (!this.outputOptions.preserveModules) {
  14904. this.addNecessaryImportsForFacades();
  14905. }
  14906. return facades;
  14907. }
  14908. getChunkName() {
  14909. return (this.name ?? (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  14910. }
  14911. getExportNames() {
  14912. return (this.sortedExportNames ?? (this.sortedExportNames = [...this.exportsByName.keys()].sort()));
  14913. }
  14914. getFileName() {
  14915. return this.fileName || this.getPreliminaryFileName().fileName;
  14916. }
  14917. getImportPath(importer) {
  14918. return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  14919. }
  14920. getPreliminaryFileName() {
  14921. if (this.preliminaryFileName) {
  14922. return this.preliminaryFileName;
  14923. }
  14924. let fileName;
  14925. let hashPlaceholder = null;
  14926. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  14927. if (file) {
  14928. fileName = node_path.basename(file);
  14929. }
  14930. else if (this.fileName === null) {
  14931. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  14932. ? [entryFileNames, 'output.entryFileNames']
  14933. : [chunkFileNames, 'output.chunkFileNames'];
  14934. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  14935. format: () => format,
  14936. hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)),
  14937. name: () => this.getChunkName()
  14938. });
  14939. if (!hashPlaceholder) {
  14940. fileName = makeUnique(fileName, this.bundle);
  14941. }
  14942. }
  14943. else {
  14944. fileName = this.fileName;
  14945. }
  14946. if (!hashPlaceholder) {
  14947. this.bundle[fileName] = FILE_PLACEHOLDER;
  14948. }
  14949. // Caching is essential to not conflict with the file name reservation above
  14950. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  14951. }
  14952. getRenderedChunkInfo() {
  14953. if (this.renderedChunkInfo) {
  14954. return this.renderedChunkInfo;
  14955. }
  14956. return (this.renderedChunkInfo = {
  14957. ...this.getPreRenderedChunkInfo(),
  14958. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  14959. fileName: this.getFileName(),
  14960. // eslint-disable-next-line unicorn/prefer-spread
  14961. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  14962. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  14963. // eslint-disable-next-line unicorn/prefer-spread
  14964. imports: Array.from(this.dependencies, resolveFileName),
  14965. modules: this.renderedModules,
  14966. referencedFiles: this.getReferencedFiles()
  14967. });
  14968. }
  14969. getVariableExportName(variable) {
  14970. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  14971. return '*';
  14972. }
  14973. return this.exportNamesByVariable.get(variable)[0];
  14974. }
  14975. link() {
  14976. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  14977. for (const module of this.orderedModules) {
  14978. this.addImplicitlyLoadedBeforeFromModule(module);
  14979. this.setUpChunkImportsAndExportsForModule(module);
  14980. }
  14981. }
  14982. async render() {
  14983. const { dependencies, exportMode, facadeModule, inputOptions: { onwarn }, outputOptions, pluginDriver, snippets } = this;
  14984. const { format, hoistTransitiveImports, preserveModules } = outputOptions;
  14985. // for static and dynamic entry points, add transitive dependencies to this
  14986. // chunk's dependencies to avoid loading latency
  14987. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  14988. for (const dep of dependencies) {
  14989. if (dep instanceof Chunk)
  14990. this.inlineChunkDependencies(dep);
  14991. }
  14992. }
  14993. const preliminaryFileName = this.getPreliminaryFileName();
  14994. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  14995. const renderedDependencies = [...this.getRenderedDependencies().values()];
  14996. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  14997. let hasExports = renderedExports.length > 0;
  14998. let hasDefaultExport = false;
  14999. for (const renderedDependence of renderedDependencies) {
  15000. const { reexports } = renderedDependence;
  15001. if (reexports?.length) {
  15002. hasExports = true;
  15003. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  15004. hasDefaultExport = true;
  15005. }
  15006. if (format === 'es') {
  15007. renderedDependence.reexports = reexports.filter(
  15008. // eslint-disable-next-line unicorn/prefer-array-some
  15009. ({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  15010. }
  15011. }
  15012. }
  15013. if (!hasDefaultExport) {
  15014. for (const { exported } of renderedExports) {
  15015. if (exported === 'default') {
  15016. hasDefaultExport = true;
  15017. break;
  15018. }
  15019. }
  15020. }
  15021. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  15022. finalisers[format](renderedSource, {
  15023. accessedGlobals,
  15024. dependencies: renderedDependencies,
  15025. exports: renderedExports,
  15026. hasDefaultExport,
  15027. hasExports,
  15028. id: preliminaryFileName.fileName,
  15029. indent,
  15030. intro,
  15031. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  15032. isModuleFacade: facadeModule !== null,
  15033. namedExportsMode: exportMode !== 'default',
  15034. onwarn,
  15035. outro,
  15036. snippets,
  15037. usesTopLevelAwait
  15038. }, outputOptions);
  15039. if (banner)
  15040. magicString.prepend(banner);
  15041. if (footer)
  15042. magicString.append(footer);
  15043. return {
  15044. chunk: this,
  15045. magicString,
  15046. preliminaryFileName,
  15047. usedModules
  15048. };
  15049. }
  15050. addImplicitlyLoadedBeforeFromModule(baseModule) {
  15051. const { chunkByModule, implicitlyLoadedBefore } = this;
  15052. for (const module of baseModule.implicitlyLoadedBefore) {
  15053. const chunk = chunkByModule.get(module);
  15054. if (chunk && chunk !== this) {
  15055. implicitlyLoadedBefore.add(chunk);
  15056. }
  15057. }
  15058. }
  15059. addNecessaryImportsForFacades() {
  15060. for (const [module, variables] of this.includedReexportsByModule) {
  15061. if (this.includedNamespaces.has(module)) {
  15062. for (const variable of variables) {
  15063. this.imports.add(variable);
  15064. }
  15065. }
  15066. }
  15067. }
  15068. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  15069. if (fileName) {
  15070. this.fileName = fileName;
  15071. }
  15072. else {
  15073. this.name = this.outputOptions.sanitizeFileName(name ||
  15074. (preservePath
  15075. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  15076. : getChunkNameFromModule(facadedModule)));
  15077. }
  15078. }
  15079. checkCircularDependencyImport(variable, importingModule) {
  15080. const variableModule = variable.module;
  15081. if (variableModule instanceof Module) {
  15082. const exportChunk = this.chunkByModule.get(variableModule);
  15083. let alternativeReexportModule;
  15084. do {
  15085. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  15086. if (alternativeReexportModule) {
  15087. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  15088. if (exportingChunk !== exportChunk) {
  15089. this.inputOptions.onwarn(errorCyclicCrossChunkReexport(
  15090. // Namespaces do not have an export name
  15091. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  15092. }
  15093. importingModule = alternativeReexportModule;
  15094. }
  15095. } while (alternativeReexportModule);
  15096. }
  15097. }
  15098. ensureReexportsAreAvailableForModule(module) {
  15099. const includedReexports = [];
  15100. const map = module.getExportNamesByVariable();
  15101. for (const exportedVariable of map.keys()) {
  15102. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  15103. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  15104. this.checkCircularDependencyImport(importedVariable, module);
  15105. // When preserving modules, we do not create namespace objects but directly
  15106. // use the actual namespaces, which would be broken by this logic.
  15107. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  15108. const exportingModule = importedVariable.module;
  15109. if (exportingModule instanceof Module) {
  15110. const chunk = this.chunkByModule.get(exportingModule);
  15111. if (chunk && chunk !== this) {
  15112. chunk.exports.add(importedVariable);
  15113. includedReexports.push(importedVariable);
  15114. if (isSynthetic) {
  15115. this.imports.add(importedVariable);
  15116. }
  15117. }
  15118. }
  15119. }
  15120. }
  15121. if (includedReexports.length > 0) {
  15122. this.includedReexportsByModule.set(module, includedReexports);
  15123. }
  15124. }
  15125. generateVariableName() {
  15126. if (this.manualChunkAlias) {
  15127. return this.manualChunkAlias;
  15128. }
  15129. const moduleForNaming = this.entryModules[0] ||
  15130. this.implicitEntryModules[0] ||
  15131. this.dynamicEntryModules[0] ||
  15132. this.orderedModules[this.orderedModules.length - 1];
  15133. if (moduleForNaming) {
  15134. return getChunkNameFromModule(moduleForNaming);
  15135. }
  15136. return 'chunk';
  15137. }
  15138. getChunkExportDeclarations(format) {
  15139. const exports = [];
  15140. for (const exportName of this.getExportNames()) {
  15141. if (exportName[0] === '*')
  15142. continue;
  15143. const variable = this.exportsByName.get(exportName);
  15144. if (!(variable instanceof SyntheticNamedExportVariable)) {
  15145. const module = variable.module;
  15146. if (module) {
  15147. const chunk = this.chunkByModule.get(module);
  15148. if (chunk !== this) {
  15149. if (!chunk || format !== 'es') {
  15150. continue;
  15151. }
  15152. const chunkDep = this.renderedDependencies.get(chunk);
  15153. if (!chunkDep) {
  15154. continue;
  15155. }
  15156. const { imports, reexports } = chunkDep;
  15157. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  15158. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  15159. if (!isImported) {
  15160. continue;
  15161. }
  15162. }
  15163. }
  15164. }
  15165. let expression = null;
  15166. let hoisted = false;
  15167. let local = variable.getName(this.snippets.getPropertyAccess);
  15168. if (variable instanceof LocalVariable) {
  15169. for (const declaration of variable.declarations) {
  15170. if (declaration.parent instanceof FunctionDeclaration ||
  15171. (declaration instanceof ExportDefaultDeclaration &&
  15172. declaration.declaration instanceof FunctionDeclaration)) {
  15173. hoisted = true;
  15174. break;
  15175. }
  15176. }
  15177. }
  15178. else if (variable instanceof SyntheticNamedExportVariable) {
  15179. expression = local;
  15180. if (format === 'es') {
  15181. local = variable.renderName;
  15182. }
  15183. }
  15184. exports.push({
  15185. exported: exportName,
  15186. expression,
  15187. hoisted,
  15188. local
  15189. });
  15190. }
  15191. return exports;
  15192. }
  15193. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  15194. const dependencies = new Set();
  15195. const deconflictedDefault = new Set();
  15196. const deconflictedNamespace = new Set();
  15197. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  15198. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  15199. const module = variable.module;
  15200. if (module instanceof ExternalModule) {
  15201. const chunk = this.externalChunkByModule.get(module);
  15202. dependencies.add(chunk);
  15203. if (addNonNamespacesAndInteropHelpers) {
  15204. if (variable.name === 'default') {
  15205. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  15206. deconflictedDefault.add(chunk);
  15207. }
  15208. }
  15209. else if (variable.name === '*' &&
  15210. namespaceInteropHelpersByInteropType[interop(module.id)]) {
  15211. deconflictedNamespace.add(chunk);
  15212. }
  15213. }
  15214. }
  15215. else {
  15216. const chunk = this.chunkByModule.get(module);
  15217. if (chunk !== this) {
  15218. dependencies.add(chunk);
  15219. if (addNonNamespacesAndInteropHelpers &&
  15220. chunk.exportMode === 'default' &&
  15221. variable.isNamespace) {
  15222. deconflictedNamespace.add(chunk);
  15223. }
  15224. }
  15225. }
  15226. }
  15227. }
  15228. if (addDependenciesWithoutBindings) {
  15229. for (const dependency of this.dependencies) {
  15230. dependencies.add(dependency);
  15231. }
  15232. }
  15233. return { deconflictedDefault, deconflictedNamespace, dependencies };
  15234. }
  15235. getDynamicDependencies() {
  15236. return this.getIncludedDynamicImports()
  15237. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  15238. resolvedDynamicImport.chunk ||
  15239. resolvedDynamicImport.externalChunk ||
  15240. resolvedDynamicImport.resolution)
  15241. .filter((resolution) => resolution !== this &&
  15242. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  15243. }
  15244. getDynamicImportStringAndAssertions(resolution, fileName) {
  15245. if (resolution instanceof ExternalModule) {
  15246. const chunk = this.externalChunkByModule.get(resolution);
  15247. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAssertions(this.snippets)];
  15248. }
  15249. return [
  15250. resolution || '',
  15251. (this.outputOptions.format === 'es' && this.outputOptions.externalImportAssertions) || null
  15252. ];
  15253. }
  15254. getFallbackChunkName() {
  15255. if (this.manualChunkAlias) {
  15256. return this.manualChunkAlias;
  15257. }
  15258. if (this.dynamicName) {
  15259. return this.dynamicName;
  15260. }
  15261. if (this.fileName) {
  15262. return getAliasName(this.fileName);
  15263. }
  15264. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  15265. }
  15266. getImportSpecifiers() {
  15267. const { interop } = this.outputOptions;
  15268. const importsByDependency = new Map();
  15269. for (const variable of this.imports) {
  15270. const module = variable.module;
  15271. let dependency;
  15272. let imported;
  15273. if (module instanceof ExternalModule) {
  15274. dependency = this.externalChunkByModule.get(module);
  15275. imported = variable.name;
  15276. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  15277. return error(errorUnexpectedNamedImport(module.id, imported, false));
  15278. }
  15279. }
  15280. else {
  15281. dependency = this.chunkByModule.get(module);
  15282. imported = dependency.getVariableExportName(variable);
  15283. }
  15284. getOrCreate(importsByDependency, dependency, getNewArray).push({
  15285. imported,
  15286. local: variable.getName(this.snippets.getPropertyAccess)
  15287. });
  15288. }
  15289. return importsByDependency;
  15290. }
  15291. getIncludedDynamicImports() {
  15292. if (this.includedDynamicImports) {
  15293. return this.includedDynamicImports;
  15294. }
  15295. const includedDynamicImports = [];
  15296. for (const module of this.orderedModules) {
  15297. for (const { node, resolution } of module.dynamicImports) {
  15298. if (!node.included) {
  15299. continue;
  15300. }
  15301. includedDynamicImports.push(resolution instanceof Module
  15302. ? {
  15303. chunk: this.chunkByModule.get(resolution),
  15304. externalChunk: null,
  15305. facadeChunk: this.facadeChunkByModule.get(resolution),
  15306. node,
  15307. resolution
  15308. }
  15309. : resolution instanceof ExternalModule
  15310. ? {
  15311. chunk: null,
  15312. externalChunk: this.externalChunkByModule.get(resolution),
  15313. facadeChunk: null,
  15314. node,
  15315. resolution
  15316. }
  15317. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  15318. }
  15319. }
  15320. return (this.includedDynamicImports = includedDynamicImports);
  15321. }
  15322. getPreRenderedChunkInfo() {
  15323. if (this.preRenderedChunkInfo) {
  15324. return this.preRenderedChunkInfo;
  15325. }
  15326. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  15327. return (this.preRenderedChunkInfo = {
  15328. exports: this.getExportNames(),
  15329. facadeModuleId: facadeModule && facadeModule.id,
  15330. isDynamicEntry: dynamicEntryModules.length > 0,
  15331. isEntry: !!facadeModule?.info.isEntry,
  15332. isImplicitEntry: implicitEntryModules.length > 0,
  15333. moduleIds: orderedModules.map(({ id }) => id),
  15334. name: this.getChunkName(),
  15335. type: 'chunk'
  15336. });
  15337. }
  15338. getPreserveModulesChunkNameFromModule(module) {
  15339. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  15340. if (predefinedChunkName)
  15341. return predefinedChunkName;
  15342. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  15343. const sanitizedId = sanitizeFileName(normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  15344. const extensionName = node_path.extname(sanitizedId);
  15345. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  15346. ? sanitizedId.slice(0, -extensionName.length)
  15347. : sanitizedId;
  15348. if (isAbsolute(idWithoutExtension)) {
  15349. return preserveModulesRoot && node_path.resolve(idWithoutExtension).startsWith(preserveModulesRoot)
  15350. ? idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '')
  15351. : relative(this.inputBase, idWithoutExtension);
  15352. }
  15353. else {
  15354. return `_virtual/${node_path.basename(idWithoutExtension)}`;
  15355. }
  15356. }
  15357. getReexportSpecifiers() {
  15358. const { externalLiveBindings, interop } = this.outputOptions;
  15359. const reexportSpecifiers = new Map();
  15360. for (let exportName of this.getExportNames()) {
  15361. let dependency;
  15362. let imported;
  15363. let needsLiveBinding = false;
  15364. if (exportName[0] === '*') {
  15365. const id = exportName.slice(1);
  15366. if (interop(id) === 'defaultOnly') {
  15367. this.inputOptions.onwarn(errorUnexpectedNamespaceReexport(id));
  15368. }
  15369. needsLiveBinding = externalLiveBindings;
  15370. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  15371. imported = exportName = '*';
  15372. }
  15373. else {
  15374. const variable = this.exportsByName.get(exportName);
  15375. if (variable instanceof SyntheticNamedExportVariable)
  15376. continue;
  15377. const module = variable.module;
  15378. if (module instanceof Module) {
  15379. dependency = this.chunkByModule.get(module);
  15380. if (dependency === this)
  15381. continue;
  15382. imported = dependency.getVariableExportName(variable);
  15383. needsLiveBinding = variable.isReassigned;
  15384. }
  15385. else {
  15386. dependency = this.externalChunkByModule.get(module);
  15387. imported = variable.name;
  15388. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  15389. return error(errorUnexpectedNamedImport(module.id, imported, true));
  15390. }
  15391. needsLiveBinding =
  15392. externalLiveBindings &&
  15393. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  15394. }
  15395. }
  15396. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  15397. imported,
  15398. needsLiveBinding,
  15399. reexported: exportName
  15400. });
  15401. }
  15402. return reexportSpecifiers;
  15403. }
  15404. getReferencedFiles() {
  15405. const referencedFiles = new Set();
  15406. for (const module of this.orderedModules) {
  15407. for (const meta of module.importMetas) {
  15408. const fileName = meta.getReferencedFileName(this.pluginDriver);
  15409. if (fileName) {
  15410. referencedFiles.add(fileName);
  15411. }
  15412. }
  15413. }
  15414. return [...referencedFiles];
  15415. }
  15416. getRenderedDependencies() {
  15417. if (this.renderedDependencies) {
  15418. return this.renderedDependencies;
  15419. }
  15420. const importSpecifiers = this.getImportSpecifiers();
  15421. const reexportSpecifiers = this.getReexportSpecifiers();
  15422. const renderedDependencies = new Map();
  15423. const fileName = this.getFileName();
  15424. for (const dep of this.dependencies) {
  15425. const imports = importSpecifiers.get(dep) || null;
  15426. const reexports = reexportSpecifiers.get(dep) || null;
  15427. const namedExportsMode = dep instanceof ExternalChunk || dep.exportMode !== 'default';
  15428. const importPath = dep.getImportPath(fileName);
  15429. renderedDependencies.set(dep, {
  15430. assertions: dep instanceof ExternalChunk ? dep.getImportAssertions(this.snippets) : null,
  15431. defaultVariableName: dep.defaultVariableName,
  15432. globalName: dep instanceof ExternalChunk &&
  15433. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  15434. getGlobalName(dep, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onwarn),
  15435. importPath,
  15436. imports,
  15437. isChunk: dep instanceof Chunk,
  15438. name: dep.variableName,
  15439. namedExportsMode,
  15440. namespaceVariableName: dep.namespaceVariableName,
  15441. reexports
  15442. });
  15443. }
  15444. return (this.renderedDependencies = renderedDependencies);
  15445. }
  15446. inlineChunkDependencies(chunk) {
  15447. for (const dep of chunk.dependencies) {
  15448. if (this.dependencies.has(dep))
  15449. continue;
  15450. this.dependencies.add(dep);
  15451. if (dep instanceof Chunk) {
  15452. this.inlineChunkDependencies(dep);
  15453. }
  15454. }
  15455. }
  15456. // This method changes properties on the AST before rendering and must not be async
  15457. renderModules(fileName) {
  15458. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onwarn }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  15459. const { compact, dynamicImportFunction, format, freeze, namespaceToStringTag, preserveModules } = outputOptions;
  15460. const { _, cnst, n } = snippets;
  15461. this.setDynamicImportResolutions(fileName);
  15462. this.setImportMetaResolutions(fileName);
  15463. this.setIdentifierRenderResolutions();
  15464. const magicString = new Bundle$1({ separator: `${n}${n}` });
  15465. const indent = getIndentString(orderedModules, outputOptions);
  15466. const usedModules = [];
  15467. let hoistedSource = '';
  15468. const accessedGlobals = new Set();
  15469. const renderedModuleSources = new Map();
  15470. const renderOptions = {
  15471. dynamicImportFunction,
  15472. exportNamesByVariable,
  15473. format,
  15474. freeze,
  15475. indent,
  15476. namespaceToStringTag,
  15477. pluginDriver,
  15478. snippets,
  15479. useOriginalName: null
  15480. };
  15481. let usesTopLevelAwait = false;
  15482. for (const module of orderedModules) {
  15483. let renderedLength = 0;
  15484. let source;
  15485. if (module.isIncluded() || includedNamespaces.has(module)) {
  15486. const rendered = module.render(renderOptions);
  15487. ({ source } = rendered);
  15488. usesTopLevelAwait || (usesTopLevelAwait = rendered.usesTopLevelAwait);
  15489. renderedLength = source.length();
  15490. if (renderedLength) {
  15491. if (compact && source.lastLine().includes('//'))
  15492. source.append('\n');
  15493. renderedModuleSources.set(module, source);
  15494. magicString.addSource(source);
  15495. usedModules.push(module);
  15496. }
  15497. const namespace = module.namespace;
  15498. if (includedNamespaces.has(module) && !preserveModules) {
  15499. const rendered = namespace.renderBlock(renderOptions);
  15500. if (namespace.renderFirst())
  15501. hoistedSource += n + rendered;
  15502. else
  15503. magicString.addSource(new MagicString(rendered));
  15504. }
  15505. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  15506. if (accessedGlobalVariables) {
  15507. for (const name of accessedGlobalVariables) {
  15508. accessedGlobals.add(name);
  15509. }
  15510. }
  15511. }
  15512. const { renderedExports, removedExports } = module.getRenderedExports();
  15513. renderedModules[module.id] = {
  15514. get code() {
  15515. return source?.toString() ?? null;
  15516. },
  15517. originalLength: module.originalCode.length,
  15518. removedExports,
  15519. renderedExports,
  15520. renderedLength
  15521. };
  15522. }
  15523. if (hoistedSource)
  15524. magicString.prepend(hoistedSource + n + n);
  15525. // eslint-disable-next-line unicorn/consistent-destructuring
  15526. if (this.needsExportsShim) {
  15527. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  15528. }
  15529. const renderedSource = compact ? magicString : magicString.trim();
  15530. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  15531. onwarn(errorEmptyChunk(this.getChunkName()));
  15532. }
  15533. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  15534. }
  15535. setDynamicImportResolutions(fileName) {
  15536. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  15537. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  15538. if (resolvedDynamicImport.chunk) {
  15539. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  15540. if (chunk === this) {
  15541. node.setInternalResolution(resolution.namespace);
  15542. }
  15543. else {
  15544. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null);
  15545. }
  15546. }
  15547. else {
  15548. const { node, resolution } = resolvedDynamicImport;
  15549. const [resolutionString, assertions] = this.getDynamicImportStringAndAssertions(resolution, fileName);
  15550. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, assertions);
  15551. }
  15552. }
  15553. }
  15554. setIdentifierRenderResolutions() {
  15555. const { format, interop, namespaceToStringTag, preserveModules, externalLiveBindings } = this.outputOptions;
  15556. const syntheticExports = new Set();
  15557. for (const exportName of this.getExportNames()) {
  15558. const exportVariable = this.exportsByName.get(exportName);
  15559. if (format !== 'es' &&
  15560. format !== 'system' &&
  15561. exportVariable.isReassigned &&
  15562. !exportVariable.isId) {
  15563. exportVariable.setRenderNames('exports', exportName);
  15564. }
  15565. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  15566. syntheticExports.add(exportVariable);
  15567. }
  15568. else {
  15569. exportVariable.setRenderNames(null, null);
  15570. }
  15571. }
  15572. for (const module of this.orderedModules) {
  15573. if (module.needsExportShim) {
  15574. this.needsExportsShim = true;
  15575. break;
  15576. }
  15577. }
  15578. const usedNames = new Set(['Object', 'Promise']);
  15579. if (this.needsExportsShim) {
  15580. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  15581. }
  15582. if (namespaceToStringTag) {
  15583. usedNames.add('Symbol');
  15584. }
  15585. switch (format) {
  15586. case 'system': {
  15587. usedNames.add('module').add('exports');
  15588. break;
  15589. }
  15590. case 'es': {
  15591. break;
  15592. }
  15593. case 'cjs': {
  15594. usedNames.add('module').add('require').add('__filename').add('__dirname');
  15595. }
  15596. // fallthrough
  15597. default: {
  15598. usedNames.add('exports');
  15599. for (const helper of HELPER_NAMES) {
  15600. usedNames.add(helper);
  15601. }
  15602. }
  15603. }
  15604. 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);
  15605. }
  15606. setImportMetaResolutions(fileName) {
  15607. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format, preserveModules } } = this;
  15608. for (const module of orderedModules) {
  15609. for (const importMeta of module.importMetas) {
  15610. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  15611. }
  15612. if (includedNamespaces.has(module) && !preserveModules) {
  15613. module.namespace.prepare(accessedGlobalsByScope);
  15614. }
  15615. }
  15616. }
  15617. setUpChunkImportsAndExportsForModule(module) {
  15618. const moduleImports = new Set(module.includedImports);
  15619. // when we are not preserving modules, we need to make all namespace variables available for
  15620. // rendering the namespace object
  15621. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  15622. const memberVariables = module.namespace.getMemberVariables();
  15623. for (const variable of Object.values(memberVariables)) {
  15624. moduleImports.add(variable);
  15625. }
  15626. }
  15627. for (let variable of moduleImports) {
  15628. if (variable instanceof ExportDefaultVariable) {
  15629. variable = variable.getOriginalVariable();
  15630. }
  15631. if (variable instanceof SyntheticNamedExportVariable) {
  15632. variable = variable.getBaseVariable();
  15633. }
  15634. const chunk = this.chunkByModule.get(variable.module);
  15635. if (chunk !== this) {
  15636. this.imports.add(variable);
  15637. if (variable.module instanceof Module) {
  15638. this.checkCircularDependencyImport(variable, module);
  15639. // When preserving modules, we do not create namespace objects but directly
  15640. // use the actual namespaces, which would be broken by this logic.
  15641. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  15642. chunk.exports.add(variable);
  15643. }
  15644. }
  15645. }
  15646. }
  15647. if (this.includedNamespaces.has(module) ||
  15648. (module.info.isEntry && module.preserveSignature !== false) ||
  15649. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  15650. this.ensureReexportsAreAvailableForModule(module);
  15651. }
  15652. for (const { node, resolution } of module.dynamicImports) {
  15653. if (node.included &&
  15654. resolution instanceof Module &&
  15655. this.chunkByModule.get(resolution) === this &&
  15656. !this.includedNamespaces.has(resolution)) {
  15657. this.includedNamespaces.add(resolution);
  15658. this.ensureReexportsAreAvailableForModule(resolution);
  15659. }
  15660. }
  15661. }
  15662. }
  15663. function getChunkNameFromModule(module) {
  15664. return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id);
  15665. }
  15666. function getPredefinedChunkNameFromModule(module) {
  15667. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  15668. }
  15669. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  15670. const importedBindingsPerDependency = {};
  15671. for (const [dependency, declaration] of renderedDependencies) {
  15672. const specifiers = new Set();
  15673. if (declaration.imports) {
  15674. for (const { imported } of declaration.imports) {
  15675. specifiers.add(imported);
  15676. }
  15677. }
  15678. if (declaration.reexports) {
  15679. for (const { imported } of declaration.reexports) {
  15680. specifiers.add(imported);
  15681. }
  15682. }
  15683. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  15684. }
  15685. return importedBindingsPerDependency;
  15686. }
  15687. const QUERY_HASH_REGEX = /[#?]/;
  15688. const resolveFileName = (dependency) => dependency.getFileName();
  15689. /**
  15690. * Concatenate a number of iterables to a new iterable without fully evaluating
  15691. * their iterators. Useful when e.g. working with large sets or lists and when
  15692. * there is a chance that the iterators will not be fully exhausted.
  15693. */
  15694. function* concatLazy(iterables) {
  15695. for (const iterable of iterables) {
  15696. yield* iterable;
  15697. }
  15698. }
  15699. /**
  15700. * At its core, the algorithm first starts from each static or dynamic entry
  15701. * point and then assigns that entry point to all modules than can be reached
  15702. * via static imports. We call this the *dependent entry points* of that
  15703. * module.
  15704. *
  15705. * Then we group all modules with the same dependent entry points into chunks
  15706. * as those modules will always be loaded together.
  15707. *
  15708. * One non-trivial optimization we can apply is that dynamic entries are
  15709. * different from static entries in so far as when a dynamic import occurs,
  15710. * some
  15711. * modules are already in memory. If some of these modules are also
  15712. * dependencies
  15713. * of the dynamic entry, then it does not make sense to create a separate chunk
  15714. * for them. Instead, the dynamic import target can load them from the
  15715. * importing
  15716. * chunk.
  15717. *
  15718. * With regard to chunking, if B is implicitly loaded after A, then this can be
  15719. * handled the same way as if there was a dynamic import A => B.
  15720. *
  15721. * Example:
  15722. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  15723. * Then the initial algorithm would assign A into the A chunk, C into the C
  15724. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  15725. * points
  15726. * A and C.
  15727. * However we know that C can only be loaded from A, so A and its dependency B
  15728. * must already be in memory when C is loaded. So it is enough to create only
  15729. * two chunks A containing [AB] and C containing [C].
  15730. *
  15731. * So we do not assign the dynamic entry C as dependent entry point to modules
  15732. * that are already loaded.
  15733. *
  15734. * In a more complex example, let us assume that we have entry points X and Y.
  15735. * Further, let us assume
  15736. * X -> A, X -> B, X -> C,
  15737. * Y -> A, Y -> B,
  15738. * A => D,
  15739. * D -> B, D -> C
  15740. * So without dynamic import optimization, the dependent entry points are
  15741. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y,
  15742. * so we would for now create six chunks.
  15743. *
  15744. * Now D is loaded only after A is loaded. But A is loaded if either X is
  15745. * loaded
  15746. * or Y is loaded. So the modules that are already in memory when D is loaded
  15747. * are the intersection of all modules that X depends on with all modules that
  15748. * Y
  15749. * depends on, which in this case are the modules A and B.
  15750. * We could also say they are all modules that have both X and Y as dependent
  15751. * entry points.
  15752. *
  15753. * So we can remove D as dependent entry point from A and B, which means they
  15754. * both now have only XY as dependent entry points and can be merged into the
  15755. * same chunk.
  15756. *
  15757. * Now let us extend this to the most general case where we have several
  15758. * dynamic
  15759. * importers for one dynamic entry point.
  15760. *
  15761. * In the most general form, it works like this:
  15762. * For each dynamic entry point, we have a number of dynamic importers, which
  15763. * are the modules importing it. Using the previous ideas, we can determine
  15764. * the modules already in memory for each dynamic importer by looking for all
  15765. * modules that have all the dependent entry points of the dynamic importer as
  15766. * dependent entry points.
  15767. * So the modules that are guaranteed to be in memory when the dynamic entry
  15768. * point is loaded are the intersection of the modules already in memory for
  15769. * each dynamic importer.
  15770. *
  15771. * Assuming that A => D and B => D and A has dependent entry points XY and B
  15772. * has
  15773. * dependent entry points YZ, then the modules guaranteed to be in memory are
  15774. * all modules that have at least XYZ as dependent entry points.
  15775. * We call XYZ the *dynamically dependent entry points* of D.
  15776. *
  15777. * Now there is one last case to consider: If one of the dynamically dependent
  15778. * entries is itself a dynamic entry, then any module is in memory that either
  15779. * is a dependency of that dynamic entry or again has the dynamic dependent
  15780. * entries of that dynamic entry as dependent entry points.
  15781. *
  15782. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  15783. * complexity with regard to dynamic entries that blew up for very large
  15784. * projects.
  15785. *
  15786. * If we have an efficient way to do Set operations, an alternative approach
  15787. * would be to instead collect already loaded modules per dynamic entry. And as
  15788. * all chunks from the initial grouping would behave the same, we can instead
  15789. * collect already loaded chunks for a performance improvement.
  15790. *
  15791. * To do that efficiently, need
  15792. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  15793. * imports that can be triggered by a dynamic entry
  15794. * - a Map of static dependencies per entry
  15795. * - a Map of already loaded chunks per entry that we initially populate with
  15796. * empty Sets for static entries and Sets containing all entries for dynamic
  15797. * entries
  15798. *
  15799. * For efficient operations, we assign each entry a numerical index and
  15800. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  15801. * bit index. Then thw last two maps can be represented as arrays of BigInt
  15802. * values.
  15803. *
  15804. * Then we iterate through each dynamic entry. We set the already loaded modules
  15805. * to the intersection of the previously already loaded modules with the union
  15806. * of the already loaded modules of that chunk with its static dependencies.
  15807. *
  15808. * If the already loaded modules changed, then we use the Map of dynamic imports
  15809. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  15810. * them back into the iteration. As an additional optimization, we note for
  15811. * each dynamic entry which dynamic dependent entries have changed and only
  15812. * intersect those entries again on subsequent interations.
  15813. *
  15814. * Then we remove the dynamic entries from the list of dependent entries for
  15815. * those chunks that are already loaded for that dynamic entry and create
  15816. * another round of chunks.
  15817. */
  15818. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize) {
  15819. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  15820. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry } = analyzeModuleGraph(entries);
  15821. // Each chunk is identified by its position in this array
  15822. const initialChunks = Object.values(getChunksBySignature(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks)));
  15823. // This mutates initialChunks but also clears
  15824. // dynamicallyDependentEntriesByDynamicEntry as side effect
  15825. removeUnnecessaryDependentEntries(initialChunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  15826. chunkDefinitions.push(...createChunks(allEntries, getChunksBySignature(initialChunks), minChunkSize));
  15827. return chunkDefinitions;
  15828. }
  15829. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  15830. const chunkDefinitions = [];
  15831. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  15832. const manualChunkModulesByAlias = Object.create(null);
  15833. for (const [entry, alias] of manualChunkAliasByEntry) {
  15834. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] || (manualChunkModulesByAlias[alias] = [])), modulesInManualChunks);
  15835. }
  15836. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  15837. chunkDefinitions.push({ alias, modules });
  15838. }
  15839. return { chunkDefinitions, modulesInManualChunks };
  15840. }
  15841. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  15842. const modulesToHandle = new Set([entry]);
  15843. for (const module of modulesToHandle) {
  15844. modulesInManualChunks.add(module);
  15845. manualChunkModules.push(module);
  15846. for (const dependency of module.dependencies) {
  15847. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  15848. modulesToHandle.add(dependency);
  15849. }
  15850. }
  15851. }
  15852. }
  15853. function analyzeModuleGraph(entries) {
  15854. const dynamicEntryModules = new Set();
  15855. const dependentEntriesByModule = new Map();
  15856. const dynamicImportModulesByEntry = [];
  15857. const allEntriesSet = new Set(entries);
  15858. let entryIndex = 0;
  15859. for (const currentEntry of allEntriesSet) {
  15860. const dynamicImportsForCurrentEntry = new Set();
  15861. dynamicImportModulesByEntry.push(dynamicImportsForCurrentEntry);
  15862. const modulesToHandle = new Set([currentEntry]);
  15863. for (const module of modulesToHandle) {
  15864. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  15865. for (const dependency of module.getDependenciesToBeIncluded()) {
  15866. if (!(dependency instanceof ExternalModule)) {
  15867. modulesToHandle.add(dependency);
  15868. }
  15869. }
  15870. for (const { resolution } of module.dynamicImports) {
  15871. if (resolution instanceof Module &&
  15872. resolution.includedDynamicImporters.length > 0 &&
  15873. !allEntriesSet.has(resolution)) {
  15874. dynamicEntryModules.add(resolution);
  15875. allEntriesSet.add(resolution);
  15876. dynamicImportsForCurrentEntry.add(resolution);
  15877. }
  15878. }
  15879. for (const dependency of module.implicitlyLoadedBefore) {
  15880. if (!allEntriesSet.has(dependency)) {
  15881. dynamicEntryModules.add(dependency);
  15882. allEntriesSet.add(dependency);
  15883. }
  15884. }
  15885. }
  15886. entryIndex++;
  15887. }
  15888. const allEntries = [...allEntriesSet];
  15889. const { dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry);
  15890. return {
  15891. allEntries,
  15892. dependentEntriesByModule,
  15893. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries),
  15894. dynamicImportsByEntry
  15895. };
  15896. }
  15897. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry) {
  15898. const entryIndexByModule = new Map();
  15899. const dynamicEntries = new Set();
  15900. for (const [entryIndex, entry] of allEntries.entries()) {
  15901. entryIndexByModule.set(entry, entryIndex);
  15902. if (dynamicEntryModules.has(entry)) {
  15903. dynamicEntries.add(entryIndex);
  15904. }
  15905. }
  15906. const dynamicImportsByEntry = [];
  15907. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  15908. const dynamicImports = new Set();
  15909. for (const dynamicEntry of dynamicImportModules) {
  15910. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  15911. }
  15912. dynamicImportsByEntry.push(dynamicImports);
  15913. }
  15914. return { dynamicEntries, dynamicImportsByEntry };
  15915. }
  15916. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries) {
  15917. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  15918. for (const dynamicEntryIndex of dynamicEntries) {
  15919. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  15920. const dynamicEntry = allEntries[dynamicEntryIndex];
  15921. for (const importer of concatLazy([
  15922. dynamicEntry.includedDynamicImporters,
  15923. dynamicEntry.implicitlyLoadedAfter
  15924. ])) {
  15925. for (const entry of dependentEntriesByModule.get(importer)) {
  15926. dynamicallyDependentEntries.add(entry);
  15927. }
  15928. }
  15929. }
  15930. return dynamicallyDependentEntriesByDynamicEntry;
  15931. }
  15932. function getChunksBySignature(modulesWithDependentEntries) {
  15933. var _a;
  15934. const chunkModules = Object.create(null);
  15935. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  15936. let chunkSignature = 0n;
  15937. for (const entryIndex of dependentEntries) {
  15938. chunkSignature |= 1n << BigInt(entryIndex);
  15939. }
  15940. (chunkModules[_a = String(chunkSignature)] || (chunkModules[_a] = {
  15941. dependentEntries: new Set(dependentEntries),
  15942. modules: []
  15943. })).modules.push(...modules);
  15944. }
  15945. return chunkModules;
  15946. }
  15947. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  15948. for (const [module, dependentEntries] of dependentEntriesByModule) {
  15949. if (!modulesInManualChunks.has(module)) {
  15950. yield { dependentEntries, modules: [module] };
  15951. }
  15952. }
  15953. }
  15954. /**
  15955. * This removes all unnecessary dynamic entries from the dependenEntries in its
  15956. * first argument. It will also consume its second argument, so if
  15957. * dynamicallyDependentEntriesByDynamicEntry is ever needed after this, we
  15958. * should make a copy.
  15959. */
  15960. function removeUnnecessaryDependentEntries(chunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  15961. // The indices correspond to the indices in allEntries. The chunks correspond
  15962. // to bits in the bigint values where chunk 0 is the lowest bit.
  15963. const staticDependenciesPerEntry = allEntries.map(() => 0n);
  15964. const alreadyLoadedChunksPerEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  15965. // This toggles the bits for each chunk that is a dependency of an entry
  15966. let chunkMask = 1n;
  15967. for (const { dependentEntries } of chunks) {
  15968. for (const entryIndex of dependentEntries) {
  15969. staticDependenciesPerEntry[entryIndex] |= chunkMask;
  15970. }
  15971. chunkMask <<= 1n;
  15972. }
  15973. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  15974. // If we no longer want this, we should make a copy here.
  15975. const updatedDynamicallyDependentEntriesByDynamicEntry = dynamicallyDependentEntriesByDynamicEntry;
  15976. for (const [dynamicEntryIndex, updatedDynamicallyDependentEntries] of updatedDynamicallyDependentEntriesByDynamicEntry) {
  15977. updatedDynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  15978. const previousLoadedModules = alreadyLoadedChunksPerEntry[dynamicEntryIndex];
  15979. let newLoadedModules = previousLoadedModules;
  15980. for (const entryIndex of updatedDynamicallyDependentEntries) {
  15981. newLoadedModules &=
  15982. staticDependenciesPerEntry[entryIndex] | alreadyLoadedChunksPerEntry[entryIndex];
  15983. }
  15984. if (newLoadedModules !== previousLoadedModules) {
  15985. alreadyLoadedChunksPerEntry[dynamicEntryIndex] = newLoadedModules;
  15986. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  15987. getOrCreate(updatedDynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  15988. }
  15989. }
  15990. }
  15991. // Remove entries from dependent entries if a chunk is already loaded without
  15992. // that entry.
  15993. chunkMask = 1n;
  15994. for (const { dependentEntries } of chunks) {
  15995. for (const entryIndex of dependentEntries) {
  15996. if ((alreadyLoadedChunksPerEntry[entryIndex] & chunkMask) === chunkMask) {
  15997. dependentEntries.delete(entryIndex);
  15998. }
  15999. }
  16000. chunkMask <<= 1n;
  16001. }
  16002. }
  16003. function createChunks(allEntries, chunkModulesBySignature, minChunkSize) {
  16004. return minChunkSize === 0
  16005. ? Object.values(chunkModulesBySignature).map(({ modules }) => ({
  16006. alias: null,
  16007. modules
  16008. }))
  16009. : getOptimizedChunks(chunkModulesBySignature, allEntries.length, minChunkSize).map(({ modules }) => ({
  16010. alias: null,
  16011. modules
  16012. }));
  16013. }
  16014. /**
  16015. * This function tries to get rid of small chunks by merging them with other
  16016. * chunks.
  16017. *
  16018. * We can only merge chunks safely if after the merge, loading any entry point
  16019. * in any allowed order will not trigger side effects that should not have been
  16020. * triggered. While side effects are usually things like global function calls,
  16021. * global variable mutations or potentially thrown errors, details do not
  16022. * matter here, and we just discern chunks without side effects (pure chunks)
  16023. * from other chunks.
  16024. *
  16025. * As a first step, we assign each pre-generated chunk with side effects a
  16026. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  16027. *
  16028. * Now to determine the side effects of loading a chunk, one also has to take
  16029. * the side effects of its dependencies into account. So if A depends on B
  16030. * (A -> B) and both have side effects, loading A triggers effects AB.
  16031. *
  16032. * Now from the previous step we know that each chunk is uniquely determine by
  16033. * the entry points that depend on it and cause it to load, which we will call
  16034. * its dependent entry points.
  16035. *
  16036. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  16037. * Starting from that idea, we can determine a set of chunks—and thus a set
  16038. * of side effects—that must have been triggered if a certain chunk has been
  16039. * loaded. Basically, it is the intersection of all chunks loaded by the
  16040. * dependent entry points of a given chunk. We call the corresponding side
  16041. * effects the correlated side effects of that chunk.
  16042. *
  16043. * Example:
  16044. * X -> ABC, Y -> ADE, A-> F, B -> D
  16045. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  16046. * The intersection is ADF. So we know that when A is loaded, D and F must also
  16047. * be in memory even though neither D nor A is a dependency of the other.
  16048. * If all have side effects, we call ADF the correlated side effects of A. The
  16049. * correlated side effects need to remain constant when merging chunks.
  16050. *
  16051. * In contrast, we have the dependency side effects of A, which represents
  16052. * the side effects we trigger if we directly load A. In this example, the
  16053. * dependency side effects are AF.
  16054. * For entry chunks, dependency and correlated side effects are the same.
  16055. *
  16056. * With these concepts, merging chunks is allowed if the correlated side effects
  16057. * of each entry do not change. Thus, we are allowed to merge two chunks if
  16058. * a) the dependency side effects of each chunk are a subset of the correlated
  16059. * side effects of the other chunk, so no additional side effects are
  16060. * triggered for any entry, or
  16061. * b) The signature of chunk A is a subset of the signature of chunk B while the
  16062. * dependency side effects of A are a subset of the correlated side effects
  16063. * of B. Because in that scenario, whenever A is loaded, B is loaded as well.
  16064. * But there are cases when B is loaded where A is not loaded. So if we merge
  16065. * the chunks, all dependency side effects of A will be added to the
  16066. * correlated side effects of B, and as the latter is not allowed to change,
  16067. * the former need to be a subset of the latter.
  16068. *
  16069. * Another consideration when merging small chunks into other chunks is to avoid
  16070. * that too much additional code is loaded. This is achieved when the dependent
  16071. * entries of the small chunk are a subset of the dependent entries of the other
  16072. * chunk. Because then when the small chunk is loaded, the other chunk was
  16073. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  16074. * additional size of the small chunk is loaded unnecessarily.
  16075. *
  16076. * So the algorithm performs merges in two passes:
  16077. * 1. First we try to merge small chunks A only into other chunks B if the
  16078. * dependent entries of A are a subset of the dependent entries of B and the
  16079. * dependency side effects of A are a subset of the correlated side effects
  16080. * of B.
  16081. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  16082. * following the above rules (a) and (b), starting with the smallest chunks
  16083. * to look for possible merge targets.
  16084. */
  16085. // TODO instead of picking the "closest" chunk, we could actually use a
  16086. // technique similar to what we do for side effects to compare the size of the
  16087. // static dependencies that are not part of the correlated dependencies
  16088. function getOptimizedChunks(chunkModulesBySignature, numberOfEntries, minChunkSize) {
  16089. timeStart('optimize chunks', 3);
  16090. const chunkPartition = getPartitionedChunks(chunkModulesBySignature, numberOfEntries, minChunkSize);
  16091. console.log('Before eliminating small chunks, there were\n', Object.keys(chunkModulesBySignature).length, 'chunks, of which\n', chunkPartition.small.size, 'were below minChunkSize.');
  16092. if (chunkPartition.small.size > 0) {
  16093. mergeChunks(chunkPartition, minChunkSize);
  16094. }
  16095. console.log('After merging chunks,\n', chunkPartition.small.size + chunkPartition.big.size, 'chunks remain, of which\n', chunkPartition.small.size, 'are below minChunkSize.');
  16096. timeEnd('optimize chunks', 3);
  16097. return [...chunkPartition.small, ...chunkPartition.big];
  16098. }
  16099. function getPartitionedChunks(chunkModulesBySignature, numberOfEntries, minChunkSize) {
  16100. const smallChunks = [];
  16101. const bigChunks = [];
  16102. const chunkByModule = new Map();
  16103. const sideEffectsByEntry = [];
  16104. for (let index = 0; index < numberOfEntries; index++) {
  16105. sideEffectsByEntry.push(new Set());
  16106. }
  16107. for (const [signature, { dependentEntries, modules }] of Object.entries(chunkModulesBySignature)) {
  16108. const chunkDescription = {
  16109. correlatedSideEffects: new Set(),
  16110. dependencies: new Set(),
  16111. dependentChunks: new Set(),
  16112. dependentEntries,
  16113. modules,
  16114. pure: true,
  16115. sideEffects: new Set(),
  16116. size: 0
  16117. };
  16118. let size = 0;
  16119. let pure = true;
  16120. for (const module of modules) {
  16121. chunkByModule.set(module, chunkDescription);
  16122. pure && (pure = !module.hasEffects());
  16123. // Unfortunately, we cannot take tree-shaking into account here because
  16124. // rendering did not happen yet
  16125. size += module.originalCode.length;
  16126. }
  16127. chunkDescription.pure = pure;
  16128. chunkDescription.size = size;
  16129. if (!pure) {
  16130. for (const entryIndex of dependentEntries) {
  16131. sideEffectsByEntry[entryIndex].add(signature);
  16132. }
  16133. // In the beginning, each chunk is only its own side effect. After
  16134. // merging, additional side effects can accumulate.
  16135. chunkDescription.sideEffects.add(signature);
  16136. }
  16137. (size < minChunkSize ? smallChunks : bigChunks).push(chunkDescription);
  16138. }
  16139. sortChunksAndAddDependenciesAndEffects([bigChunks, smallChunks], chunkByModule, sideEffectsByEntry);
  16140. return {
  16141. big: new Set(bigChunks),
  16142. small: new Set(smallChunks)
  16143. };
  16144. }
  16145. function sortChunksAndAddDependenciesAndEffects(chunkLists, chunkByModule, sideEffectsByEntry) {
  16146. for (const chunks of chunkLists) {
  16147. chunks.sort(compareChunkSize);
  16148. for (const chunk of chunks) {
  16149. const { dependencies, modules, correlatedSideEffects, dependentEntries } = chunk;
  16150. for (const module of modules) {
  16151. for (const dependency of module.getDependenciesToBeIncluded()) {
  16152. const dependencyChunk = chunkByModule.get(dependency);
  16153. if (dependencyChunk && dependencyChunk !== chunk) {
  16154. dependencies.add(dependencyChunk);
  16155. dependencyChunk.dependentChunks.add(chunk);
  16156. }
  16157. }
  16158. }
  16159. let firstEntry = true;
  16160. // Correlated side effects is the intersection of all entry side effects
  16161. for (const entryIndex of dependentEntries) {
  16162. const entryEffects = sideEffectsByEntry[entryIndex];
  16163. if (firstEntry) {
  16164. for (const sideEffect of entryEffects) {
  16165. correlatedSideEffects.add(sideEffect);
  16166. }
  16167. firstEntry = false;
  16168. }
  16169. else {
  16170. for (const sideEffect of correlatedSideEffects) {
  16171. if (!entryEffects.has(sideEffect)) {
  16172. correlatedSideEffects.delete(sideEffect);
  16173. }
  16174. }
  16175. }
  16176. }
  16177. }
  16178. }
  16179. }
  16180. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  16181. return sizeA - sizeB;
  16182. }
  16183. function mergeChunks(chunkPartition, minChunkSize) {
  16184. for (const allowArbitraryMerges of [false, true]) {
  16185. for (const mergedChunk of chunkPartition.small) {
  16186. let closestChunk = null;
  16187. let closestChunkDistance = Infinity;
  16188. const { modules, pure, size } = mergedChunk;
  16189. for (const targetChunk of concatLazy([chunkPartition.small, chunkPartition.big])) {
  16190. if (mergedChunk === targetChunk)
  16191. continue;
  16192. // If both chunks are small, we also allow for unrelated merges during
  16193. // the first pass
  16194. const onlySubsetMerge = !allowArbitraryMerges && targetChunk.size >= minChunkSize;
  16195. const distance = getChunkEntryDistance(mergedChunk, targetChunk, onlySubsetMerge);
  16196. if (distance < closestChunkDistance &&
  16197. isValidMerge(mergedChunk, targetChunk, onlySubsetMerge)) {
  16198. closestChunk = targetChunk;
  16199. closestChunkDistance = distance;
  16200. }
  16201. }
  16202. if (closestChunk) {
  16203. chunkPartition.small.delete(mergedChunk);
  16204. getChunksInPartition(closestChunk, minChunkSize, chunkPartition).delete(closestChunk);
  16205. closestChunk.modules.push(...modules);
  16206. closestChunk.size += size;
  16207. closestChunk.pure && (closestChunk.pure = pure);
  16208. const { correlatedSideEffects, dependencies, dependentChunks, dependentEntries, sideEffects } = closestChunk;
  16209. for (const sideEffect of correlatedSideEffects) {
  16210. if (!mergedChunk.correlatedSideEffects.has(sideEffect)) {
  16211. correlatedSideEffects.delete(sideEffect);
  16212. }
  16213. }
  16214. for (const entry of mergedChunk.dependentEntries) {
  16215. dependentEntries.add(entry);
  16216. }
  16217. for (const sideEffect of mergedChunk.sideEffects) {
  16218. sideEffects.add(sideEffect);
  16219. }
  16220. for (const dependency of mergedChunk.dependencies) {
  16221. dependencies.add(dependency);
  16222. dependency.dependentChunks.delete(mergedChunk);
  16223. dependency.dependentChunks.add(closestChunk);
  16224. }
  16225. for (const dependentChunk of mergedChunk.dependentChunks) {
  16226. dependentChunks.add(dependentChunk);
  16227. dependentChunk.dependencies.delete(mergedChunk);
  16228. dependentChunk.dependencies.add(closestChunk);
  16229. }
  16230. dependencies.delete(closestChunk);
  16231. dependentChunks.delete(closestChunk);
  16232. getChunksInPartition(closestChunk, minChunkSize, chunkPartition).add(closestChunk);
  16233. }
  16234. }
  16235. }
  16236. }
  16237. // Merging will not produce cycles if none of the direct non-merged dependencies
  16238. // of a chunk have the other chunk as a transitive dependency
  16239. function isValidMerge(mergedChunk, targetChunk, onlySubsetMerge) {
  16240. return !(hasTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, true) ||
  16241. hasTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, !onlySubsetMerge));
  16242. }
  16243. function hasTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, checkSideEffects) {
  16244. const { correlatedSideEffects } = dependencyChunk;
  16245. if (checkSideEffects) {
  16246. for (const sideEffect of dependentChunk.sideEffects) {
  16247. if (!correlatedSideEffects.has(sideEffect)) {
  16248. return true;
  16249. }
  16250. }
  16251. }
  16252. const chunksToCheck = new Set(dependentChunk.dependencies);
  16253. for (const { dependencies, sideEffects } of chunksToCheck) {
  16254. for (const dependency of dependencies) {
  16255. if (dependency === dependencyChunk) {
  16256. return true;
  16257. }
  16258. chunksToCheck.add(dependency);
  16259. }
  16260. if (checkSideEffects) {
  16261. for (const sideEffect of sideEffects) {
  16262. if (!correlatedSideEffects.has(sideEffect)) {
  16263. return true;
  16264. }
  16265. }
  16266. }
  16267. }
  16268. return false;
  16269. }
  16270. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  16271. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  16272. }
  16273. function getChunkEntryDistance({ dependentEntries: sourceEntries }, { dependentEntries: targetEntries }, enforceSubest) {
  16274. let distance = 0;
  16275. for (const entryIndex of targetEntries) {
  16276. if (!sourceEntries.has(entryIndex)) {
  16277. distance++;
  16278. }
  16279. }
  16280. for (const entryIndex of sourceEntries) {
  16281. if (!targetEntries.has(entryIndex)) {
  16282. if (enforceSubest) {
  16283. return Infinity;
  16284. }
  16285. distance++;
  16286. }
  16287. }
  16288. return distance;
  16289. }
  16290. // ported from https://github.com/substack/node-commondir
  16291. function commondir(files) {
  16292. if (files.length === 0)
  16293. return '/';
  16294. if (files.length === 1)
  16295. return node_path.dirname(files[0]);
  16296. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  16297. const pathSegements = file.split(/\/+|\\+/);
  16298. let index;
  16299. for (index = 0; commonSegments[index] === pathSegements[index] &&
  16300. index < Math.min(commonSegments.length, pathSegements.length); index++)
  16301. ;
  16302. return commonSegments.slice(0, index);
  16303. }, files[0].split(/\/+|\\+/));
  16304. // Windows correctly handles paths with forward-slashes
  16305. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  16306. }
  16307. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  16308. function sortByExecutionOrder(units) {
  16309. units.sort(compareExecIndex);
  16310. }
  16311. function analyseModuleExecution(entryModules) {
  16312. let nextExecIndex = 0;
  16313. const cyclePaths = [];
  16314. const analysedModules = new Set();
  16315. const dynamicImports = new Set();
  16316. const parents = new Map();
  16317. const orderedModules = [];
  16318. const analyseModule = (module) => {
  16319. if (module instanceof Module) {
  16320. for (const dependency of module.dependencies) {
  16321. if (parents.has(dependency)) {
  16322. if (!analysedModules.has(dependency)) {
  16323. cyclePaths.push(getCyclePath(dependency, module, parents));
  16324. }
  16325. continue;
  16326. }
  16327. parents.set(dependency, module);
  16328. analyseModule(dependency);
  16329. }
  16330. for (const dependency of module.implicitlyLoadedBefore) {
  16331. dynamicImports.add(dependency);
  16332. }
  16333. for (const { resolution } of module.dynamicImports) {
  16334. if (resolution instanceof Module) {
  16335. dynamicImports.add(resolution);
  16336. }
  16337. }
  16338. orderedModules.push(module);
  16339. }
  16340. module.execIndex = nextExecIndex++;
  16341. analysedModules.add(module);
  16342. };
  16343. for (const currentEntry of entryModules) {
  16344. if (!parents.has(currentEntry)) {
  16345. parents.set(currentEntry, null);
  16346. analyseModule(currentEntry);
  16347. }
  16348. }
  16349. for (const currentEntry of dynamicImports) {
  16350. if (!parents.has(currentEntry)) {
  16351. parents.set(currentEntry, null);
  16352. analyseModule(currentEntry);
  16353. }
  16354. }
  16355. return { cyclePaths, orderedModules };
  16356. }
  16357. function getCyclePath(module, parent, parents) {
  16358. const cycleSymbol = Symbol(module.id);
  16359. const path = [module.id];
  16360. let nextModule = parent;
  16361. module.cycles.add(cycleSymbol);
  16362. while (nextModule !== module) {
  16363. nextModule.cycles.add(cycleSymbol);
  16364. path.push(nextModule.id);
  16365. nextModule = parents.get(nextModule);
  16366. }
  16367. path.push(path[0]);
  16368. path.reverse();
  16369. return path;
  16370. }
  16371. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  16372. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  16373. const cnst = constBindings ? 'const' : 'var';
  16374. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  16375. const getFunctionIntro = arrowFunctions
  16376. ? (parameters, { isAsync, name }) => {
  16377. const singleParameter = parameters.length === 1;
  16378. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  16379. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  16380. }
  16381. : getNonArrowFunctionIntro;
  16382. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  16383. `${getFunctionIntro(parameters, {
  16384. isAsync: false,
  16385. name
  16386. })}${arrowFunctions
  16387. ? lineBreakIndent
  16388. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  16389. : ''
  16390. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  16391. arrowFunctions
  16392. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  16393. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  16394. ];
  16395. const isValidPropertyName = reservedNamesAsProps
  16396. ? (name) => validPropertyName.test(name)
  16397. : (name) => !RESERVED_NAMES$1.has(name) && validPropertyName.test(name);
  16398. return {
  16399. _,
  16400. cnst,
  16401. getDirectReturnFunction,
  16402. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  16403. const [left, right] = getDirectReturnFunction(parameters, {
  16404. functionReturn: true,
  16405. lineBreakIndent: null,
  16406. name: null
  16407. });
  16408. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  16409. },
  16410. getFunctionIntro,
  16411. getNonArrowFunctionIntro,
  16412. getObject(fields, { lineBreakIndent }) {
  16413. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  16414. return `{${fields
  16415. .map(([key, value]) => {
  16416. if (key === null)
  16417. return `${prefix}${value}`;
  16418. const needsQuotes = !isValidPropertyName(key);
  16419. return key === value && objectShorthand && !needsQuotes
  16420. ? prefix + key
  16421. : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
  16422. })
  16423. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  16424. },
  16425. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  16426. n,
  16427. s
  16428. };
  16429. }
  16430. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  16431. const validPropertyName = /^(?!\d)[\w$]+$/;
  16432. class Source {
  16433. constructor(filename, content) {
  16434. this.isOriginal = true;
  16435. this.filename = filename;
  16436. this.content = content;
  16437. }
  16438. traceSegment(line, column, name) {
  16439. return { column, line, name, source: this };
  16440. }
  16441. }
  16442. class Link {
  16443. constructor(map, sources) {
  16444. this.sources = sources;
  16445. this.names = map.names;
  16446. this.mappings = map.mappings;
  16447. }
  16448. traceMappings() {
  16449. const sources = [];
  16450. const sourceIndexMap = new Map();
  16451. const sourcesContent = [];
  16452. const names = [];
  16453. const nameIndexMap = new Map();
  16454. const mappings = [];
  16455. for (const line of this.mappings) {
  16456. const tracedLine = [];
  16457. for (const segment of line) {
  16458. if (segment.length === 1)
  16459. continue;
  16460. const source = this.sources[segment[1]];
  16461. if (!source)
  16462. continue;
  16463. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  16464. if (traced) {
  16465. const { column, line, name, source: { content, filename } } = traced;
  16466. let sourceIndex = sourceIndexMap.get(filename);
  16467. if (sourceIndex === undefined) {
  16468. sourceIndex = sources.length;
  16469. sources.push(filename);
  16470. sourceIndexMap.set(filename, sourceIndex);
  16471. sourcesContent[sourceIndex] = content;
  16472. }
  16473. else if (sourcesContent[sourceIndex] == null) {
  16474. sourcesContent[sourceIndex] = content;
  16475. }
  16476. else if (content != null && sourcesContent[sourceIndex] !== content) {
  16477. return error(errorConflictingSourcemapSources(filename));
  16478. }
  16479. const tracedSegment = [segment[0], sourceIndex, line, column];
  16480. if (name) {
  16481. let nameIndex = nameIndexMap.get(name);
  16482. if (nameIndex === undefined) {
  16483. nameIndex = names.length;
  16484. names.push(name);
  16485. nameIndexMap.set(name, nameIndex);
  16486. }
  16487. tracedSegment[4] = nameIndex;
  16488. }
  16489. tracedLine.push(tracedSegment);
  16490. }
  16491. }
  16492. mappings.push(tracedLine);
  16493. }
  16494. return { mappings, names, sources, sourcesContent };
  16495. }
  16496. traceSegment(line, column, name) {
  16497. const segments = this.mappings[line];
  16498. if (!segments)
  16499. return null;
  16500. // binary search through segments for the given column
  16501. let searchStart = 0;
  16502. let searchEnd = segments.length - 1;
  16503. while (searchStart <= searchEnd) {
  16504. const m = (searchStart + searchEnd) >> 1;
  16505. const segment = segments[m];
  16506. // If a sourcemap does not have sufficient resolution to contain a
  16507. // necessary mapping, e.g. because it only contains line information, we
  16508. // use the best approximation we could find
  16509. if (segment[0] === column || searchStart === searchEnd) {
  16510. if (segment.length == 1)
  16511. return null;
  16512. const source = this.sources[segment[1]];
  16513. if (!source)
  16514. return null;
  16515. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  16516. }
  16517. if (segment[0] > column) {
  16518. searchEnd = m - 1;
  16519. }
  16520. else {
  16521. searchStart = m + 1;
  16522. }
  16523. }
  16524. return null;
  16525. }
  16526. }
  16527. function getLinkMap(warn) {
  16528. return function linkMap(source, map) {
  16529. if (map.mappings) {
  16530. return new Link(map, [source]);
  16531. }
  16532. warn(errorSourcemapBroken(map.plugin));
  16533. return new Link({
  16534. mappings: [],
  16535. names: []
  16536. }, [source]);
  16537. };
  16538. }
  16539. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  16540. let source;
  16541. if (originalSourcemap) {
  16542. const sources = originalSourcemap.sources;
  16543. const sourcesContent = originalSourcemap.sourcesContent || [];
  16544. const directory = node_path.dirname(id) || '.';
  16545. const sourceRoot = originalSourcemap.sourceRoot || '.';
  16546. const baseSources = sources.map((source, index) => new Source(node_path.resolve(directory, sourceRoot, source), sourcesContent[index]));
  16547. source = new Link(originalSourcemap, baseSources);
  16548. }
  16549. else {
  16550. source = new Source(id, originalCode);
  16551. }
  16552. return sourcemapChain.reduce(linkMap, source);
  16553. }
  16554. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  16555. const linkMap = getLinkMap(warn);
  16556. const moduleSources = modules
  16557. .filter(module => !module.excludeFromSourcemap)
  16558. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  16559. const link = new Link(map, moduleSources);
  16560. const source = bundleSourcemapChain.reduce(linkMap, link);
  16561. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  16562. if (file) {
  16563. const directory = node_path.dirname(file);
  16564. sources = sources.map((source) => node_path.relative(directory, source));
  16565. file = node_path.basename(file);
  16566. }
  16567. sourcesContent = (excludeContent ? null : sourcesContent);
  16568. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  16569. }
  16570. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  16571. if (sourcemapChain.length === 0) {
  16572. return originalSourcemap;
  16573. }
  16574. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  16575. const map = source.traceMappings();
  16576. return { version: 3, ...map };
  16577. }
  16578. const createHash = () => node_crypto.createHash('sha256');
  16579. function decodedSourcemap(map) {
  16580. if (!map)
  16581. return null;
  16582. if (typeof map === 'string') {
  16583. map = JSON.parse(map);
  16584. }
  16585. if (map.mappings === '') {
  16586. return {
  16587. mappings: [],
  16588. names: [],
  16589. sources: [],
  16590. version: 3
  16591. };
  16592. }
  16593. const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
  16594. return { ...map, mappings };
  16595. }
  16596. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, onwarn) {
  16597. timeStart('render chunks', 2);
  16598. reserveEntryChunksInBundle(chunks);
  16599. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  16600. timeEnd('render chunks', 2);
  16601. timeStart('transform chunks', 2);
  16602. const chunkGraph = getChunkGraph(chunks);
  16603. const { nonHashedChunksWithPlaceholders, renderedChunksByPlaceholder, hashDependenciesByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, onwarn);
  16604. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, bundle);
  16605. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  16606. timeEnd('transform chunks', 2);
  16607. }
  16608. function reserveEntryChunksInBundle(chunks) {
  16609. for (const chunk of chunks) {
  16610. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  16611. // reserves name in bundle as side effect if it does not contain a hash
  16612. chunk.getPreliminaryFileName();
  16613. }
  16614. }
  16615. }
  16616. function getChunkGraph(chunks) {
  16617. return Object.fromEntries(chunks.map(chunk => {
  16618. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  16619. return [renderedChunkInfo.fileName, renderedChunkInfo];
  16620. }));
  16621. }
  16622. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, onwarn) {
  16623. let map = null;
  16624. const sourcemapChain = [];
  16625. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  16626. if (result == null)
  16627. return code;
  16628. if (typeof result === 'string')
  16629. result = {
  16630. code: result,
  16631. map: undefined
  16632. };
  16633. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  16634. if (result.map !== null) {
  16635. const map = decodedSourcemap(result.map);
  16636. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  16637. }
  16638. return result.code;
  16639. });
  16640. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  16641. if (!compact && code[code.length - 1] !== '\n')
  16642. code += '\n';
  16643. if (sourcemap) {
  16644. timeStart('sourcemaps', 3);
  16645. let resultingFile;
  16646. if (file)
  16647. resultingFile = node_path.resolve(sourcemapFile || file);
  16648. else if (dir)
  16649. resultingFile = node_path.resolve(dir, fileName);
  16650. else
  16651. resultingFile = node_path.resolve(fileName);
  16652. const decodedMap = magicString.generateDecodedMap({});
  16653. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, onwarn);
  16654. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  16655. let sourcePath = map.sources[sourcesIndex];
  16656. const sourcemapPath = `${resultingFile}.map`;
  16657. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  16658. if (typeof ignoreList !== 'boolean') {
  16659. error(errorFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  16660. }
  16661. if (ignoreList) {
  16662. if (map.x_google_ignoreList === undefined) {
  16663. map.x_google_ignoreList = [];
  16664. }
  16665. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  16666. map.x_google_ignoreList.push(sourcesIndex);
  16667. }
  16668. }
  16669. if (sourcemapPathTransform) {
  16670. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  16671. if (typeof sourcePath !== 'string') {
  16672. error(errorFailedValidation(`sourcemapPathTransform function must return a string.`));
  16673. }
  16674. }
  16675. map.sources[sourcesIndex] = normalize(sourcePath);
  16676. }
  16677. timeEnd('sourcemaps', 3);
  16678. }
  16679. return {
  16680. code,
  16681. map
  16682. };
  16683. }
  16684. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, onwarn) {
  16685. const nonHashedChunksWithPlaceholders = [];
  16686. const renderedChunksByPlaceholder = new Map();
  16687. const hashDependenciesByPlaceholder = new Map();
  16688. const placeholders = new Set();
  16689. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  16690. if (hashPlaceholder)
  16691. placeholders.add(hashPlaceholder);
  16692. }
  16693. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, magicString, usedModules }) => {
  16694. const transformedChunk = {
  16695. chunk,
  16696. fileName,
  16697. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, onwarn))
  16698. };
  16699. const { code } = transformedChunk;
  16700. if (hashPlaceholder) {
  16701. // To create a reproducible content-only hash, all placeholders are
  16702. // replaced with the same value before hashing
  16703. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  16704. const hash = createHash().update(transformedCode);
  16705. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  16706. if (pluginHash) {
  16707. augmentation += pluginHash;
  16708. }
  16709. return augmentation;
  16710. });
  16711. if (hashAugmentation) {
  16712. hash.update(hashAugmentation);
  16713. }
  16714. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  16715. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  16716. containedPlaceholders,
  16717. contentHash: hash.digest('hex')
  16718. });
  16719. }
  16720. else {
  16721. nonHashedChunksWithPlaceholders.push(transformedChunk);
  16722. }
  16723. }));
  16724. return {
  16725. hashDependenciesByPlaceholder,
  16726. nonHashedChunksWithPlaceholders,
  16727. renderedChunksByPlaceholder
  16728. };
  16729. }
  16730. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, bundle) {
  16731. const hashesByPlaceholder = new Map();
  16732. for (const [placeholder, { fileName }] of renderedChunksByPlaceholder) {
  16733. let hash = createHash();
  16734. const hashDependencyPlaceholders = new Set([placeholder]);
  16735. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  16736. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  16737. hash.update(contentHash);
  16738. for (const containedPlaceholder of containedPlaceholders) {
  16739. // When looping over a map, setting an entry only causes a new iteration if the key is new
  16740. hashDependencyPlaceholders.add(containedPlaceholder);
  16741. }
  16742. }
  16743. let finalFileName;
  16744. let finalHash;
  16745. do {
  16746. // In case of a hash collision, create a hash of the hash
  16747. if (finalHash) {
  16748. hash = createHash().update(finalHash);
  16749. }
  16750. finalHash = hash.digest('hex').slice(0, placeholder.length);
  16751. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  16752. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  16753. bundle[finalFileName] = FILE_PLACEHOLDER;
  16754. hashesByPlaceholder.set(placeholder, finalHash);
  16755. }
  16756. return hashesByPlaceholder;
  16757. }
  16758. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  16759. for (const { chunk, code, fileName, map } of renderedChunksByPlaceholder.values()) {
  16760. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  16761. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  16762. if (map) {
  16763. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  16764. updatedCode += emitSourceMapAndGetComment(finalFileName, map, pluginDriver, options);
  16765. }
  16766. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, hashesByPlaceholder);
  16767. }
  16768. for (const { chunk, code, fileName, map } of nonHashedChunksWithPlaceholders) {
  16769. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  16770. if (map) {
  16771. updatedCode += emitSourceMapAndGetComment(fileName, map, pluginDriver, options);
  16772. }
  16773. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, hashesByPlaceholder);
  16774. }
  16775. }
  16776. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  16777. let url;
  16778. if (sourcemap === 'inline') {
  16779. url = map.toUrl();
  16780. }
  16781. else {
  16782. const sourcemapFileName = `${node_path.basename(fileName)}.map`;
  16783. url = sourcemapBaseUrl
  16784. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  16785. : sourcemapFileName;
  16786. pluginDriver.emitFile({ fileName: `${fileName}.map`, source: map.toString(), type: 'asset' });
  16787. }
  16788. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  16789. }
  16790. class Bundle {
  16791. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  16792. this.outputOptions = outputOptions;
  16793. this.unsetOptions = unsetOptions;
  16794. this.inputOptions = inputOptions;
  16795. this.pluginDriver = pluginDriver;
  16796. this.graph = graph;
  16797. this.facadeChunkByModule = new Map();
  16798. this.includedNamespaces = new Set();
  16799. }
  16800. async generate(isWrite) {
  16801. timeStart('GENERATE', 1);
  16802. const outputBundleBase = Object.create(null);
  16803. const outputBundle = getOutputBundle(outputBundleBase);
  16804. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  16805. try {
  16806. timeStart('initialize render', 2);
  16807. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  16808. timeEnd('initialize render', 2);
  16809. timeStart('generate chunks', 2);
  16810. const getHashPlaceholder = getHashPlaceholderGenerator();
  16811. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  16812. if (chunks.length > 1) {
  16813. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
  16814. }
  16815. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  16816. for (const chunk of chunks) {
  16817. chunk.generateExports();
  16818. }
  16819. timeEnd('generate chunks', 2);
  16820. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onwarn);
  16821. }
  16822. catch (error_) {
  16823. await this.pluginDriver.hookParallel('renderError', [error_]);
  16824. throw error_;
  16825. }
  16826. removeUnreferencedAssets(outputBundle);
  16827. timeStart('generate bundle', 2);
  16828. await this.pluginDriver.hookSeq('generateBundle', [
  16829. this.outputOptions,
  16830. outputBundle,
  16831. isWrite
  16832. ]);
  16833. this.finaliseAssets(outputBundle);
  16834. timeEnd('generate bundle', 2);
  16835. timeEnd('GENERATE', 1);
  16836. return outputBundleBase;
  16837. }
  16838. async addManualChunks(manualChunks) {
  16839. const manualChunkAliasByEntry = new Map();
  16840. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  16841. alias,
  16842. entries: await this.graph.moduleLoader.addAdditionalModules(files)
  16843. })));
  16844. for (const { alias, entries } of chunkEntries) {
  16845. for (const entry of entries) {
  16846. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  16847. }
  16848. }
  16849. return manualChunkAliasByEntry;
  16850. }
  16851. assignManualChunks(getManualChunk) {
  16852. // eslint-disable-next-line unicorn/prefer-module
  16853. const manualChunkAliasesWithEntry = [];
  16854. const manualChunksApi = {
  16855. getModuleIds: () => this.graph.modulesById.keys(),
  16856. getModuleInfo: this.graph.getModuleInfo
  16857. };
  16858. for (const module of this.graph.modulesById.values()) {
  16859. if (module instanceof Module) {
  16860. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  16861. if (typeof manualChunkAlias === 'string') {
  16862. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  16863. }
  16864. }
  16865. }
  16866. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  16867. const manualChunkAliasByEntry = new Map();
  16868. for (const [alias, module] of manualChunkAliasesWithEntry) {
  16869. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  16870. }
  16871. return manualChunkAliasByEntry;
  16872. }
  16873. finaliseAssets(bundle) {
  16874. if (this.outputOptions.validate) {
  16875. for (const file of Object.values(bundle)) {
  16876. if ('code' in file) {
  16877. try {
  16878. this.graph.contextParse(file.code, {
  16879. ecmaVersion: 'latest'
  16880. });
  16881. }
  16882. catch (error_) {
  16883. this.inputOptions.onwarn(errorChunkInvalid(file, error_));
  16884. }
  16885. }
  16886. }
  16887. }
  16888. this.pluginDriver.finaliseAssets();
  16889. }
  16890. async generateChunks(bundle, getHashPlaceholder) {
  16891. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  16892. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  16893. ? await this.addManualChunks(manualChunks)
  16894. : this.assignManualChunks(manualChunks);
  16895. const snippets = getGenerateCodeSnippets(this.outputOptions);
  16896. const includedModules = getIncludedModules(this.graph.modulesById);
  16897. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  16898. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  16899. const chunks = [];
  16900. const chunkByModule = new Map();
  16901. for (const { alias, modules } of inlineDynamicImports
  16902. ? [{ alias: null, modules: includedModules }]
  16903. : preserveModules
  16904. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  16905. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize)) {
  16906. sortByExecutionOrder(modules);
  16907. 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);
  16908. chunks.push(chunk);
  16909. }
  16910. for (const chunk of chunks) {
  16911. chunk.link();
  16912. }
  16913. const facades = [];
  16914. for (const chunk of chunks) {
  16915. facades.push(...chunk.generateFacades());
  16916. }
  16917. return [...chunks, ...facades];
  16918. }
  16919. }
  16920. function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
  16921. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  16922. return error(errorInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  16923. if (typeof outputOptions.file === 'string')
  16924. return error(errorInvalidOption('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'));
  16925. if (outputOptions.sourcemapFile)
  16926. return error(errorInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  16927. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  16928. onWarn(errorInvalidOption('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'));
  16929. }
  16930. function getIncludedModules(modulesById) {
  16931. const includedModules = [];
  16932. for (const module of modulesById.values()) {
  16933. if (module instanceof Module &&
  16934. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  16935. includedModules.push(module);
  16936. }
  16937. }
  16938. return includedModules;
  16939. }
  16940. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  16941. const absoluteEntryModulePaths = [];
  16942. for (const module of includedModules) {
  16943. if ((module.info.isEntry || preserveModules) && isAbsolute(module.id)) {
  16944. absoluteEntryModulePaths.push(module.id);
  16945. }
  16946. }
  16947. return absoluteEntryModulePaths;
  16948. }
  16949. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  16950. const externalChunkByModule = new Map();
  16951. for (const module of modulesById.values()) {
  16952. if (module instanceof ExternalModule) {
  16953. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  16954. }
  16955. }
  16956. return externalChunkByModule;
  16957. }
  16958. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  16959. const existingAlias = manualChunkAliasByEntry.get(module);
  16960. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  16961. return error(errorCannotAssignModuleToChunk(module.id, alias, existingAlias));
  16962. }
  16963. manualChunkAliasByEntry.set(module, alias);
  16964. }
  16965. // This file was generated. Do not modify manually!
  16966. var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  16967. // This file was generated. Do not modify manually!
  16968. var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
  16969. // This file was generated. Do not modify manually!
  16970. var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  16971. // This file was generated. Do not modify manually!
  16972. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  16973. // These are a run-length and offset encoded representation of the
  16974. // Reserved word lists for various dialects of the language
  16975. var reservedWords = {
  16976. 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  16977. 5: "class enum extends super const export import",
  16978. 6: "enum",
  16979. strict: "implements interface let package private protected public static yield",
  16980. strictBind: "eval arguments"
  16981. };
  16982. // And the keywords
  16983. var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
  16984. var keywords$1 = {
  16985. 5: ecma5AndLessKeywords,
  16986. "5module": ecma5AndLessKeywords + " export import",
  16987. 6: ecma5AndLessKeywords + " const class extends export import super"
  16988. };
  16989. var keywordRelationalOperator = /^in(stanceof)?$/;
  16990. // ## Character categories
  16991. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  16992. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  16993. // This has a complexity linear to the value of the code. The
  16994. // assumption is that looking up astral identifier characters is
  16995. // rare.
  16996. function isInAstralSet(code, set) {
  16997. var pos = 0x10000;
  16998. for (var i = 0; i < set.length; i += 2) {
  16999. pos += set[i];
  17000. if (pos > code) { return false }
  17001. pos += set[i + 1];
  17002. if (pos >= code) { return true }
  17003. }
  17004. }
  17005. // Test whether a given character code starts an identifier.
  17006. function isIdentifierStart(code, astral) {
  17007. if (code < 65) { return code === 36 }
  17008. if (code < 91) { return true }
  17009. if (code < 97) { return code === 95 }
  17010. if (code < 123) { return true }
  17011. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  17012. if (astral === false) { return false }
  17013. return isInAstralSet(code, astralIdentifierStartCodes)
  17014. }
  17015. // Test whether a given character is part of an identifier.
  17016. function isIdentifierChar(code, astral) {
  17017. if (code < 48) { return code === 36 }
  17018. if (code < 58) { return true }
  17019. if (code < 65) { return false }
  17020. if (code < 91) { return true }
  17021. if (code < 97) { return code === 95 }
  17022. if (code < 123) { return true }
  17023. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  17024. if (astral === false) { return false }
  17025. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  17026. }
  17027. // ## Token types
  17028. // The assignment of fine-grained, information-carrying type objects
  17029. // allows the tokenizer to store the information it has about a
  17030. // token in a way that is very cheap for the parser to look up.
  17031. // All token type variables start with an underscore, to make them
  17032. // easy to recognize.
  17033. // The `beforeExpr` property is used to disambiguate between regular
  17034. // expressions and divisions. It is set on all token types that can
  17035. // be followed by an expression (thus, a slash after them would be a
  17036. // regular expression).
  17037. //
  17038. // The `startsExpr` property is used to check if the token ends a
  17039. // `yield` expression. It is set on all token types that either can
  17040. // directly start an expression (like a quotation mark) or can
  17041. // continue an expression (like the body of a string).
  17042. //
  17043. // `isLoop` marks a keyword as starting a loop, which is important
  17044. // to know when parsing a label, in order to allow or disallow
  17045. // continue jumps to that label.
  17046. var TokenType = function TokenType(label, conf) {
  17047. if ( conf === void 0 ) conf = {};
  17048. this.label = label;
  17049. this.keyword = conf.keyword;
  17050. this.beforeExpr = !!conf.beforeExpr;
  17051. this.startsExpr = !!conf.startsExpr;
  17052. this.isLoop = !!conf.isLoop;
  17053. this.isAssign = !!conf.isAssign;
  17054. this.prefix = !!conf.prefix;
  17055. this.postfix = !!conf.postfix;
  17056. this.binop = conf.binop || null;
  17057. this.updateContext = null;
  17058. };
  17059. function binop(name, prec) {
  17060. return new TokenType(name, {beforeExpr: true, binop: prec})
  17061. }
  17062. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  17063. // Map keyword names to token types.
  17064. var keywords = {};
  17065. // Succinct definitions of keyword token types
  17066. function kw(name, options) {
  17067. if ( options === void 0 ) options = {};
  17068. options.keyword = name;
  17069. return keywords[name] = new TokenType(name, options)
  17070. }
  17071. var types$1 = {
  17072. num: new TokenType("num", startsExpr),
  17073. regexp: new TokenType("regexp", startsExpr),
  17074. string: new TokenType("string", startsExpr),
  17075. name: new TokenType("name", startsExpr),
  17076. privateId: new TokenType("privateId", startsExpr),
  17077. eof: new TokenType("eof"),
  17078. // Punctuation token types.
  17079. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  17080. bracketR: new TokenType("]"),
  17081. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  17082. braceR: new TokenType("}"),
  17083. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  17084. parenR: new TokenType(")"),
  17085. comma: new TokenType(",", beforeExpr),
  17086. semi: new TokenType(";", beforeExpr),
  17087. colon: new TokenType(":", beforeExpr),
  17088. dot: new TokenType("."),
  17089. question: new TokenType("?", beforeExpr),
  17090. questionDot: new TokenType("?."),
  17091. arrow: new TokenType("=>", beforeExpr),
  17092. template: new TokenType("template"),
  17093. invalidTemplate: new TokenType("invalidTemplate"),
  17094. ellipsis: new TokenType("...", beforeExpr),
  17095. backQuote: new TokenType("`", startsExpr),
  17096. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  17097. // Operators. These carry several kinds of properties to help the
  17098. // parser use them properly (the presence of these properties is
  17099. // what categorizes them as operators).
  17100. //
  17101. // `binop`, when present, specifies that this operator is a binary
  17102. // operator, and will refer to its precedence.
  17103. //
  17104. // `prefix` and `postfix` mark the operator as a prefix or postfix
  17105. // unary operator.
  17106. //
  17107. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  17108. // binary operators with a very low precedence, that should result
  17109. // in AssignmentExpression nodes.
  17110. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  17111. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  17112. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  17113. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  17114. logicalOR: binop("||", 1),
  17115. logicalAND: binop("&&", 2),
  17116. bitwiseOR: binop("|", 3),
  17117. bitwiseXOR: binop("^", 4),
  17118. bitwiseAND: binop("&", 5),
  17119. equality: binop("==/!=/===/!==", 6),
  17120. relational: binop("</>/<=/>=", 7),
  17121. bitShift: binop("<</>>/>>>", 8),
  17122. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  17123. modulo: binop("%", 10),
  17124. star: binop("*", 10),
  17125. slash: binop("/", 10),
  17126. starstar: new TokenType("**", {beforeExpr: true}),
  17127. coalesce: binop("??", 1),
  17128. // Keyword token types.
  17129. _break: kw("break"),
  17130. _case: kw("case", beforeExpr),
  17131. _catch: kw("catch"),
  17132. _continue: kw("continue"),
  17133. _debugger: kw("debugger"),
  17134. _default: kw("default", beforeExpr),
  17135. _do: kw("do", {isLoop: true, beforeExpr: true}),
  17136. _else: kw("else", beforeExpr),
  17137. _finally: kw("finally"),
  17138. _for: kw("for", {isLoop: true}),
  17139. _function: kw("function", startsExpr),
  17140. _if: kw("if"),
  17141. _return: kw("return", beforeExpr),
  17142. _switch: kw("switch"),
  17143. _throw: kw("throw", beforeExpr),
  17144. _try: kw("try"),
  17145. _var: kw("var"),
  17146. _const: kw("const"),
  17147. _while: kw("while", {isLoop: true}),
  17148. _with: kw("with"),
  17149. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  17150. _this: kw("this", startsExpr),
  17151. _super: kw("super", startsExpr),
  17152. _class: kw("class", startsExpr),
  17153. _extends: kw("extends", beforeExpr),
  17154. _export: kw("export"),
  17155. _import: kw("import", startsExpr),
  17156. _null: kw("null", startsExpr),
  17157. _true: kw("true", startsExpr),
  17158. _false: kw("false", startsExpr),
  17159. _in: kw("in", {beforeExpr: true, binop: 7}),
  17160. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  17161. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  17162. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  17163. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  17164. };
  17165. // Matches a whole line break (where CRLF is considered a single
  17166. // line break). Used to count lines.
  17167. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  17168. var lineBreakG = new RegExp(lineBreak.source, "g");
  17169. function isNewLine(code) {
  17170. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  17171. }
  17172. function nextLineBreak(code, from, end) {
  17173. if ( end === void 0 ) end = code.length;
  17174. for (var i = from; i < end; i++) {
  17175. var next = code.charCodeAt(i);
  17176. if (isNewLine(next))
  17177. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  17178. }
  17179. return -1
  17180. }
  17181. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  17182. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  17183. var ref = Object.prototype;
  17184. var hasOwnProperty = ref.hasOwnProperty;
  17185. var toString = ref.toString;
  17186. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  17187. hasOwnProperty.call(obj, propName)
  17188. ); });
  17189. var isArray = Array.isArray || (function (obj) { return (
  17190. toString.call(obj) === "[object Array]"
  17191. ); });
  17192. function wordsRegexp(words) {
  17193. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  17194. }
  17195. function codePointToString(code) {
  17196. // UTF-16 Decoding
  17197. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  17198. code -= 0x10000;
  17199. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  17200. }
  17201. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  17202. // These are used when `options.locations` is on, for the
  17203. // `startLoc` and `endLoc` properties.
  17204. var Position = function Position(line, col) {
  17205. this.line = line;
  17206. this.column = col;
  17207. };
  17208. Position.prototype.offset = function offset (n) {
  17209. return new Position(this.line, this.column + n)
  17210. };
  17211. var SourceLocation = function SourceLocation(p, start, end) {
  17212. this.start = start;
  17213. this.end = end;
  17214. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  17215. };
  17216. // The `getLineInfo` function is mostly useful when the
  17217. // `locations` option is off (for performance reasons) and you
  17218. // want to find the line/column position for a given character
  17219. // offset. `input` should be the code string that the offset refers
  17220. // into.
  17221. function getLineInfo(input, offset) {
  17222. for (var line = 1, cur = 0;;) {
  17223. var nextBreak = nextLineBreak(input, cur, offset);
  17224. if (nextBreak < 0) { return new Position(line, offset - cur) }
  17225. ++line;
  17226. cur = nextBreak;
  17227. }
  17228. }
  17229. // A second argument must be given to configure the parser process.
  17230. // These options are recognized (only `ecmaVersion` is required):
  17231. var defaultOptions = {
  17232. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  17233. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  17234. // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
  17235. // (the latest version the library supports). This influences
  17236. // support for strict mode, the set of reserved words, and support
  17237. // for new syntax features.
  17238. ecmaVersion: null,
  17239. // `sourceType` indicates the mode the code should be parsed in.
  17240. // Can be either `"script"` or `"module"`. This influences global
  17241. // strict mode and parsing of `import` and `export` declarations.
  17242. sourceType: "script",
  17243. // `onInsertedSemicolon` can be a callback that will be called
  17244. // when a semicolon is automatically inserted. It will be passed
  17245. // the position of the comma as an offset, and if `locations` is
  17246. // enabled, it is given the location as a `{line, column}` object
  17247. // as second argument.
  17248. onInsertedSemicolon: null,
  17249. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  17250. // trailing commas.
  17251. onTrailingComma: null,
  17252. // By default, reserved words are only enforced if ecmaVersion >= 5.
  17253. // Set `allowReserved` to a boolean value to explicitly turn this on
  17254. // an off. When this option has the value "never", reserved words
  17255. // and keywords can also not be used as property names.
  17256. allowReserved: null,
  17257. // When enabled, a return at the top level is not considered an
  17258. // error.
  17259. allowReturnOutsideFunction: false,
  17260. // When enabled, import/export statements are not constrained to
  17261. // appearing at the top of the program, and an import.meta expression
  17262. // in a script isn't considered an error.
  17263. allowImportExportEverywhere: false,
  17264. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  17265. // When enabled, await identifiers are allowed to appear at the top-level scope,
  17266. // but they are still not allowed in non-async functions.
  17267. allowAwaitOutsideFunction: null,
  17268. // When enabled, super identifiers are not constrained to
  17269. // appearing in methods and do not raise an error when they appear elsewhere.
  17270. allowSuperOutsideMethod: null,
  17271. // When enabled, hashbang directive in the beginning of file is
  17272. // allowed and treated as a line comment. Enabled by default when
  17273. // `ecmaVersion` >= 2023.
  17274. allowHashBang: false,
  17275. // When `locations` is on, `loc` properties holding objects with
  17276. // `start` and `end` properties in `{line, column}` form (with
  17277. // line being 1-based and column 0-based) will be attached to the
  17278. // nodes.
  17279. locations: false,
  17280. // A function can be passed as `onToken` option, which will
  17281. // cause Acorn to call that function with object in the same
  17282. // format as tokens returned from `tokenizer().getToken()`. Note
  17283. // that you are not allowed to call the parser from the
  17284. // callback—that will corrupt its internal state.
  17285. onToken: null,
  17286. // A function can be passed as `onComment` option, which will
  17287. // cause Acorn to call that function with `(block, text, start,
  17288. // end)` parameters whenever a comment is skipped. `block` is a
  17289. // boolean indicating whether this is a block (`/* */`) comment,
  17290. // `text` is the content of the comment, and `start` and `end` are
  17291. // character offsets that denote the start and end of the comment.
  17292. // When the `locations` option is on, two more parameters are
  17293. // passed, the full `{line, column}` locations of the start and
  17294. // end of the comments. Note that you are not allowed to call the
  17295. // parser from the callback—that will corrupt its internal state.
  17296. onComment: null,
  17297. // Nodes have their start and end characters offsets recorded in
  17298. // `start` and `end` properties (directly on the node, rather than
  17299. // the `loc` object, which holds line/column data. To also add a
  17300. // [semi-standardized][range] `range` property holding a `[start,
  17301. // end]` array with the same numbers, set the `ranges` option to
  17302. // `true`.
  17303. //
  17304. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  17305. ranges: false,
  17306. // It is possible to parse multiple files into a single AST by
  17307. // passing the tree produced by parsing the first file as
  17308. // `program` option in subsequent parses. This will add the
  17309. // toplevel forms of the parsed file to the `Program` (top) node
  17310. // of an existing parse tree.
  17311. program: null,
  17312. // When `locations` is on, you can pass this to record the source
  17313. // file in every node's `loc` object.
  17314. sourceFile: null,
  17315. // This value, if given, is stored in every node, whether
  17316. // `locations` is on or off.
  17317. directSourceFile: null,
  17318. // When enabled, parenthesized expressions are represented by
  17319. // (non-standard) ParenthesizedExpression nodes
  17320. preserveParens: false
  17321. };
  17322. // Interpret and default an options object
  17323. var warnedAboutEcmaVersion = false;
  17324. function getOptions(opts) {
  17325. var options = {};
  17326. for (var opt in defaultOptions)
  17327. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  17328. if (options.ecmaVersion === "latest") {
  17329. options.ecmaVersion = 1e8;
  17330. } else if (options.ecmaVersion == null) {
  17331. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  17332. warnedAboutEcmaVersion = true;
  17333. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  17334. }
  17335. options.ecmaVersion = 11;
  17336. } else if (options.ecmaVersion >= 2015) {
  17337. options.ecmaVersion -= 2009;
  17338. }
  17339. if (options.allowReserved == null)
  17340. { options.allowReserved = options.ecmaVersion < 5; }
  17341. if (opts.allowHashBang == null)
  17342. { options.allowHashBang = options.ecmaVersion >= 14; }
  17343. if (isArray(options.onToken)) {
  17344. var tokens = options.onToken;
  17345. options.onToken = function (token) { return tokens.push(token); };
  17346. }
  17347. if (isArray(options.onComment))
  17348. { options.onComment = pushComment(options, options.onComment); }
  17349. return options
  17350. }
  17351. function pushComment(options, array) {
  17352. return function(block, text, start, end, startLoc, endLoc) {
  17353. var comment = {
  17354. type: block ? "Block" : "Line",
  17355. value: text,
  17356. start: start,
  17357. end: end
  17358. };
  17359. if (options.locations)
  17360. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  17361. if (options.ranges)
  17362. { comment.range = [start, end]; }
  17363. array.push(comment);
  17364. }
  17365. }
  17366. // Each scope gets a bitset that may contain these flags
  17367. var
  17368. SCOPE_TOP = 1,
  17369. SCOPE_FUNCTION = 2,
  17370. SCOPE_ASYNC = 4,
  17371. SCOPE_GENERATOR = 8,
  17372. SCOPE_ARROW = 16,
  17373. SCOPE_SIMPLE_CATCH = 32,
  17374. SCOPE_SUPER = 64,
  17375. SCOPE_DIRECT_SUPER = 128,
  17376. SCOPE_CLASS_STATIC_BLOCK = 256,
  17377. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  17378. function functionFlags(async, generator) {
  17379. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  17380. }
  17381. // Used in checkLVal* and declareName to determine the type of a binding
  17382. var
  17383. BIND_NONE = 0, // Not a binding
  17384. BIND_VAR = 1, // Var-style binding
  17385. BIND_LEXICAL = 2, // Let- or const-style binding
  17386. BIND_FUNCTION = 3, // Function declaration
  17387. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  17388. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  17389. var Parser = function Parser(options, input, startPos) {
  17390. this.options = options = getOptions(options);
  17391. this.sourceFile = options.sourceFile;
  17392. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  17393. var reserved = "";
  17394. if (options.allowReserved !== true) {
  17395. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  17396. if (options.sourceType === "module") { reserved += " await"; }
  17397. }
  17398. this.reservedWords = wordsRegexp(reserved);
  17399. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  17400. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  17401. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  17402. this.input = String(input);
  17403. // Used to signal to callers of `readWord1` whether the word
  17404. // contained any escape sequences. This is needed because words with
  17405. // escape sequences must not be interpreted as keywords.
  17406. this.containsEsc = false;
  17407. // Set up token state
  17408. // The current position of the tokenizer in the input.
  17409. if (startPos) {
  17410. this.pos = startPos;
  17411. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  17412. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  17413. } else {
  17414. this.pos = this.lineStart = 0;
  17415. this.curLine = 1;
  17416. }
  17417. // Properties of the current token:
  17418. // Its type
  17419. this.type = types$1.eof;
  17420. // For tokens that include more information than their type, the value
  17421. this.value = null;
  17422. // Its start and end offset
  17423. this.start = this.end = this.pos;
  17424. // And, if locations are used, the {line, column} object
  17425. // corresponding to those offsets
  17426. this.startLoc = this.endLoc = this.curPosition();
  17427. // Position information for the previous token
  17428. this.lastTokEndLoc = this.lastTokStartLoc = null;
  17429. this.lastTokStart = this.lastTokEnd = this.pos;
  17430. // The context stack is used to superficially track syntactic
  17431. // context to predict whether a regular expression is allowed in a
  17432. // given position.
  17433. this.context = this.initialContext();
  17434. this.exprAllowed = true;
  17435. // Figure out if it's a module code.
  17436. this.inModule = options.sourceType === "module";
  17437. this.strict = this.inModule || this.strictDirective(this.pos);
  17438. // Used to signify the start of a potential arrow function
  17439. this.potentialArrowAt = -1;
  17440. this.potentialArrowInForAwait = false;
  17441. // Positions to delayed-check that yield/await does not exist in default parameters.
  17442. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  17443. // Labels in scope.
  17444. this.labels = [];
  17445. // Thus-far undefined exports.
  17446. this.undefinedExports = Object.create(null);
  17447. // If enabled, skip leading hashbang line.
  17448. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  17449. { this.skipLineComment(2); }
  17450. // Scope tracking for duplicate variable names (see scope.js)
  17451. this.scopeStack = [];
  17452. this.enterScope(SCOPE_TOP);
  17453. // For RegExp validation
  17454. this.regexpState = null;
  17455. // The stack of private names.
  17456. // Each element has two properties: 'declared' and 'used'.
  17457. // When it exited from the outermost class definition, all used private names must be declared.
  17458. this.privateNameStack = [];
  17459. };
  17460. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };
  17461. Parser.prototype.parse = function parse () {
  17462. var node = this.options.program || this.startNode();
  17463. this.nextToken();
  17464. return this.parseTopLevel(node)
  17465. };
  17466. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  17467. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  17468. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  17469. prototypeAccessors.canAwait.get = function () {
  17470. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  17471. var scope = this.scopeStack[i];
  17472. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  17473. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  17474. }
  17475. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  17476. };
  17477. prototypeAccessors.allowSuper.get = function () {
  17478. var ref = this.currentThisScope();
  17479. var flags = ref.flags;
  17480. var inClassFieldInit = ref.inClassFieldInit;
  17481. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  17482. };
  17483. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  17484. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  17485. prototypeAccessors.allowNewDotTarget.get = function () {
  17486. var ref = this.currentThisScope();
  17487. var flags = ref.flags;
  17488. var inClassFieldInit = ref.inClassFieldInit;
  17489. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  17490. };
  17491. prototypeAccessors.inClassStaticBlock.get = function () {
  17492. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  17493. };
  17494. Parser.extend = function extend () {
  17495. var plugins = [], len = arguments.length;
  17496. while ( len-- ) plugins[ len ] = arguments[ len ];
  17497. var cls = this;
  17498. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  17499. return cls
  17500. };
  17501. Parser.parse = function parse (input, options) {
  17502. return new this(options, input).parse()
  17503. };
  17504. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  17505. var parser = new this(options, input, pos);
  17506. parser.nextToken();
  17507. return parser.parseExpression()
  17508. };
  17509. Parser.tokenizer = function tokenizer (input, options) {
  17510. return new this(options, input)
  17511. };
  17512. Object.defineProperties( Parser.prototype, prototypeAccessors );
  17513. var pp$9 = Parser.prototype;
  17514. // ## Parser utilities
  17515. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  17516. pp$9.strictDirective = function(start) {
  17517. if (this.options.ecmaVersion < 5) { return false }
  17518. for (;;) {
  17519. // Try to find string literal.
  17520. skipWhiteSpace.lastIndex = start;
  17521. start += skipWhiteSpace.exec(this.input)[0].length;
  17522. var match = literal.exec(this.input.slice(start));
  17523. if (!match) { return false }
  17524. if ((match[1] || match[2]) === "use strict") {
  17525. skipWhiteSpace.lastIndex = start + match[0].length;
  17526. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  17527. var next = this.input.charAt(end);
  17528. return next === ";" || next === "}" ||
  17529. (lineBreak.test(spaceAfter[0]) &&
  17530. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  17531. }
  17532. start += match[0].length;
  17533. // Skip semicolon, if any.
  17534. skipWhiteSpace.lastIndex = start;
  17535. start += skipWhiteSpace.exec(this.input)[0].length;
  17536. if (this.input[start] === ";")
  17537. { start++; }
  17538. }
  17539. };
  17540. // Predicate that tests whether the next token is of the given
  17541. // type, and if yes, consumes it as a side effect.
  17542. pp$9.eat = function(type) {
  17543. if (this.type === type) {
  17544. this.next();
  17545. return true
  17546. } else {
  17547. return false
  17548. }
  17549. };
  17550. // Tests whether parsed token is a contextual keyword.
  17551. pp$9.isContextual = function(name) {
  17552. return this.type === types$1.name && this.value === name && !this.containsEsc
  17553. };
  17554. // Consumes contextual keyword if possible.
  17555. pp$9.eatContextual = function(name) {
  17556. if (!this.isContextual(name)) { return false }
  17557. this.next();
  17558. return true
  17559. };
  17560. // Asserts that following token is given contextual keyword.
  17561. pp$9.expectContextual = function(name) {
  17562. if (!this.eatContextual(name)) { this.unexpected(); }
  17563. };
  17564. // Test whether a semicolon can be inserted at the current position.
  17565. pp$9.canInsertSemicolon = function() {
  17566. return this.type === types$1.eof ||
  17567. this.type === types$1.braceR ||
  17568. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  17569. };
  17570. pp$9.insertSemicolon = function() {
  17571. if (this.canInsertSemicolon()) {
  17572. if (this.options.onInsertedSemicolon)
  17573. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  17574. return true
  17575. }
  17576. };
  17577. // Consume a semicolon, or, failing that, see if we are allowed to
  17578. // pretend that there is a semicolon at this position.
  17579. pp$9.semicolon = function() {
  17580. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  17581. };
  17582. pp$9.afterTrailingComma = function(tokType, notNext) {
  17583. if (this.type === tokType) {
  17584. if (this.options.onTrailingComma)
  17585. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  17586. if (!notNext)
  17587. { this.next(); }
  17588. return true
  17589. }
  17590. };
  17591. // Expect a token of a given type. If found, consume it, otherwise,
  17592. // raise an unexpected token error.
  17593. pp$9.expect = function(type) {
  17594. this.eat(type) || this.unexpected();
  17595. };
  17596. // Raise an unexpected token error.
  17597. pp$9.unexpected = function(pos) {
  17598. this.raise(pos != null ? pos : this.start, "Unexpected token");
  17599. };
  17600. var DestructuringErrors = function DestructuringErrors() {
  17601. this.shorthandAssign =
  17602. this.trailingComma =
  17603. this.parenthesizedAssign =
  17604. this.parenthesizedBind =
  17605. this.doubleProto =
  17606. -1;
  17607. };
  17608. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  17609. if (!refDestructuringErrors) { return }
  17610. if (refDestructuringErrors.trailingComma > -1)
  17611. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  17612. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  17613. if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
  17614. };
  17615. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  17616. if (!refDestructuringErrors) { return false }
  17617. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  17618. var doubleProto = refDestructuringErrors.doubleProto;
  17619. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  17620. if (shorthandAssign >= 0)
  17621. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  17622. if (doubleProto >= 0)
  17623. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  17624. };
  17625. pp$9.checkYieldAwaitInDefaultParams = function() {
  17626. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  17627. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  17628. if (this.awaitPos)
  17629. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  17630. };
  17631. pp$9.isSimpleAssignTarget = function(expr) {
  17632. if (expr.type === "ParenthesizedExpression")
  17633. { return this.isSimpleAssignTarget(expr.expression) }
  17634. return expr.type === "Identifier" || expr.type === "MemberExpression"
  17635. };
  17636. var pp$8 = Parser.prototype;
  17637. // ### Statement parsing
  17638. // Parse a program. Initializes the parser, reads any number of
  17639. // statements, and wraps them in a Program node. Optionally takes a
  17640. // `program` argument. If present, the statements will be appended
  17641. // to its body instead of creating a new node.
  17642. pp$8.parseTopLevel = function(node) {
  17643. var exports = Object.create(null);
  17644. if (!node.body) { node.body = []; }
  17645. while (this.type !== types$1.eof) {
  17646. var stmt = this.parseStatement(null, true, exports);
  17647. node.body.push(stmt);
  17648. }
  17649. if (this.inModule)
  17650. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  17651. {
  17652. var name = list[i];
  17653. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  17654. } }
  17655. this.adaptDirectivePrologue(node.body);
  17656. this.next();
  17657. node.sourceType = this.options.sourceType;
  17658. return this.finishNode(node, "Program")
  17659. };
  17660. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  17661. pp$8.isLet = function(context) {
  17662. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  17663. skipWhiteSpace.lastIndex = this.pos;
  17664. var skip = skipWhiteSpace.exec(this.input);
  17665. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  17666. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  17667. // Statement) is allowed here. If context is not empty then only a Statement
  17668. // is allowed. However, `let [` is an explicit negative lookahead for
  17669. // ExpressionStatement, so special-case it first.
  17670. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
  17671. if (context) { return false }
  17672. if (nextCh === 123) { return true } // '{'
  17673. if (isIdentifierStart(nextCh, true)) {
  17674. var pos = next + 1;
  17675. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  17676. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  17677. var ident = this.input.slice(next, pos);
  17678. if (!keywordRelationalOperator.test(ident)) { return true }
  17679. }
  17680. return false
  17681. };
  17682. // check 'async [no LineTerminator here] function'
  17683. // - 'async /*foo*/ function' is OK.
  17684. // - 'async /*\n*/ function' is invalid.
  17685. pp$8.isAsyncFunction = function() {
  17686. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  17687. { return false }
  17688. skipWhiteSpace.lastIndex = this.pos;
  17689. var skip = skipWhiteSpace.exec(this.input);
  17690. var next = this.pos + skip[0].length, after;
  17691. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  17692. this.input.slice(next, next + 8) === "function" &&
  17693. (next + 8 === this.input.length ||
  17694. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  17695. };
  17696. // Parse a single statement.
  17697. //
  17698. // If expecting a statement and finding a slash operator, parse a
  17699. // regular expression literal. This is to handle cases like
  17700. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  17701. // does not help.
  17702. pp$8.parseStatement = function(context, topLevel, exports) {
  17703. var starttype = this.type, node = this.startNode(), kind;
  17704. if (this.isLet(context)) {
  17705. starttype = types$1._var;
  17706. kind = "let";
  17707. }
  17708. // Most types of statements are recognized by the keyword they
  17709. // start with. Many are trivial to parse, some require a bit of
  17710. // complexity.
  17711. switch (starttype) {
  17712. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  17713. case types$1._debugger: return this.parseDebuggerStatement(node)
  17714. case types$1._do: return this.parseDoStatement(node)
  17715. case types$1._for: return this.parseForStatement(node)
  17716. case types$1._function:
  17717. // Function as sole body of either an if statement or a labeled statement
  17718. // works, but not when it is part of a labeled statement that is the sole
  17719. // body of an if statement.
  17720. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  17721. return this.parseFunctionStatement(node, false, !context)
  17722. case types$1._class:
  17723. if (context) { this.unexpected(); }
  17724. return this.parseClass(node, true)
  17725. case types$1._if: return this.parseIfStatement(node)
  17726. case types$1._return: return this.parseReturnStatement(node)
  17727. case types$1._switch: return this.parseSwitchStatement(node)
  17728. case types$1._throw: return this.parseThrowStatement(node)
  17729. case types$1._try: return this.parseTryStatement(node)
  17730. case types$1._const: case types$1._var:
  17731. kind = kind || this.value;
  17732. if (context && kind !== "var") { this.unexpected(); }
  17733. return this.parseVarStatement(node, kind)
  17734. case types$1._while: return this.parseWhileStatement(node)
  17735. case types$1._with: return this.parseWithStatement(node)
  17736. case types$1.braceL: return this.parseBlock(true, node)
  17737. case types$1.semi: return this.parseEmptyStatement(node)
  17738. case types$1._export:
  17739. case types$1._import:
  17740. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  17741. skipWhiteSpace.lastIndex = this.pos;
  17742. var skip = skipWhiteSpace.exec(this.input);
  17743. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  17744. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  17745. { return this.parseExpressionStatement(node, this.parseExpression()) }
  17746. }
  17747. if (!this.options.allowImportExportEverywhere) {
  17748. if (!topLevel)
  17749. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  17750. if (!this.inModule)
  17751. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  17752. }
  17753. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  17754. // If the statement does not start with a statement keyword or a
  17755. // brace, it's an ExpressionStatement or LabeledStatement. We
  17756. // simply start parsing an expression, and afterwards, if the
  17757. // next token is a colon and the expression was a simple
  17758. // Identifier node, we switch to interpreting it as a label.
  17759. default:
  17760. if (this.isAsyncFunction()) {
  17761. if (context) { this.unexpected(); }
  17762. this.next();
  17763. return this.parseFunctionStatement(node, true, !context)
  17764. }
  17765. var maybeName = this.value, expr = this.parseExpression();
  17766. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  17767. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  17768. else { return this.parseExpressionStatement(node, expr) }
  17769. }
  17770. };
  17771. pp$8.parseBreakContinueStatement = function(node, keyword) {
  17772. var isBreak = keyword === "break";
  17773. this.next();
  17774. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  17775. else if (this.type !== types$1.name) { this.unexpected(); }
  17776. else {
  17777. node.label = this.parseIdent();
  17778. this.semicolon();
  17779. }
  17780. // Verify that there is an actual destination to break or
  17781. // continue to.
  17782. var i = 0;
  17783. for (; i < this.labels.length; ++i) {
  17784. var lab = this.labels[i];
  17785. if (node.label == null || lab.name === node.label.name) {
  17786. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  17787. if (node.label && isBreak) { break }
  17788. }
  17789. }
  17790. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  17791. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  17792. };
  17793. pp$8.parseDebuggerStatement = function(node) {
  17794. this.next();
  17795. this.semicolon();
  17796. return this.finishNode(node, "DebuggerStatement")
  17797. };
  17798. pp$8.parseDoStatement = function(node) {
  17799. this.next();
  17800. this.labels.push(loopLabel);
  17801. node.body = this.parseStatement("do");
  17802. this.labels.pop();
  17803. this.expect(types$1._while);
  17804. node.test = this.parseParenExpression();
  17805. if (this.options.ecmaVersion >= 6)
  17806. { this.eat(types$1.semi); }
  17807. else
  17808. { this.semicolon(); }
  17809. return this.finishNode(node, "DoWhileStatement")
  17810. };
  17811. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  17812. // loop is non-trivial. Basically, we have to parse the init `var`
  17813. // statement or expression, disallowing the `in` operator (see
  17814. // the second parameter to `parseExpression`), and then check
  17815. // whether the next token is `in` or `of`. When there is no init
  17816. // part (semicolon immediately after the opening parenthesis), it
  17817. // is a regular `for` loop.
  17818. pp$8.parseForStatement = function(node) {
  17819. this.next();
  17820. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  17821. this.labels.push(loopLabel);
  17822. this.enterScope(0);
  17823. this.expect(types$1.parenL);
  17824. if (this.type === types$1.semi) {
  17825. if (awaitAt > -1) { this.unexpected(awaitAt); }
  17826. return this.parseFor(node, null)
  17827. }
  17828. var isLet = this.isLet();
  17829. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  17830. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  17831. this.next();
  17832. this.parseVar(init$1, true, kind);
  17833. this.finishNode(init$1, "VariableDeclaration");
  17834. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  17835. if (this.options.ecmaVersion >= 9) {
  17836. if (this.type === types$1._in) {
  17837. if (awaitAt > -1) { this.unexpected(awaitAt); }
  17838. } else { node.await = awaitAt > -1; }
  17839. }
  17840. return this.parseForIn(node, init$1)
  17841. }
  17842. if (awaitAt > -1) { this.unexpected(awaitAt); }
  17843. return this.parseFor(node, init$1)
  17844. }
  17845. var startsWithLet = this.isContextual("let"), isForOf = false;
  17846. var refDestructuringErrors = new DestructuringErrors;
  17847. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  17848. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  17849. if (this.options.ecmaVersion >= 9) {
  17850. if (this.type === types$1._in) {
  17851. if (awaitAt > -1) { this.unexpected(awaitAt); }
  17852. } else { node.await = awaitAt > -1; }
  17853. }
  17854. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  17855. this.toAssignable(init, false, refDestructuringErrors);
  17856. this.checkLValPattern(init);
  17857. return this.parseForIn(node, init)
  17858. } else {
  17859. this.checkExpressionErrors(refDestructuringErrors, true);
  17860. }
  17861. if (awaitAt > -1) { this.unexpected(awaitAt); }
  17862. return this.parseFor(node, init)
  17863. };
  17864. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  17865. this.next();
  17866. return this.parseFunction(node, FUNC_STATEMENT$1 | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  17867. };
  17868. pp$8.parseIfStatement = function(node) {
  17869. this.next();
  17870. node.test = this.parseParenExpression();
  17871. // allow function declarations in branches, but only in non-strict mode
  17872. node.consequent = this.parseStatement("if");
  17873. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  17874. return this.finishNode(node, "IfStatement")
  17875. };
  17876. pp$8.parseReturnStatement = function(node) {
  17877. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  17878. { this.raise(this.start, "'return' outside of function"); }
  17879. this.next();
  17880. // In `return` (and `break`/`continue`), the keywords with
  17881. // optional arguments, we eagerly look for a semicolon or the
  17882. // possibility to insert one.
  17883. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  17884. else { node.argument = this.parseExpression(); this.semicolon(); }
  17885. return this.finishNode(node, "ReturnStatement")
  17886. };
  17887. pp$8.parseSwitchStatement = function(node) {
  17888. this.next();
  17889. node.discriminant = this.parseParenExpression();
  17890. node.cases = [];
  17891. this.expect(types$1.braceL);
  17892. this.labels.push(switchLabel);
  17893. this.enterScope(0);
  17894. // Statements under must be grouped (by label) in SwitchCase
  17895. // nodes. `cur` is used to keep the node that we are currently
  17896. // adding statements to.
  17897. var cur;
  17898. for (var sawDefault = false; this.type !== types$1.braceR;) {
  17899. if (this.type === types$1._case || this.type === types$1._default) {
  17900. var isCase = this.type === types$1._case;
  17901. if (cur) { this.finishNode(cur, "SwitchCase"); }
  17902. node.cases.push(cur = this.startNode());
  17903. cur.consequent = [];
  17904. this.next();
  17905. if (isCase) {
  17906. cur.test = this.parseExpression();
  17907. } else {
  17908. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  17909. sawDefault = true;
  17910. cur.test = null;
  17911. }
  17912. this.expect(types$1.colon);
  17913. } else {
  17914. if (!cur) { this.unexpected(); }
  17915. cur.consequent.push(this.parseStatement(null));
  17916. }
  17917. }
  17918. this.exitScope();
  17919. if (cur) { this.finishNode(cur, "SwitchCase"); }
  17920. this.next(); // Closing brace
  17921. this.labels.pop();
  17922. return this.finishNode(node, "SwitchStatement")
  17923. };
  17924. pp$8.parseThrowStatement = function(node) {
  17925. this.next();
  17926. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  17927. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  17928. node.argument = this.parseExpression();
  17929. this.semicolon();
  17930. return this.finishNode(node, "ThrowStatement")
  17931. };
  17932. // Reused empty array added for node fields that are always empty.
  17933. var empty$1 = [];
  17934. pp$8.parseTryStatement = function(node) {
  17935. this.next();
  17936. node.block = this.parseBlock();
  17937. node.handler = null;
  17938. if (this.type === types$1._catch) {
  17939. var clause = this.startNode();
  17940. this.next();
  17941. if (this.eat(types$1.parenL)) {
  17942. clause.param = this.parseBindingAtom();
  17943. var simple = clause.param.type === "Identifier";
  17944. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  17945. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  17946. this.expect(types$1.parenR);
  17947. } else {
  17948. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  17949. clause.param = null;
  17950. this.enterScope(0);
  17951. }
  17952. clause.body = this.parseBlock(false);
  17953. this.exitScope();
  17954. node.handler = this.finishNode(clause, "CatchClause");
  17955. }
  17956. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  17957. if (!node.handler && !node.finalizer)
  17958. { this.raise(node.start, "Missing catch or finally clause"); }
  17959. return this.finishNode(node, "TryStatement")
  17960. };
  17961. pp$8.parseVarStatement = function(node, kind) {
  17962. this.next();
  17963. this.parseVar(node, false, kind);
  17964. this.semicolon();
  17965. return this.finishNode(node, "VariableDeclaration")
  17966. };
  17967. pp$8.parseWhileStatement = function(node) {
  17968. this.next();
  17969. node.test = this.parseParenExpression();
  17970. this.labels.push(loopLabel);
  17971. node.body = this.parseStatement("while");
  17972. this.labels.pop();
  17973. return this.finishNode(node, "WhileStatement")
  17974. };
  17975. pp$8.parseWithStatement = function(node) {
  17976. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  17977. this.next();
  17978. node.object = this.parseParenExpression();
  17979. node.body = this.parseStatement("with");
  17980. return this.finishNode(node, "WithStatement")
  17981. };
  17982. pp$8.parseEmptyStatement = function(node) {
  17983. this.next();
  17984. return this.finishNode(node, "EmptyStatement")
  17985. };
  17986. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  17987. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  17988. {
  17989. var label = list[i$1];
  17990. if (label.name === maybeName)
  17991. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  17992. } }
  17993. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  17994. for (var i = this.labels.length - 1; i >= 0; i--) {
  17995. var label$1 = this.labels[i];
  17996. if (label$1.statementStart === node.start) {
  17997. // Update information about previous labels on this node
  17998. label$1.statementStart = this.start;
  17999. label$1.kind = kind;
  18000. } else { break }
  18001. }
  18002. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  18003. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  18004. this.labels.pop();
  18005. node.label = expr;
  18006. return this.finishNode(node, "LabeledStatement")
  18007. };
  18008. pp$8.parseExpressionStatement = function(node, expr) {
  18009. node.expression = expr;
  18010. this.semicolon();
  18011. return this.finishNode(node, "ExpressionStatement")
  18012. };
  18013. // Parse a semicolon-enclosed block of statements, handling `"use
  18014. // strict"` declarations when `allowStrict` is true (used for
  18015. // function bodies).
  18016. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  18017. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  18018. if ( node === void 0 ) node = this.startNode();
  18019. node.body = [];
  18020. this.expect(types$1.braceL);
  18021. if (createNewLexicalScope) { this.enterScope(0); }
  18022. while (this.type !== types$1.braceR) {
  18023. var stmt = this.parseStatement(null);
  18024. node.body.push(stmt);
  18025. }
  18026. if (exitStrict) { this.strict = false; }
  18027. this.next();
  18028. if (createNewLexicalScope) { this.exitScope(); }
  18029. return this.finishNode(node, "BlockStatement")
  18030. };
  18031. // Parse a regular `for` loop. The disambiguation code in
  18032. // `parseStatement` will already have parsed the init statement or
  18033. // expression.
  18034. pp$8.parseFor = function(node, init) {
  18035. node.init = init;
  18036. this.expect(types$1.semi);
  18037. node.test = this.type === types$1.semi ? null : this.parseExpression();
  18038. this.expect(types$1.semi);
  18039. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  18040. this.expect(types$1.parenR);
  18041. node.body = this.parseStatement("for");
  18042. this.exitScope();
  18043. this.labels.pop();
  18044. return this.finishNode(node, "ForStatement")
  18045. };
  18046. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  18047. // same from parser's perspective.
  18048. pp$8.parseForIn = function(node, init) {
  18049. var isForIn = this.type === types$1._in;
  18050. this.next();
  18051. if (
  18052. init.type === "VariableDeclaration" &&
  18053. init.declarations[0].init != null &&
  18054. (
  18055. !isForIn ||
  18056. this.options.ecmaVersion < 8 ||
  18057. this.strict ||
  18058. init.kind !== "var" ||
  18059. init.declarations[0].id.type !== "Identifier"
  18060. )
  18061. ) {
  18062. this.raise(
  18063. init.start,
  18064. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  18065. );
  18066. }
  18067. node.left = init;
  18068. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  18069. this.expect(types$1.parenR);
  18070. node.body = this.parseStatement("for");
  18071. this.exitScope();
  18072. this.labels.pop();
  18073. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  18074. };
  18075. // Parse a list of variable declarations.
  18076. pp$8.parseVar = function(node, isFor, kind) {
  18077. node.declarations = [];
  18078. node.kind = kind;
  18079. for (;;) {
  18080. var decl = this.startNode();
  18081. this.parseVarId(decl, kind);
  18082. if (this.eat(types$1.eq)) {
  18083. decl.init = this.parseMaybeAssign(isFor);
  18084. } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  18085. this.unexpected();
  18086. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  18087. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  18088. } else {
  18089. decl.init = null;
  18090. }
  18091. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  18092. if (!this.eat(types$1.comma)) { break }
  18093. }
  18094. return node
  18095. };
  18096. pp$8.parseVarId = function(decl, kind) {
  18097. decl.id = this.parseBindingAtom();
  18098. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  18099. };
  18100. var FUNC_STATEMENT$1 = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID$1 = 4;
  18101. // Parse a function declaration or literal (depending on the
  18102. // `statement & FUNC_STATEMENT`).
  18103. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  18104. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  18105. this.initFunction(node);
  18106. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  18107. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  18108. { this.unexpected(); }
  18109. node.generator = this.eat(types$1.star);
  18110. }
  18111. if (this.options.ecmaVersion >= 8)
  18112. { node.async = !!isAsync; }
  18113. if (statement & FUNC_STATEMENT$1) {
  18114. node.id = (statement & FUNC_NULLABLE_ID$1) && this.type !== types$1.name ? null : this.parseIdent();
  18115. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  18116. // If it is a regular function declaration in sloppy mode, then it is
  18117. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  18118. // mode depends on properties of the current scope (see
  18119. // treatFunctionsAsVar).
  18120. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  18121. }
  18122. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  18123. this.yieldPos = 0;
  18124. this.awaitPos = 0;
  18125. this.awaitIdentPos = 0;
  18126. this.enterScope(functionFlags(node.async, node.generator));
  18127. if (!(statement & FUNC_STATEMENT$1))
  18128. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  18129. this.parseFunctionParams(node);
  18130. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  18131. this.yieldPos = oldYieldPos;
  18132. this.awaitPos = oldAwaitPos;
  18133. this.awaitIdentPos = oldAwaitIdentPos;
  18134. return this.finishNode(node, (statement & FUNC_STATEMENT$1) ? "FunctionDeclaration" : "FunctionExpression")
  18135. };
  18136. pp$8.parseFunctionParams = function(node) {
  18137. this.expect(types$1.parenL);
  18138. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  18139. this.checkYieldAwaitInDefaultParams();
  18140. };
  18141. // Parse a class declaration or literal (depending on the
  18142. // `isStatement` parameter).
  18143. pp$8.parseClass = function(node, isStatement) {
  18144. this.next();
  18145. // ecma-262 14.6 Class Definitions
  18146. // A class definition is always strict mode code.
  18147. var oldStrict = this.strict;
  18148. this.strict = true;
  18149. this.parseClassId(node, isStatement);
  18150. this.parseClassSuper(node);
  18151. var privateNameMap = this.enterClassBody();
  18152. var classBody = this.startNode();
  18153. var hadConstructor = false;
  18154. classBody.body = [];
  18155. this.expect(types$1.braceL);
  18156. while (this.type !== types$1.braceR) {
  18157. var element = this.parseClassElement(node.superClass !== null);
  18158. if (element) {
  18159. classBody.body.push(element);
  18160. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  18161. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  18162. hadConstructor = true;
  18163. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  18164. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  18165. }
  18166. }
  18167. }
  18168. this.strict = oldStrict;
  18169. this.next();
  18170. node.body = this.finishNode(classBody, "ClassBody");
  18171. this.exitClassBody();
  18172. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  18173. };
  18174. pp$8.parseClassElement = function(constructorAllowsSuper) {
  18175. if (this.eat(types$1.semi)) { return null }
  18176. var ecmaVersion = this.options.ecmaVersion;
  18177. var node = this.startNode();
  18178. var keyName = "";
  18179. var isGenerator = false;
  18180. var isAsync = false;
  18181. var kind = "method";
  18182. var isStatic = false;
  18183. if (this.eatContextual("static")) {
  18184. // Parse static init block
  18185. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  18186. this.parseClassStaticBlock(node);
  18187. return node
  18188. }
  18189. if (this.isClassElementNameStart() || this.type === types$1.star) {
  18190. isStatic = true;
  18191. } else {
  18192. keyName = "static";
  18193. }
  18194. }
  18195. node.static = isStatic;
  18196. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  18197. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  18198. isAsync = true;
  18199. } else {
  18200. keyName = "async";
  18201. }
  18202. }
  18203. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  18204. isGenerator = true;
  18205. }
  18206. if (!keyName && !isAsync && !isGenerator) {
  18207. var lastValue = this.value;
  18208. if (this.eatContextual("get") || this.eatContextual("set")) {
  18209. if (this.isClassElementNameStart()) {
  18210. kind = lastValue;
  18211. } else {
  18212. keyName = lastValue;
  18213. }
  18214. }
  18215. }
  18216. // Parse element name
  18217. if (keyName) {
  18218. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  18219. // The last token is any of those. Make it the element name.
  18220. node.computed = false;
  18221. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  18222. node.key.name = keyName;
  18223. this.finishNode(node.key, "Identifier");
  18224. } else {
  18225. this.parseClassElementName(node);
  18226. }
  18227. // Parse element value
  18228. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  18229. var isConstructor = !node.static && checkKeyName(node, "constructor");
  18230. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  18231. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  18232. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  18233. node.kind = isConstructor ? "constructor" : kind;
  18234. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  18235. } else {
  18236. this.parseClassField(node);
  18237. }
  18238. return node
  18239. };
  18240. pp$8.isClassElementNameStart = function() {
  18241. return (
  18242. this.type === types$1.name ||
  18243. this.type === types$1.privateId ||
  18244. this.type === types$1.num ||
  18245. this.type === types$1.string ||
  18246. this.type === types$1.bracketL ||
  18247. this.type.keyword
  18248. )
  18249. };
  18250. pp$8.parseClassElementName = function(element) {
  18251. if (this.type === types$1.privateId) {
  18252. if (this.value === "constructor") {
  18253. this.raise(this.start, "Classes can't have an element named '#constructor'");
  18254. }
  18255. element.computed = false;
  18256. element.key = this.parsePrivateIdent();
  18257. } else {
  18258. this.parsePropertyName(element);
  18259. }
  18260. };
  18261. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  18262. // Check key and flags
  18263. var key = method.key;
  18264. if (method.kind === "constructor") {
  18265. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  18266. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  18267. } else if (method.static && checkKeyName(method, "prototype")) {
  18268. this.raise(key.start, "Classes may not have a static property named prototype");
  18269. }
  18270. // Parse value
  18271. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  18272. // Check value
  18273. if (method.kind === "get" && value.params.length !== 0)
  18274. { this.raiseRecoverable(value.start, "getter should have no params"); }
  18275. if (method.kind === "set" && value.params.length !== 1)
  18276. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  18277. if (method.kind === "set" && value.params[0].type === "RestElement")
  18278. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  18279. return this.finishNode(method, "MethodDefinition")
  18280. };
  18281. pp$8.parseClassField = function(field) {
  18282. if (checkKeyName(field, "constructor")) {
  18283. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  18284. } else if (field.static && checkKeyName(field, "prototype")) {
  18285. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  18286. }
  18287. if (this.eat(types$1.eq)) {
  18288. // To raise SyntaxError if 'arguments' exists in the initializer.
  18289. var scope = this.currentThisScope();
  18290. var inClassFieldInit = scope.inClassFieldInit;
  18291. scope.inClassFieldInit = true;
  18292. field.value = this.parseMaybeAssign();
  18293. scope.inClassFieldInit = inClassFieldInit;
  18294. } else {
  18295. field.value = null;
  18296. }
  18297. this.semicolon();
  18298. return this.finishNode(field, "PropertyDefinition")
  18299. };
  18300. pp$8.parseClassStaticBlock = function(node) {
  18301. node.body = [];
  18302. var oldLabels = this.labels;
  18303. this.labels = [];
  18304. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  18305. while (this.type !== types$1.braceR) {
  18306. var stmt = this.parseStatement(null);
  18307. node.body.push(stmt);
  18308. }
  18309. this.next();
  18310. this.exitScope();
  18311. this.labels = oldLabels;
  18312. return this.finishNode(node, "StaticBlock")
  18313. };
  18314. pp$8.parseClassId = function(node, isStatement) {
  18315. if (this.type === types$1.name) {
  18316. node.id = this.parseIdent();
  18317. if (isStatement)
  18318. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  18319. } else {
  18320. if (isStatement === true)
  18321. { this.unexpected(); }
  18322. node.id = null;
  18323. }
  18324. };
  18325. pp$8.parseClassSuper = function(node) {
  18326. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;
  18327. };
  18328. pp$8.enterClassBody = function() {
  18329. var element = {declared: Object.create(null), used: []};
  18330. this.privateNameStack.push(element);
  18331. return element.declared
  18332. };
  18333. pp$8.exitClassBody = function() {
  18334. var ref = this.privateNameStack.pop();
  18335. var declared = ref.declared;
  18336. var used = ref.used;
  18337. var len = this.privateNameStack.length;
  18338. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  18339. for (var i = 0; i < used.length; ++i) {
  18340. var id = used[i];
  18341. if (!hasOwn(declared, id.name)) {
  18342. if (parent) {
  18343. parent.used.push(id);
  18344. } else {
  18345. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  18346. }
  18347. }
  18348. }
  18349. };
  18350. function isPrivateNameConflicted(privateNameMap, element) {
  18351. var name = element.key.name;
  18352. var curr = privateNameMap[name];
  18353. var next = "true";
  18354. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  18355. next = (element.static ? "s" : "i") + element.kind;
  18356. }
  18357. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  18358. if (
  18359. curr === "iget" && next === "iset" ||
  18360. curr === "iset" && next === "iget" ||
  18361. curr === "sget" && next === "sset" ||
  18362. curr === "sset" && next === "sget"
  18363. ) {
  18364. privateNameMap[name] = "true";
  18365. return false
  18366. } else if (!curr) {
  18367. privateNameMap[name] = next;
  18368. return false
  18369. } else {
  18370. return true
  18371. }
  18372. }
  18373. function checkKeyName(node, name) {
  18374. var computed = node.computed;
  18375. var key = node.key;
  18376. return !computed && (
  18377. key.type === "Identifier" && key.name === name ||
  18378. key.type === "Literal" && key.value === name
  18379. )
  18380. }
  18381. // Parses module export declaration.
  18382. pp$8.parseExport = function(node, exports) {
  18383. this.next();
  18384. // export * from '...'
  18385. if (this.eat(types$1.star)) {
  18386. if (this.options.ecmaVersion >= 11) {
  18387. if (this.eatContextual("as")) {
  18388. node.exported = this.parseModuleExportName();
  18389. this.checkExport(exports, node.exported, this.lastTokStart);
  18390. } else {
  18391. node.exported = null;
  18392. }
  18393. }
  18394. this.expectContextual("from");
  18395. if (this.type !== types$1.string) { this.unexpected(); }
  18396. node.source = this.parseExprAtom();
  18397. this.semicolon();
  18398. return this.finishNode(node, "ExportAllDeclaration")
  18399. }
  18400. if (this.eat(types$1._default)) { // export default ...
  18401. this.checkExport(exports, "default", this.lastTokStart);
  18402. var isAsync;
  18403. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  18404. var fNode = this.startNode();
  18405. this.next();
  18406. if (isAsync) { this.next(); }
  18407. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT$1 | FUNC_NULLABLE_ID$1, false, isAsync);
  18408. } else if (this.type === types$1._class) {
  18409. var cNode = this.startNode();
  18410. node.declaration = this.parseClass(cNode, "nullableID");
  18411. } else {
  18412. node.declaration = this.parseMaybeAssign();
  18413. this.semicolon();
  18414. }
  18415. return this.finishNode(node, "ExportDefaultDeclaration")
  18416. }
  18417. // export var|const|let|function|class ...
  18418. if (this.shouldParseExportStatement()) {
  18419. node.declaration = this.parseStatement(null);
  18420. if (node.declaration.type === "VariableDeclaration")
  18421. { this.checkVariableExport(exports, node.declaration.declarations); }
  18422. else
  18423. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  18424. node.specifiers = [];
  18425. node.source = null;
  18426. } else { // export { x, y as z } [from '...']
  18427. node.declaration = null;
  18428. node.specifiers = this.parseExportSpecifiers(exports);
  18429. if (this.eatContextual("from")) {
  18430. if (this.type !== types$1.string) { this.unexpected(); }
  18431. node.source = this.parseExprAtom();
  18432. } else {
  18433. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  18434. // check for keywords used as local names
  18435. var spec = list[i];
  18436. this.checkUnreserved(spec.local);
  18437. // check if export is defined
  18438. this.checkLocalExport(spec.local);
  18439. if (spec.local.type === "Literal") {
  18440. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  18441. }
  18442. }
  18443. node.source = null;
  18444. }
  18445. this.semicolon();
  18446. }
  18447. return this.finishNode(node, "ExportNamedDeclaration")
  18448. };
  18449. pp$8.checkExport = function(exports, name, pos) {
  18450. if (!exports) { return }
  18451. if (typeof name !== "string")
  18452. { name = name.type === "Identifier" ? name.name : name.value; }
  18453. if (hasOwn(exports, name))
  18454. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  18455. exports[name] = true;
  18456. };
  18457. pp$8.checkPatternExport = function(exports, pat) {
  18458. var type = pat.type;
  18459. if (type === "Identifier")
  18460. { this.checkExport(exports, pat, pat.start); }
  18461. else if (type === "ObjectPattern")
  18462. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  18463. {
  18464. var prop = list[i];
  18465. this.checkPatternExport(exports, prop);
  18466. } }
  18467. else if (type === "ArrayPattern")
  18468. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  18469. var elt = list$1[i$1];
  18470. if (elt) { this.checkPatternExport(exports, elt); }
  18471. } }
  18472. else if (type === "Property")
  18473. { this.checkPatternExport(exports, pat.value); }
  18474. else if (type === "AssignmentPattern")
  18475. { this.checkPatternExport(exports, pat.left); }
  18476. else if (type === "RestElement")
  18477. { this.checkPatternExport(exports, pat.argument); }
  18478. else if (type === "ParenthesizedExpression")
  18479. { this.checkPatternExport(exports, pat.expression); }
  18480. };
  18481. pp$8.checkVariableExport = function(exports, decls) {
  18482. if (!exports) { return }
  18483. for (var i = 0, list = decls; i < list.length; i += 1)
  18484. {
  18485. var decl = list[i];
  18486. this.checkPatternExport(exports, decl.id);
  18487. }
  18488. };
  18489. pp$8.shouldParseExportStatement = function() {
  18490. return this.type.keyword === "var" ||
  18491. this.type.keyword === "const" ||
  18492. this.type.keyword === "class" ||
  18493. this.type.keyword === "function" ||
  18494. this.isLet() ||
  18495. this.isAsyncFunction()
  18496. };
  18497. // Parses a comma-separated list of module exports.
  18498. pp$8.parseExportSpecifiers = function(exports) {
  18499. var nodes = [], first = true;
  18500. // export { x, y as z } [from '...']
  18501. this.expect(types$1.braceL);
  18502. while (!this.eat(types$1.braceR)) {
  18503. if (!first) {
  18504. this.expect(types$1.comma);
  18505. if (this.afterTrailingComma(types$1.braceR)) { break }
  18506. } else { first = false; }
  18507. var node = this.startNode();
  18508. node.local = this.parseModuleExportName();
  18509. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  18510. this.checkExport(
  18511. exports,
  18512. node.exported,
  18513. node.exported.start
  18514. );
  18515. nodes.push(this.finishNode(node, "ExportSpecifier"));
  18516. }
  18517. return nodes
  18518. };
  18519. // Parses import declaration.
  18520. pp$8.parseImport = function(node) {
  18521. this.next();
  18522. // import '...'
  18523. if (this.type === types$1.string) {
  18524. node.specifiers = empty$1;
  18525. node.source = this.parseExprAtom();
  18526. } else {
  18527. node.specifiers = this.parseImportSpecifiers();
  18528. this.expectContextual("from");
  18529. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  18530. }
  18531. this.semicolon();
  18532. return this.finishNode(node, "ImportDeclaration")
  18533. };
  18534. // Parses a comma-separated list of module imports.
  18535. pp$8.parseImportSpecifiers = function() {
  18536. var nodes = [], first = true;
  18537. if (this.type === types$1.name) {
  18538. // import defaultObj, { x, y as z } from '...'
  18539. var node = this.startNode();
  18540. node.local = this.parseIdent();
  18541. this.checkLValSimple(node.local, BIND_LEXICAL);
  18542. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  18543. if (!this.eat(types$1.comma)) { return nodes }
  18544. }
  18545. if (this.type === types$1.star) {
  18546. var node$1 = this.startNode();
  18547. this.next();
  18548. this.expectContextual("as");
  18549. node$1.local = this.parseIdent();
  18550. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  18551. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  18552. return nodes
  18553. }
  18554. this.expect(types$1.braceL);
  18555. while (!this.eat(types$1.braceR)) {
  18556. if (!first) {
  18557. this.expect(types$1.comma);
  18558. if (this.afterTrailingComma(types$1.braceR)) { break }
  18559. } else { first = false; }
  18560. var node$2 = this.startNode();
  18561. node$2.imported = this.parseModuleExportName();
  18562. if (this.eatContextual("as")) {
  18563. node$2.local = this.parseIdent();
  18564. } else {
  18565. this.checkUnreserved(node$2.imported);
  18566. node$2.local = node$2.imported;
  18567. }
  18568. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  18569. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  18570. }
  18571. return nodes
  18572. };
  18573. pp$8.parseModuleExportName = function() {
  18574. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  18575. var stringLiteral = this.parseLiteral(this.value);
  18576. if (loneSurrogate.test(stringLiteral.value)) {
  18577. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  18578. }
  18579. return stringLiteral
  18580. }
  18581. return this.parseIdent(true)
  18582. };
  18583. // Set `ExpressionStatement#directive` property for directive prologues.
  18584. pp$8.adaptDirectivePrologue = function(statements) {
  18585. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  18586. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  18587. }
  18588. };
  18589. pp$8.isDirectiveCandidate = function(statement) {
  18590. return (
  18591. this.options.ecmaVersion >= 5 &&
  18592. statement.type === "ExpressionStatement" &&
  18593. statement.expression.type === "Literal" &&
  18594. typeof statement.expression.value === "string" &&
  18595. // Reject parenthesized strings.
  18596. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  18597. )
  18598. };
  18599. var pp$7 = Parser.prototype;
  18600. // Convert existing expression atom to assignable pattern
  18601. // if possible.
  18602. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  18603. if (this.options.ecmaVersion >= 6 && node) {
  18604. switch (node.type) {
  18605. case "Identifier":
  18606. if (this.inAsync && node.name === "await")
  18607. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  18608. break
  18609. case "ObjectPattern":
  18610. case "ArrayPattern":
  18611. case "AssignmentPattern":
  18612. case "RestElement":
  18613. break
  18614. case "ObjectExpression":
  18615. node.type = "ObjectPattern";
  18616. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  18617. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  18618. var prop = list[i];
  18619. this.toAssignable(prop, isBinding);
  18620. // Early error:
  18621. // AssignmentRestProperty[Yield, Await] :
  18622. // `...` DestructuringAssignmentTarget[Yield, Await]
  18623. //
  18624. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  18625. if (
  18626. prop.type === "RestElement" &&
  18627. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  18628. ) {
  18629. this.raise(prop.argument.start, "Unexpected token");
  18630. }
  18631. }
  18632. break
  18633. case "Property":
  18634. // AssignmentProperty has type === "Property"
  18635. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  18636. this.toAssignable(node.value, isBinding);
  18637. break
  18638. case "ArrayExpression":
  18639. node.type = "ArrayPattern";
  18640. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  18641. this.toAssignableList(node.elements, isBinding);
  18642. break
  18643. case "SpreadElement":
  18644. node.type = "RestElement";
  18645. this.toAssignable(node.argument, isBinding);
  18646. if (node.argument.type === "AssignmentPattern")
  18647. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  18648. break
  18649. case "AssignmentExpression":
  18650. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  18651. node.type = "AssignmentPattern";
  18652. delete node.operator;
  18653. this.toAssignable(node.left, isBinding);
  18654. break
  18655. case "ParenthesizedExpression":
  18656. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  18657. break
  18658. case "ChainExpression":
  18659. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  18660. break
  18661. case "MemberExpression":
  18662. if (!isBinding) { break }
  18663. default:
  18664. this.raise(node.start, "Assigning to rvalue");
  18665. }
  18666. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  18667. return node
  18668. };
  18669. // Convert list of expression atoms to binding list.
  18670. pp$7.toAssignableList = function(exprList, isBinding) {
  18671. var end = exprList.length;
  18672. for (var i = 0; i < end; i++) {
  18673. var elt = exprList[i];
  18674. if (elt) { this.toAssignable(elt, isBinding); }
  18675. }
  18676. if (end) {
  18677. var last = exprList[end - 1];
  18678. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  18679. { this.unexpected(last.argument.start); }
  18680. }
  18681. return exprList
  18682. };
  18683. // Parses spread element.
  18684. pp$7.parseSpread = function(refDestructuringErrors) {
  18685. var node = this.startNode();
  18686. this.next();
  18687. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  18688. return this.finishNode(node, "SpreadElement")
  18689. };
  18690. pp$7.parseRestBinding = function() {
  18691. var node = this.startNode();
  18692. this.next();
  18693. // RestElement inside of a function parameter must be an identifier
  18694. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  18695. { this.unexpected(); }
  18696. node.argument = this.parseBindingAtom();
  18697. return this.finishNode(node, "RestElement")
  18698. };
  18699. // Parses lvalue (assignable) atom.
  18700. pp$7.parseBindingAtom = function() {
  18701. if (this.options.ecmaVersion >= 6) {
  18702. switch (this.type) {
  18703. case types$1.bracketL:
  18704. var node = this.startNode();
  18705. this.next();
  18706. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  18707. return this.finishNode(node, "ArrayPattern")
  18708. case types$1.braceL:
  18709. return this.parseObj(true)
  18710. }
  18711. }
  18712. return this.parseIdent()
  18713. };
  18714. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  18715. var elts = [], first = true;
  18716. while (!this.eat(close)) {
  18717. if (first) { first = false; }
  18718. else { this.expect(types$1.comma); }
  18719. if (allowEmpty && this.type === types$1.comma) {
  18720. elts.push(null);
  18721. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  18722. break
  18723. } else if (this.type === types$1.ellipsis) {
  18724. var rest = this.parseRestBinding();
  18725. this.parseBindingListItem(rest);
  18726. elts.push(rest);
  18727. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  18728. this.expect(close);
  18729. break
  18730. } else {
  18731. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  18732. this.parseBindingListItem(elem);
  18733. elts.push(elem);
  18734. }
  18735. }
  18736. return elts
  18737. };
  18738. pp$7.parseBindingListItem = function(param) {
  18739. return param
  18740. };
  18741. // Parses assignment pattern around given atom if possible.
  18742. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  18743. left = left || this.parseBindingAtom();
  18744. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  18745. var node = this.startNodeAt(startPos, startLoc);
  18746. node.left = left;
  18747. node.right = this.parseMaybeAssign();
  18748. return this.finishNode(node, "AssignmentPattern")
  18749. };
  18750. // The following three functions all verify that a node is an lvalue —
  18751. // something that can be bound, or assigned to. In order to do so, they perform
  18752. // a variety of checks:
  18753. //
  18754. // - Check that none of the bound/assigned-to identifiers are reserved words.
  18755. // - Record name declarations for bindings in the appropriate scope.
  18756. // - Check duplicate argument names, if checkClashes is set.
  18757. //
  18758. // If a complex binding pattern is encountered (e.g., object and array
  18759. // destructuring), the entire pattern is recursively checked.
  18760. //
  18761. // There are three versions of checkLVal*() appropriate for different
  18762. // circumstances:
  18763. //
  18764. // - checkLValSimple() shall be used if the syntactic construct supports
  18765. // nothing other than identifiers and member expressions. Parenthesized
  18766. // expressions are also correctly handled. This is generally appropriate for
  18767. // constructs for which the spec says
  18768. //
  18769. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  18770. // > simple.
  18771. //
  18772. // It is also appropriate for checking if an identifier is valid and not
  18773. // defined elsewhere, like import declarations or function/class identifiers.
  18774. //
  18775. // Examples where this is used include:
  18776. // a += …;
  18777. // import a from '…';
  18778. // where a is the node to be checked.
  18779. //
  18780. // - checkLValPattern() shall be used if the syntactic construct supports
  18781. // anything checkLValSimple() supports, as well as object and array
  18782. // destructuring patterns. This is generally appropriate for constructs for
  18783. // which the spec says
  18784. //
  18785. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  18786. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  18787. // > simple.
  18788. //
  18789. // Examples where this is used include:
  18790. // (a = …);
  18791. // const a = …;
  18792. // try { … } catch (a) { … }
  18793. // where a is the node to be checked.
  18794. //
  18795. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  18796. // anything checkLValPattern() supports, as well as default assignment
  18797. // patterns, rest elements, and other constructs that may appear within an
  18798. // object or array destructuring pattern.
  18799. //
  18800. // As a special case, function parameters also use checkLValInnerPattern(),
  18801. // as they also support defaults and rest constructs.
  18802. //
  18803. // These functions deliberately support both assignment and binding constructs,
  18804. // as the logic for both is exceedingly similar. If the node is the target of
  18805. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  18806. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  18807. // BIND_LEXICAL.
  18808. //
  18809. // If the function is called with a non-BIND_NONE bindingType, then
  18810. // additionally a checkClashes object may be specified to allow checking for
  18811. // duplicate argument names. checkClashes is ignored if the provided construct
  18812. // is an assignment (i.e., bindingType is BIND_NONE).
  18813. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  18814. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  18815. var isBind = bindingType !== BIND_NONE;
  18816. switch (expr.type) {
  18817. case "Identifier":
  18818. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  18819. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  18820. if (isBind) {
  18821. if (bindingType === BIND_LEXICAL && expr.name === "let")
  18822. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  18823. if (checkClashes) {
  18824. if (hasOwn(checkClashes, expr.name))
  18825. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  18826. checkClashes[expr.name] = true;
  18827. }
  18828. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  18829. }
  18830. break
  18831. case "ChainExpression":
  18832. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  18833. break
  18834. case "MemberExpression":
  18835. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  18836. break
  18837. case "ParenthesizedExpression":
  18838. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  18839. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  18840. default:
  18841. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  18842. }
  18843. };
  18844. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  18845. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  18846. switch (expr.type) {
  18847. case "ObjectPattern":
  18848. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  18849. var prop = list[i];
  18850. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  18851. }
  18852. break
  18853. case "ArrayPattern":
  18854. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  18855. var elem = list$1[i$1];
  18856. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  18857. }
  18858. break
  18859. default:
  18860. this.checkLValSimple(expr, bindingType, checkClashes);
  18861. }
  18862. };
  18863. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  18864. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  18865. switch (expr.type) {
  18866. case "Property":
  18867. // AssignmentProperty has type === "Property"
  18868. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  18869. break
  18870. case "AssignmentPattern":
  18871. this.checkLValPattern(expr.left, bindingType, checkClashes);
  18872. break
  18873. case "RestElement":
  18874. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  18875. break
  18876. default:
  18877. this.checkLValPattern(expr, bindingType, checkClashes);
  18878. }
  18879. };
  18880. // The algorithm used to determine whether a regexp can appear at a
  18881. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  18882. this.token = token;
  18883. this.isExpr = !!isExpr;
  18884. this.preserveSpace = !!preserveSpace;
  18885. this.override = override;
  18886. this.generator = !!generator;
  18887. };
  18888. var types = {
  18889. b_stat: new TokContext("{", false),
  18890. b_expr: new TokContext("{", true),
  18891. b_tmpl: new TokContext("${", false),
  18892. p_stat: new TokContext("(", false),
  18893. p_expr: new TokContext("(", true),
  18894. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  18895. f_stat: new TokContext("function", false),
  18896. f_expr: new TokContext("function", true),
  18897. f_expr_gen: new TokContext("function", true, false, null, true),
  18898. f_gen: new TokContext("function", false, false, null, true)
  18899. };
  18900. var pp$6 = Parser.prototype;
  18901. pp$6.initialContext = function() {
  18902. return [types.b_stat]
  18903. };
  18904. pp$6.curContext = function() {
  18905. return this.context[this.context.length - 1]
  18906. };
  18907. pp$6.braceIsBlock = function(prevType) {
  18908. var parent = this.curContext();
  18909. if (parent === types.f_expr || parent === types.f_stat)
  18910. { return true }
  18911. if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
  18912. { return !parent.isExpr }
  18913. // The check for `tt.name && exprAllowed` detects whether we are
  18914. // after a `yield` or `of` construct. See the `updateContext` for
  18915. // `tt.name`.
  18916. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  18917. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  18918. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  18919. { return true }
  18920. if (prevType === types$1.braceL)
  18921. { return parent === types.b_stat }
  18922. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  18923. { return false }
  18924. return !this.exprAllowed
  18925. };
  18926. pp$6.inGeneratorContext = function() {
  18927. for (var i = this.context.length - 1; i >= 1; i--) {
  18928. var context = this.context[i];
  18929. if (context.token === "function")
  18930. { return context.generator }
  18931. }
  18932. return false
  18933. };
  18934. pp$6.updateContext = function(prevType) {
  18935. var update, type = this.type;
  18936. if (type.keyword && prevType === types$1.dot)
  18937. { this.exprAllowed = false; }
  18938. else if (update = type.updateContext)
  18939. { update.call(this, prevType); }
  18940. else
  18941. { this.exprAllowed = type.beforeExpr; }
  18942. };
  18943. // Used to handle egde cases when token context could not be inferred correctly during tokenization phase
  18944. pp$6.overrideContext = function(tokenCtx) {
  18945. if (this.curContext() !== tokenCtx) {
  18946. this.context[this.context.length - 1] = tokenCtx;
  18947. }
  18948. };
  18949. // Token-specific context update code
  18950. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  18951. if (this.context.length === 1) {
  18952. this.exprAllowed = true;
  18953. return
  18954. }
  18955. var out = this.context.pop();
  18956. if (out === types.b_stat && this.curContext().token === "function") {
  18957. out = this.context.pop();
  18958. }
  18959. this.exprAllowed = !out.isExpr;
  18960. };
  18961. types$1.braceL.updateContext = function(prevType) {
  18962. this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  18963. this.exprAllowed = true;
  18964. };
  18965. types$1.dollarBraceL.updateContext = function() {
  18966. this.context.push(types.b_tmpl);
  18967. this.exprAllowed = true;
  18968. };
  18969. types$1.parenL.updateContext = function(prevType) {
  18970. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  18971. this.context.push(statementParens ? types.p_stat : types.p_expr);
  18972. this.exprAllowed = true;
  18973. };
  18974. types$1.incDec.updateContext = function() {
  18975. // tokExprAllowed stays unchanged
  18976. };
  18977. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  18978. if (prevType.beforeExpr && prevType !== types$1._else &&
  18979. !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
  18980. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  18981. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
  18982. { this.context.push(types.f_expr); }
  18983. else
  18984. { this.context.push(types.f_stat); }
  18985. this.exprAllowed = false;
  18986. };
  18987. types$1.backQuote.updateContext = function() {
  18988. if (this.curContext() === types.q_tmpl)
  18989. { this.context.pop(); }
  18990. else
  18991. { this.context.push(types.q_tmpl); }
  18992. this.exprAllowed = false;
  18993. };
  18994. types$1.star.updateContext = function(prevType) {
  18995. if (prevType === types$1._function) {
  18996. var index = this.context.length - 1;
  18997. if (this.context[index] === types.f_expr)
  18998. { this.context[index] = types.f_expr_gen; }
  18999. else
  19000. { this.context[index] = types.f_gen; }
  19001. }
  19002. this.exprAllowed = true;
  19003. };
  19004. types$1.name.updateContext = function(prevType) {
  19005. var allowed = false;
  19006. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  19007. if (this.value === "of" && !this.exprAllowed ||
  19008. this.value === "yield" && this.inGeneratorContext())
  19009. { allowed = true; }
  19010. }
  19011. this.exprAllowed = allowed;
  19012. };
  19013. // A recursive descent parser operates by defining functions for all
  19014. var pp$5 = Parser.prototype;
  19015. // Check if property name clashes with already added.
  19016. // Object/class getters and setters are not allowed to clash —
  19017. // either with each other or with an init property — and in
  19018. // strict mode, init properties are also not allowed to be repeated.
  19019. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  19020. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  19021. { return }
  19022. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  19023. { return }
  19024. var key = prop.key;
  19025. var name;
  19026. switch (key.type) {
  19027. case "Identifier": name = key.name; break
  19028. case "Literal": name = String(key.value); break
  19029. default: return
  19030. }
  19031. var kind = prop.kind;
  19032. if (this.options.ecmaVersion >= 6) {
  19033. if (name === "__proto__" && kind === "init") {
  19034. if (propHash.proto) {
  19035. if (refDestructuringErrors) {
  19036. if (refDestructuringErrors.doubleProto < 0) {
  19037. refDestructuringErrors.doubleProto = key.start;
  19038. }
  19039. } else {
  19040. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  19041. }
  19042. }
  19043. propHash.proto = true;
  19044. }
  19045. return
  19046. }
  19047. name = "$" + name;
  19048. var other = propHash[name];
  19049. if (other) {
  19050. var redefinition;
  19051. if (kind === "init") {
  19052. redefinition = this.strict && other.init || other.get || other.set;
  19053. } else {
  19054. redefinition = other.init || other[kind];
  19055. }
  19056. if (redefinition)
  19057. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  19058. } else {
  19059. other = propHash[name] = {
  19060. init: false,
  19061. get: false,
  19062. set: false
  19063. };
  19064. }
  19065. other[kind] = true;
  19066. };
  19067. // ### Expression parsing
  19068. // These nest, from the most general expression type at the top to
  19069. // 'atomic', nondivisible expression types at the bottom. Most of
  19070. // the functions will simply let the function(s) below them parse,
  19071. // and, *if* the syntactic construct they handle is present, wrap
  19072. // the AST node that the inner parser gave them in another node.
  19073. // Parse a full expression. The optional arguments are used to
  19074. // forbid the `in` operator (in for loops initalization expressions)
  19075. // and provide reference for storing '=' operator inside shorthand
  19076. // property assignment in contexts where both object expression
  19077. // and object pattern might appear (so it's possible to raise
  19078. // delayed syntax error at correct position).
  19079. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  19080. var startPos = this.start, startLoc = this.startLoc;
  19081. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  19082. if (this.type === types$1.comma) {
  19083. var node = this.startNodeAt(startPos, startLoc);
  19084. node.expressions = [expr];
  19085. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  19086. return this.finishNode(node, "SequenceExpression")
  19087. }
  19088. return expr
  19089. };
  19090. // Parse an assignment expression. This includes applications of
  19091. // operators like `+=`.
  19092. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  19093. if (this.isContextual("yield")) {
  19094. if (this.inGenerator) { return this.parseYield(forInit) }
  19095. // The tokenizer will assume an expression is allowed after
  19096. // `yield`, but this isn't that kind of yield
  19097. else { this.exprAllowed = false; }
  19098. }
  19099. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  19100. if (refDestructuringErrors) {
  19101. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  19102. oldTrailingComma = refDestructuringErrors.trailingComma;
  19103. oldDoubleProto = refDestructuringErrors.doubleProto;
  19104. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  19105. } else {
  19106. refDestructuringErrors = new DestructuringErrors;
  19107. ownDestructuringErrors = true;
  19108. }
  19109. var startPos = this.start, startLoc = this.startLoc;
  19110. if (this.type === types$1.parenL || this.type === types$1.name) {
  19111. this.potentialArrowAt = this.start;
  19112. this.potentialArrowInForAwait = forInit === "await";
  19113. }
  19114. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  19115. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  19116. if (this.type.isAssign) {
  19117. var node = this.startNodeAt(startPos, startLoc);
  19118. node.operator = this.value;
  19119. if (this.type === types$1.eq)
  19120. { left = this.toAssignable(left, false, refDestructuringErrors); }
  19121. if (!ownDestructuringErrors) {
  19122. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  19123. }
  19124. if (refDestructuringErrors.shorthandAssign >= left.start)
  19125. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  19126. if (this.type === types$1.eq)
  19127. { this.checkLValPattern(left); }
  19128. else
  19129. { this.checkLValSimple(left); }
  19130. node.left = left;
  19131. this.next();
  19132. node.right = this.parseMaybeAssign(forInit);
  19133. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  19134. return this.finishNode(node, "AssignmentExpression")
  19135. } else {
  19136. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  19137. }
  19138. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  19139. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  19140. return left
  19141. };
  19142. // Parse a ternary conditional (`?:`) operator.
  19143. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  19144. var startPos = this.start, startLoc = this.startLoc;
  19145. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  19146. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  19147. if (this.eat(types$1.question)) {
  19148. var node = this.startNodeAt(startPos, startLoc);
  19149. node.test = expr;
  19150. node.consequent = this.parseMaybeAssign();
  19151. this.expect(types$1.colon);
  19152. node.alternate = this.parseMaybeAssign(forInit);
  19153. return this.finishNode(node, "ConditionalExpression")
  19154. }
  19155. return expr
  19156. };
  19157. // Start the precedence parser.
  19158. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  19159. var startPos = this.start, startLoc = this.startLoc;
  19160. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  19161. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  19162. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  19163. };
  19164. // Parse binary operators with the operator precedence parsing
  19165. // algorithm. `left` is the left-hand side of the operator.
  19166. // `minPrec` provides context that allows the function to stop and
  19167. // defer further parser to one of its callers when it encounters an
  19168. // operator that has a lower precedence than the set it is parsing.
  19169. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  19170. var prec = this.type.binop;
  19171. if (prec != null && (!forInit || this.type !== types$1._in)) {
  19172. if (prec > minPrec) {
  19173. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  19174. var coalesce = this.type === types$1.coalesce;
  19175. if (coalesce) {
  19176. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  19177. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  19178. prec = types$1.logicalAND.binop;
  19179. }
  19180. var op = this.value;
  19181. this.next();
  19182. var startPos = this.start, startLoc = this.startLoc;
  19183. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  19184. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  19185. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  19186. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  19187. }
  19188. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  19189. }
  19190. }
  19191. return left
  19192. };
  19193. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  19194. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  19195. var node = this.startNodeAt(startPos, startLoc);
  19196. node.left = left;
  19197. node.operator = op;
  19198. node.right = right;
  19199. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  19200. };
  19201. // Parse unary operators, both prefix and postfix.
  19202. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  19203. var startPos = this.start, startLoc = this.startLoc, expr;
  19204. if (this.isContextual("await") && this.canAwait) {
  19205. expr = this.parseAwait(forInit);
  19206. sawUnary = true;
  19207. } else if (this.type.prefix) {
  19208. var node = this.startNode(), update = this.type === types$1.incDec;
  19209. node.operator = this.value;
  19210. node.prefix = true;
  19211. this.next();
  19212. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  19213. this.checkExpressionErrors(refDestructuringErrors, true);
  19214. if (update) { this.checkLValSimple(node.argument); }
  19215. else if (this.strict && node.operator === "delete" &&
  19216. node.argument.type === "Identifier")
  19217. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  19218. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  19219. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  19220. else { sawUnary = true; }
  19221. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  19222. } else if (!sawUnary && this.type === types$1.privateId) {
  19223. if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
  19224. expr = this.parsePrivateIdent();
  19225. // only could be private fields in 'in', such as #x in obj
  19226. if (this.type !== types$1._in) { this.unexpected(); }
  19227. } else {
  19228. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  19229. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  19230. while (this.type.postfix && !this.canInsertSemicolon()) {
  19231. var node$1 = this.startNodeAt(startPos, startLoc);
  19232. node$1.operator = this.value;
  19233. node$1.prefix = false;
  19234. node$1.argument = expr;
  19235. this.checkLValSimple(expr);
  19236. this.next();
  19237. expr = this.finishNode(node$1, "UpdateExpression");
  19238. }
  19239. }
  19240. if (!incDec && this.eat(types$1.starstar)) {
  19241. if (sawUnary)
  19242. { this.unexpected(this.lastTokStart); }
  19243. else
  19244. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  19245. } else {
  19246. return expr
  19247. }
  19248. };
  19249. function isPrivateFieldAccess(node) {
  19250. return (
  19251. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  19252. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  19253. )
  19254. }
  19255. // Parse call, dot, and `[]`-subscript expressions.
  19256. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  19257. var startPos = this.start, startLoc = this.startLoc;
  19258. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  19259. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  19260. { return expr }
  19261. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  19262. if (refDestructuringErrors && result.type === "MemberExpression") {
  19263. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  19264. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  19265. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  19266. }
  19267. return result
  19268. };
  19269. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  19270. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  19271. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  19272. this.potentialArrowAt === base.start;
  19273. var optionalChained = false;
  19274. while (true) {
  19275. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  19276. if (element.optional) { optionalChained = true; }
  19277. if (element === base || element.type === "ArrowFunctionExpression") {
  19278. if (optionalChained) {
  19279. var chainNode = this.startNodeAt(startPos, startLoc);
  19280. chainNode.expression = element;
  19281. element = this.finishNode(chainNode, "ChainExpression");
  19282. }
  19283. return element
  19284. }
  19285. base = element;
  19286. }
  19287. };
  19288. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  19289. var optionalSupported = this.options.ecmaVersion >= 11;
  19290. var optional = optionalSupported && this.eat(types$1.questionDot);
  19291. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  19292. var computed = this.eat(types$1.bracketL);
  19293. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  19294. var node = this.startNodeAt(startPos, startLoc);
  19295. node.object = base;
  19296. if (computed) {
  19297. node.property = this.parseExpression();
  19298. this.expect(types$1.bracketR);
  19299. } else if (this.type === types$1.privateId && base.type !== "Super") {
  19300. node.property = this.parsePrivateIdent();
  19301. } else {
  19302. node.property = this.parseIdent(this.options.allowReserved !== "never");
  19303. }
  19304. node.computed = !!computed;
  19305. if (optionalSupported) {
  19306. node.optional = optional;
  19307. }
  19308. base = this.finishNode(node, "MemberExpression");
  19309. } else if (!noCalls && this.eat(types$1.parenL)) {
  19310. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  19311. this.yieldPos = 0;
  19312. this.awaitPos = 0;
  19313. this.awaitIdentPos = 0;
  19314. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  19315. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  19316. this.checkPatternErrors(refDestructuringErrors, false);
  19317. this.checkYieldAwaitInDefaultParams();
  19318. if (this.awaitIdentPos > 0)
  19319. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  19320. this.yieldPos = oldYieldPos;
  19321. this.awaitPos = oldAwaitPos;
  19322. this.awaitIdentPos = oldAwaitIdentPos;
  19323. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  19324. }
  19325. this.checkExpressionErrors(refDestructuringErrors, true);
  19326. this.yieldPos = oldYieldPos || this.yieldPos;
  19327. this.awaitPos = oldAwaitPos || this.awaitPos;
  19328. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  19329. var node$1 = this.startNodeAt(startPos, startLoc);
  19330. node$1.callee = base;
  19331. node$1.arguments = exprList;
  19332. if (optionalSupported) {
  19333. node$1.optional = optional;
  19334. }
  19335. base = this.finishNode(node$1, "CallExpression");
  19336. } else if (this.type === types$1.backQuote) {
  19337. if (optional || optionalChained) {
  19338. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  19339. }
  19340. var node$2 = this.startNodeAt(startPos, startLoc);
  19341. node$2.tag = base;
  19342. node$2.quasi = this.parseTemplate({isTagged: true});
  19343. base = this.finishNode(node$2, "TaggedTemplateExpression");
  19344. }
  19345. return base
  19346. };
  19347. // Parse an atomic expression — either a single token that is an
  19348. // expression, an expression started by a keyword like `function` or
  19349. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  19350. // or `{}`.
  19351. pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
  19352. // If a division operator appears in an expression position, the
  19353. // tokenizer got confused, and we force it to read a regexp instead.
  19354. if (this.type === types$1.slash) { this.readRegexp(); }
  19355. var node, canBeArrow = this.potentialArrowAt === this.start;
  19356. switch (this.type) {
  19357. case types$1._super:
  19358. if (!this.allowSuper)
  19359. { this.raise(this.start, "'super' keyword outside a method"); }
  19360. node = this.startNode();
  19361. this.next();
  19362. if (this.type === types$1.parenL && !this.allowDirectSuper)
  19363. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  19364. // The `super` keyword can appear at below:
  19365. // SuperProperty:
  19366. // super [ Expression ]
  19367. // super . IdentifierName
  19368. // SuperCall:
  19369. // super ( Arguments )
  19370. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  19371. { this.unexpected(); }
  19372. return this.finishNode(node, "Super")
  19373. case types$1._this:
  19374. node = this.startNode();
  19375. this.next();
  19376. return this.finishNode(node, "ThisExpression")
  19377. case types$1.name:
  19378. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  19379. var id = this.parseIdent(false);
  19380. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  19381. this.overrideContext(types.f_expr);
  19382. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  19383. }
  19384. if (canBeArrow && !this.canInsertSemicolon()) {
  19385. if (this.eat(types$1.arrow))
  19386. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  19387. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  19388. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  19389. id = this.parseIdent(false);
  19390. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  19391. { this.unexpected(); }
  19392. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  19393. }
  19394. }
  19395. return id
  19396. case types$1.regexp:
  19397. var value = this.value;
  19398. node = this.parseLiteral(value.value);
  19399. node.regex = {pattern: value.pattern, flags: value.flags};
  19400. return node
  19401. case types$1.num: case types$1.string:
  19402. return this.parseLiteral(this.value)
  19403. case types$1._null: case types$1._true: case types$1._false:
  19404. node = this.startNode();
  19405. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  19406. node.raw = this.type.keyword;
  19407. this.next();
  19408. return this.finishNode(node, "Literal")
  19409. case types$1.parenL:
  19410. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  19411. if (refDestructuringErrors) {
  19412. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  19413. { refDestructuringErrors.parenthesizedAssign = start; }
  19414. if (refDestructuringErrors.parenthesizedBind < 0)
  19415. { refDestructuringErrors.parenthesizedBind = start; }
  19416. }
  19417. return expr
  19418. case types$1.bracketL:
  19419. node = this.startNode();
  19420. this.next();
  19421. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  19422. return this.finishNode(node, "ArrayExpression")
  19423. case types$1.braceL:
  19424. this.overrideContext(types.b_expr);
  19425. return this.parseObj(false, refDestructuringErrors)
  19426. case types$1._function:
  19427. node = this.startNode();
  19428. this.next();
  19429. return this.parseFunction(node, 0)
  19430. case types$1._class:
  19431. return this.parseClass(this.startNode(), false)
  19432. case types$1._new:
  19433. return this.parseNew()
  19434. case types$1.backQuote:
  19435. return this.parseTemplate()
  19436. case types$1._import:
  19437. if (this.options.ecmaVersion >= 11) {
  19438. return this.parseExprImport()
  19439. } else {
  19440. return this.unexpected()
  19441. }
  19442. default:
  19443. this.unexpected();
  19444. }
  19445. };
  19446. pp$5.parseExprImport = function() {
  19447. var node = this.startNode();
  19448. // Consume `import` as an identifier for `import.meta`.
  19449. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  19450. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  19451. var meta = this.parseIdent(true);
  19452. switch (this.type) {
  19453. case types$1.parenL:
  19454. return this.parseDynamicImport(node)
  19455. case types$1.dot:
  19456. node.meta = meta;
  19457. return this.parseImportMeta(node)
  19458. default:
  19459. this.unexpected();
  19460. }
  19461. };
  19462. pp$5.parseDynamicImport = function(node) {
  19463. this.next(); // skip `(`
  19464. // Parse node.source.
  19465. node.source = this.parseMaybeAssign();
  19466. // Verify ending.
  19467. if (!this.eat(types$1.parenR)) {
  19468. var errorPos = this.start;
  19469. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  19470. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  19471. } else {
  19472. this.unexpected(errorPos);
  19473. }
  19474. }
  19475. return this.finishNode(node, "ImportExpression")
  19476. };
  19477. pp$5.parseImportMeta = function(node) {
  19478. this.next(); // skip `.`
  19479. var containsEsc = this.containsEsc;
  19480. node.property = this.parseIdent(true);
  19481. if (node.property.name !== "meta")
  19482. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  19483. if (containsEsc)
  19484. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  19485. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  19486. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  19487. return this.finishNode(node, "MetaProperty")
  19488. };
  19489. pp$5.parseLiteral = function(value) {
  19490. var node = this.startNode();
  19491. node.value = value;
  19492. node.raw = this.input.slice(this.start, this.end);
  19493. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  19494. this.next();
  19495. return this.finishNode(node, "Literal")
  19496. };
  19497. pp$5.parseParenExpression = function() {
  19498. this.expect(types$1.parenL);
  19499. var val = this.parseExpression();
  19500. this.expect(types$1.parenR);
  19501. return val
  19502. };
  19503. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  19504. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  19505. if (this.options.ecmaVersion >= 6) {
  19506. this.next();
  19507. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  19508. var exprList = [], first = true, lastIsComma = false;
  19509. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  19510. this.yieldPos = 0;
  19511. this.awaitPos = 0;
  19512. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  19513. while (this.type !== types$1.parenR) {
  19514. first ? first = false : this.expect(types$1.comma);
  19515. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  19516. lastIsComma = true;
  19517. break
  19518. } else if (this.type === types$1.ellipsis) {
  19519. spreadStart = this.start;
  19520. exprList.push(this.parseParenItem(this.parseRestBinding()));
  19521. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  19522. break
  19523. } else {
  19524. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  19525. }
  19526. }
  19527. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  19528. this.expect(types$1.parenR);
  19529. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  19530. this.checkPatternErrors(refDestructuringErrors, false);
  19531. this.checkYieldAwaitInDefaultParams();
  19532. this.yieldPos = oldYieldPos;
  19533. this.awaitPos = oldAwaitPos;
  19534. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  19535. }
  19536. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  19537. if (spreadStart) { this.unexpected(spreadStart); }
  19538. this.checkExpressionErrors(refDestructuringErrors, true);
  19539. this.yieldPos = oldYieldPos || this.yieldPos;
  19540. this.awaitPos = oldAwaitPos || this.awaitPos;
  19541. if (exprList.length > 1) {
  19542. val = this.startNodeAt(innerStartPos, innerStartLoc);
  19543. val.expressions = exprList;
  19544. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  19545. } else {
  19546. val = exprList[0];
  19547. }
  19548. } else {
  19549. val = this.parseParenExpression();
  19550. }
  19551. if (this.options.preserveParens) {
  19552. var par = this.startNodeAt(startPos, startLoc);
  19553. par.expression = val;
  19554. return this.finishNode(par, "ParenthesizedExpression")
  19555. } else {
  19556. return val
  19557. }
  19558. };
  19559. pp$5.parseParenItem = function(item) {
  19560. return item
  19561. };
  19562. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  19563. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  19564. };
  19565. // New's precedence is slightly tricky. It must allow its argument to
  19566. // be a `[]` or dot subscript expression, but not a call — at least,
  19567. // not without wrapping it in parentheses. Thus, it uses the noCalls
  19568. // argument to parseSubscripts to prevent it from consuming the
  19569. // argument list.
  19570. var empty = [];
  19571. pp$5.parseNew = function() {
  19572. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  19573. var node = this.startNode();
  19574. var meta = this.parseIdent(true);
  19575. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  19576. node.meta = meta;
  19577. var containsEsc = this.containsEsc;
  19578. node.property = this.parseIdent(true);
  19579. if (node.property.name !== "target")
  19580. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  19581. if (containsEsc)
  19582. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  19583. if (!this.allowNewDotTarget)
  19584. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  19585. return this.finishNode(node, "MetaProperty")
  19586. }
  19587. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
  19588. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
  19589. if (isImport && node.callee.type === "ImportExpression") {
  19590. this.raise(startPos, "Cannot use new with import()");
  19591. }
  19592. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  19593. else { node.arguments = empty; }
  19594. return this.finishNode(node, "NewExpression")
  19595. };
  19596. // Parse template expression.
  19597. pp$5.parseTemplateElement = function(ref) {
  19598. var isTagged = ref.isTagged;
  19599. var elem = this.startNode();
  19600. if (this.type === types$1.invalidTemplate) {
  19601. if (!isTagged) {
  19602. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  19603. }
  19604. elem.value = {
  19605. raw: this.value,
  19606. cooked: null
  19607. };
  19608. } else {
  19609. elem.value = {
  19610. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  19611. cooked: this.value
  19612. };
  19613. }
  19614. this.next();
  19615. elem.tail = this.type === types$1.backQuote;
  19616. return this.finishNode(elem, "TemplateElement")
  19617. };
  19618. pp$5.parseTemplate = function(ref) {
  19619. if ( ref === void 0 ) ref = {};
  19620. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  19621. var node = this.startNode();
  19622. this.next();
  19623. node.expressions = [];
  19624. var curElt = this.parseTemplateElement({isTagged: isTagged});
  19625. node.quasis = [curElt];
  19626. while (!curElt.tail) {
  19627. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  19628. this.expect(types$1.dollarBraceL);
  19629. node.expressions.push(this.parseExpression());
  19630. this.expect(types$1.braceR);
  19631. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  19632. }
  19633. this.next();
  19634. return this.finishNode(node, "TemplateLiteral")
  19635. };
  19636. pp$5.isAsyncProp = function(prop) {
  19637. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  19638. (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&
  19639. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  19640. };
  19641. // Parse an object literal or binding pattern.
  19642. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  19643. var node = this.startNode(), first = true, propHash = {};
  19644. node.properties = [];
  19645. this.next();
  19646. while (!this.eat(types$1.braceR)) {
  19647. if (!first) {
  19648. this.expect(types$1.comma);
  19649. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  19650. } else { first = false; }
  19651. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  19652. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  19653. node.properties.push(prop);
  19654. }
  19655. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  19656. };
  19657. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  19658. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  19659. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  19660. if (isPattern) {
  19661. prop.argument = this.parseIdent(false);
  19662. if (this.type === types$1.comma) {
  19663. this.raise(this.start, "Comma is not permitted after the rest element");
  19664. }
  19665. return this.finishNode(prop, "RestElement")
  19666. }
  19667. // Parse argument.
  19668. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  19669. // To disallow trailing comma via `this.toAssignable()`.
  19670. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  19671. refDestructuringErrors.trailingComma = this.start;
  19672. }
  19673. // Finish
  19674. return this.finishNode(prop, "SpreadElement")
  19675. }
  19676. if (this.options.ecmaVersion >= 6) {
  19677. prop.method = false;
  19678. prop.shorthand = false;
  19679. if (isPattern || refDestructuringErrors) {
  19680. startPos = this.start;
  19681. startLoc = this.startLoc;
  19682. }
  19683. if (!isPattern)
  19684. { isGenerator = this.eat(types$1.star); }
  19685. }
  19686. var containsEsc = this.containsEsc;
  19687. this.parsePropertyName(prop);
  19688. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  19689. isAsync = true;
  19690. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  19691. this.parsePropertyName(prop, refDestructuringErrors);
  19692. } else {
  19693. isAsync = false;
  19694. }
  19695. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  19696. return this.finishNode(prop, "Property")
  19697. };
  19698. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  19699. if ((isGenerator || isAsync) && this.type === types$1.colon)
  19700. { this.unexpected(); }
  19701. if (this.eat(types$1.colon)) {
  19702. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  19703. prop.kind = "init";
  19704. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  19705. if (isPattern) { this.unexpected(); }
  19706. prop.kind = "init";
  19707. prop.method = true;
  19708. prop.value = this.parseMethod(isGenerator, isAsync);
  19709. } else if (!isPattern && !containsEsc &&
  19710. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  19711. (prop.key.name === "get" || prop.key.name === "set") &&
  19712. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  19713. if (isGenerator || isAsync) { this.unexpected(); }
  19714. prop.kind = prop.key.name;
  19715. this.parsePropertyName(prop);
  19716. prop.value = this.parseMethod(false);
  19717. var paramCount = prop.kind === "get" ? 0 : 1;
  19718. if (prop.value.params.length !== paramCount) {
  19719. var start = prop.value.start;
  19720. if (prop.kind === "get")
  19721. { this.raiseRecoverable(start, "getter should have no params"); }
  19722. else
  19723. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  19724. } else {
  19725. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  19726. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  19727. }
  19728. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  19729. if (isGenerator || isAsync) { this.unexpected(); }
  19730. this.checkUnreserved(prop.key);
  19731. if (prop.key.name === "await" && !this.awaitIdentPos)
  19732. { this.awaitIdentPos = startPos; }
  19733. prop.kind = "init";
  19734. if (isPattern) {
  19735. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  19736. } else if (this.type === types$1.eq && refDestructuringErrors) {
  19737. if (refDestructuringErrors.shorthandAssign < 0)
  19738. { refDestructuringErrors.shorthandAssign = this.start; }
  19739. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  19740. } else {
  19741. prop.value = this.copyNode(prop.key);
  19742. }
  19743. prop.shorthand = true;
  19744. } else { this.unexpected(); }
  19745. };
  19746. pp$5.parsePropertyName = function(prop) {
  19747. if (this.options.ecmaVersion >= 6) {
  19748. if (this.eat(types$1.bracketL)) {
  19749. prop.computed = true;
  19750. prop.key = this.parseMaybeAssign();
  19751. this.expect(types$1.bracketR);
  19752. return prop.key
  19753. } else {
  19754. prop.computed = false;
  19755. }
  19756. }
  19757. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  19758. };
  19759. // Initialize empty function node.
  19760. pp$5.initFunction = function(node) {
  19761. node.id = null;
  19762. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  19763. if (this.options.ecmaVersion >= 8) { node.async = false; }
  19764. };
  19765. // Parse object or class method.
  19766. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  19767. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  19768. this.initFunction(node);
  19769. if (this.options.ecmaVersion >= 6)
  19770. { node.generator = isGenerator; }
  19771. if (this.options.ecmaVersion >= 8)
  19772. { node.async = !!isAsync; }
  19773. this.yieldPos = 0;
  19774. this.awaitPos = 0;
  19775. this.awaitIdentPos = 0;
  19776. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  19777. this.expect(types$1.parenL);
  19778. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  19779. this.checkYieldAwaitInDefaultParams();
  19780. this.parseFunctionBody(node, false, true, false);
  19781. this.yieldPos = oldYieldPos;
  19782. this.awaitPos = oldAwaitPos;
  19783. this.awaitIdentPos = oldAwaitIdentPos;
  19784. return this.finishNode(node, "FunctionExpression")
  19785. };
  19786. // Parse arrow function expression with given parameters.
  19787. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  19788. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  19789. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  19790. this.initFunction(node);
  19791. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  19792. this.yieldPos = 0;
  19793. this.awaitPos = 0;
  19794. this.awaitIdentPos = 0;
  19795. node.params = this.toAssignableList(params, true);
  19796. this.parseFunctionBody(node, true, false, forInit);
  19797. this.yieldPos = oldYieldPos;
  19798. this.awaitPos = oldAwaitPos;
  19799. this.awaitIdentPos = oldAwaitIdentPos;
  19800. return this.finishNode(node, "ArrowFunctionExpression")
  19801. };
  19802. // Parse function body and check parameters.
  19803. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  19804. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  19805. var oldStrict = this.strict, useStrict = false;
  19806. if (isExpression) {
  19807. node.body = this.parseMaybeAssign(forInit);
  19808. node.expression = true;
  19809. this.checkParams(node, false);
  19810. } else {
  19811. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  19812. if (!oldStrict || nonSimple) {
  19813. useStrict = this.strictDirective(this.end);
  19814. // If this is a strict mode function, verify that argument names
  19815. // are not repeated, and it does not try to bind the words `eval`
  19816. // or `arguments`.
  19817. if (useStrict && nonSimple)
  19818. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  19819. }
  19820. // Start a new scope with regard to labels and the `inFunction`
  19821. // flag (restore them to their old value afterwards).
  19822. var oldLabels = this.labels;
  19823. this.labels = [];
  19824. if (useStrict) { this.strict = true; }
  19825. // Add the params to varDeclaredNames to ensure that an error is thrown
  19826. // if a let/const declaration in the function clashes with one of the params.
  19827. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  19828. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  19829. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  19830. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  19831. node.expression = false;
  19832. this.adaptDirectivePrologue(node.body.body);
  19833. this.labels = oldLabels;
  19834. }
  19835. this.exitScope();
  19836. };
  19837. pp$5.isSimpleParamList = function(params) {
  19838. for (var i = 0, list = params; i < list.length; i += 1)
  19839. {
  19840. var param = list[i];
  19841. if (param.type !== "Identifier") { return false
  19842. } }
  19843. return true
  19844. };
  19845. // Checks function params for various disallowed patterns such as using "eval"
  19846. // or "arguments" and duplicate parameters.
  19847. pp$5.checkParams = function(node, allowDuplicates) {
  19848. var nameHash = Object.create(null);
  19849. for (var i = 0, list = node.params; i < list.length; i += 1)
  19850. {
  19851. var param = list[i];
  19852. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  19853. }
  19854. };
  19855. // Parses a comma-separated list of expressions, and returns them as
  19856. // an array. `close` is the token type that ends the list, and
  19857. // `allowEmpty` can be turned on to allow subsequent commas with
  19858. // nothing in between them to be parsed as `null` (which is needed
  19859. // for array literals).
  19860. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  19861. var elts = [], first = true;
  19862. while (!this.eat(close)) {
  19863. if (!first) {
  19864. this.expect(types$1.comma);
  19865. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  19866. } else { first = false; }
  19867. var elt = (void 0);
  19868. if (allowEmpty && this.type === types$1.comma)
  19869. { elt = null; }
  19870. else if (this.type === types$1.ellipsis) {
  19871. elt = this.parseSpread(refDestructuringErrors);
  19872. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  19873. { refDestructuringErrors.trailingComma = this.start; }
  19874. } else {
  19875. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  19876. }
  19877. elts.push(elt);
  19878. }
  19879. return elts
  19880. };
  19881. pp$5.checkUnreserved = function(ref) {
  19882. var start = ref.start;
  19883. var end = ref.end;
  19884. var name = ref.name;
  19885. if (this.inGenerator && name === "yield")
  19886. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  19887. if (this.inAsync && name === "await")
  19888. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  19889. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  19890. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  19891. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  19892. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  19893. if (this.keywords.test(name))
  19894. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  19895. if (this.options.ecmaVersion < 6 &&
  19896. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  19897. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  19898. if (re.test(name)) {
  19899. if (!this.inAsync && name === "await")
  19900. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  19901. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  19902. }
  19903. };
  19904. // Parse the next token as an identifier. If `liberal` is true (used
  19905. // when parsing properties), it will also convert keywords into
  19906. // identifiers.
  19907. pp$5.parseIdent = function(liberal, isBinding) {
  19908. var node = this.startNode();
  19909. if (this.type === types$1.name) {
  19910. node.name = this.value;
  19911. } else if (this.type.keyword) {
  19912. node.name = this.type.keyword;
  19913. // To fix https://github.com/acornjs/acorn/issues/575
  19914. // `class` and `function` keywords push new context into this.context.
  19915. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  19916. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  19917. if ((node.name === "class" || node.name === "function") &&
  19918. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  19919. this.context.pop();
  19920. }
  19921. } else {
  19922. this.unexpected();
  19923. }
  19924. this.next(!!liberal);
  19925. this.finishNode(node, "Identifier");
  19926. if (!liberal) {
  19927. this.checkUnreserved(node);
  19928. if (node.name === "await" && !this.awaitIdentPos)
  19929. { this.awaitIdentPos = node.start; }
  19930. }
  19931. return node
  19932. };
  19933. pp$5.parsePrivateIdent = function() {
  19934. var node = this.startNode();
  19935. if (this.type === types$1.privateId) {
  19936. node.name = this.value;
  19937. } else {
  19938. this.unexpected();
  19939. }
  19940. this.next();
  19941. this.finishNode(node, "PrivateIdentifier");
  19942. // For validating existence
  19943. if (this.privateNameStack.length === 0) {
  19944. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  19945. } else {
  19946. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  19947. }
  19948. return node
  19949. };
  19950. // Parses yield expression inside generator.
  19951. pp$5.parseYield = function(forInit) {
  19952. if (!this.yieldPos) { this.yieldPos = this.start; }
  19953. var node = this.startNode();
  19954. this.next();
  19955. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  19956. node.delegate = false;
  19957. node.argument = null;
  19958. } else {
  19959. node.delegate = this.eat(types$1.star);
  19960. node.argument = this.parseMaybeAssign(forInit);
  19961. }
  19962. return this.finishNode(node, "YieldExpression")
  19963. };
  19964. pp$5.parseAwait = function(forInit) {
  19965. if (!this.awaitPos) { this.awaitPos = this.start; }
  19966. var node = this.startNode();
  19967. this.next();
  19968. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  19969. return this.finishNode(node, "AwaitExpression")
  19970. };
  19971. var pp$4 = Parser.prototype;
  19972. // This function is used to raise exceptions on parse errors. It
  19973. // takes an offset integer (into the current `input`) to indicate
  19974. // the location of the error, attaches the position to the end
  19975. // of the error message, and then raises a `SyntaxError` with that
  19976. // message.
  19977. pp$4.raise = function(pos, message) {
  19978. var loc = getLineInfo(this.input, pos);
  19979. message += " (" + loc.line + ":" + loc.column + ")";
  19980. var err = new SyntaxError(message);
  19981. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  19982. throw err
  19983. };
  19984. pp$4.raiseRecoverable = pp$4.raise;
  19985. pp$4.curPosition = function() {
  19986. if (this.options.locations) {
  19987. return new Position(this.curLine, this.pos - this.lineStart)
  19988. }
  19989. };
  19990. var pp$3 = Parser.prototype;
  19991. var Scope = function Scope(flags) {
  19992. this.flags = flags;
  19993. // A list of var-declared names in the current lexical scope
  19994. this.var = [];
  19995. // A list of lexically-declared names in the current lexical scope
  19996. this.lexical = [];
  19997. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  19998. this.functions = [];
  19999. // A switch to disallow the identifier reference 'arguments'
  20000. this.inClassFieldInit = false;
  20001. };
  20002. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  20003. pp$3.enterScope = function(flags) {
  20004. this.scopeStack.push(new Scope(flags));
  20005. };
  20006. pp$3.exitScope = function() {
  20007. this.scopeStack.pop();
  20008. };
  20009. // The spec says:
  20010. // > At the top level of a function, or script, function declarations are
  20011. // > treated like var declarations rather than like lexical declarations.
  20012. pp$3.treatFunctionsAsVarInScope = function(scope) {
  20013. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  20014. };
  20015. pp$3.declareName = function(name, bindingType, pos) {
  20016. var redeclared = false;
  20017. if (bindingType === BIND_LEXICAL) {
  20018. var scope = this.currentScope();
  20019. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  20020. scope.lexical.push(name);
  20021. if (this.inModule && (scope.flags & SCOPE_TOP))
  20022. { delete this.undefinedExports[name]; }
  20023. } else if (bindingType === BIND_SIMPLE_CATCH) {
  20024. var scope$1 = this.currentScope();
  20025. scope$1.lexical.push(name);
  20026. } else if (bindingType === BIND_FUNCTION) {
  20027. var scope$2 = this.currentScope();
  20028. if (this.treatFunctionsAsVar)
  20029. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  20030. else
  20031. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  20032. scope$2.functions.push(name);
  20033. } else {
  20034. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  20035. var scope$3 = this.scopeStack[i];
  20036. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  20037. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  20038. redeclared = true;
  20039. break
  20040. }
  20041. scope$3.var.push(name);
  20042. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  20043. { delete this.undefinedExports[name]; }
  20044. if (scope$3.flags & SCOPE_VAR) { break }
  20045. }
  20046. }
  20047. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  20048. };
  20049. pp$3.checkLocalExport = function(id) {
  20050. // scope.functions must be empty as Module code is always strict.
  20051. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  20052. this.scopeStack[0].var.indexOf(id.name) === -1) {
  20053. this.undefinedExports[id.name] = id;
  20054. }
  20055. };
  20056. pp$3.currentScope = function() {
  20057. return this.scopeStack[this.scopeStack.length - 1]
  20058. };
  20059. pp$3.currentVarScope = function() {
  20060. for (var i = this.scopeStack.length - 1;; i--) {
  20061. var scope = this.scopeStack[i];
  20062. if (scope.flags & SCOPE_VAR) { return scope }
  20063. }
  20064. };
  20065. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  20066. pp$3.currentThisScope = function() {
  20067. for (var i = this.scopeStack.length - 1;; i--) {
  20068. var scope = this.scopeStack[i];
  20069. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  20070. }
  20071. };
  20072. var Node = function Node(parser, pos, loc) {
  20073. this.type = "";
  20074. this.start = pos;
  20075. this.end = 0;
  20076. if (parser.options.locations)
  20077. { this.loc = new SourceLocation(parser, loc); }
  20078. if (parser.options.directSourceFile)
  20079. { this.sourceFile = parser.options.directSourceFile; }
  20080. if (parser.options.ranges)
  20081. { this.range = [pos, 0]; }
  20082. };
  20083. // Start an AST node, attaching a start offset.
  20084. var pp$2 = Parser.prototype;
  20085. pp$2.startNode = function() {
  20086. return new Node(this, this.start, this.startLoc)
  20087. };
  20088. pp$2.startNodeAt = function(pos, loc) {
  20089. return new Node(this, pos, loc)
  20090. };
  20091. // Finish an AST node, adding `type` and `end` properties.
  20092. function finishNodeAt(node, type, pos, loc) {
  20093. node.type = type;
  20094. node.end = pos;
  20095. if (this.options.locations)
  20096. { node.loc.end = loc; }
  20097. if (this.options.ranges)
  20098. { node.range[1] = pos; }
  20099. return node
  20100. }
  20101. pp$2.finishNode = function(node, type) {
  20102. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  20103. };
  20104. // Finish node at given position
  20105. pp$2.finishNodeAt = function(node, type, pos, loc) {
  20106. return finishNodeAt.call(this, node, type, pos, loc)
  20107. };
  20108. pp$2.copyNode = function(node) {
  20109. var newNode = new Node(this, node.start, this.startLoc);
  20110. for (var prop in node) { newNode[prop] = node[prop]; }
  20111. return newNode
  20112. };
  20113. // This file contains Unicode properties extracted from the ECMAScript
  20114. // specification. The lists are extracted like so:
  20115. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  20116. // #table-binary-unicode-properties
  20117. var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
  20118. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  20119. var ecma11BinaryProperties = ecma10BinaryProperties;
  20120. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  20121. var ecma13BinaryProperties = ecma12BinaryProperties;
  20122. var unicodeBinaryProperties = {
  20123. 9: ecma9BinaryProperties,
  20124. 10: ecma10BinaryProperties,
  20125. 11: ecma11BinaryProperties,
  20126. 12: ecma12BinaryProperties,
  20127. 13: ecma13BinaryProperties
  20128. };
  20129. // #table-unicode-general-category-values
  20130. var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
  20131. // #table-unicode-script-values
  20132. var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
  20133. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  20134. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  20135. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  20136. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  20137. var unicodeScriptValues = {
  20138. 9: ecma9ScriptValues,
  20139. 10: ecma10ScriptValues,
  20140. 11: ecma11ScriptValues,
  20141. 12: ecma12ScriptValues,
  20142. 13: ecma13ScriptValues
  20143. };
  20144. var data = {};
  20145. function buildUnicodeData(ecmaVersion) {
  20146. var d = data[ecmaVersion] = {
  20147. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  20148. nonBinary: {
  20149. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  20150. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  20151. }
  20152. };
  20153. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  20154. d.nonBinary.gc = d.nonBinary.General_Category;
  20155. d.nonBinary.sc = d.nonBinary.Script;
  20156. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  20157. }
  20158. for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) {
  20159. var ecmaVersion = list[i];
  20160. buildUnicodeData(ecmaVersion);
  20161. }
  20162. var pp$1 = Parser.prototype;
  20163. var RegExpValidationState = function RegExpValidationState(parser) {
  20164. this.parser = parser;
  20165. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  20166. this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
  20167. this.source = "";
  20168. this.flags = "";
  20169. this.start = 0;
  20170. this.switchU = false;
  20171. this.switchN = false;
  20172. this.pos = 0;
  20173. this.lastIntValue = 0;
  20174. this.lastStringValue = "";
  20175. this.lastAssertionIsQuantifiable = false;
  20176. this.numCapturingParens = 0;
  20177. this.maxBackReference = 0;
  20178. this.groupNames = [];
  20179. this.backReferenceNames = [];
  20180. };
  20181. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  20182. var unicode = flags.indexOf("u") !== -1;
  20183. this.start = start | 0;
  20184. this.source = pattern + "";
  20185. this.flags = flags;
  20186. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  20187. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  20188. };
  20189. RegExpValidationState.prototype.raise = function raise (message) {
  20190. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  20191. };
  20192. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  20193. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  20194. RegExpValidationState.prototype.at = function at (i, forceU) {
  20195. if ( forceU === void 0 ) forceU = false;
  20196. var s = this.source;
  20197. var l = s.length;
  20198. if (i >= l) {
  20199. return -1
  20200. }
  20201. var c = s.charCodeAt(i);
  20202. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  20203. return c
  20204. }
  20205. var next = s.charCodeAt(i + 1);
  20206. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  20207. };
  20208. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  20209. if ( forceU === void 0 ) forceU = false;
  20210. var s = this.source;
  20211. var l = s.length;
  20212. if (i >= l) {
  20213. return l
  20214. }
  20215. var c = s.charCodeAt(i), next;
  20216. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  20217. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  20218. return i + 1
  20219. }
  20220. return i + 2
  20221. };
  20222. RegExpValidationState.prototype.current = function current (forceU) {
  20223. if ( forceU === void 0 ) forceU = false;
  20224. return this.at(this.pos, forceU)
  20225. };
  20226. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  20227. if ( forceU === void 0 ) forceU = false;
  20228. return this.at(this.nextIndex(this.pos, forceU), forceU)
  20229. };
  20230. RegExpValidationState.prototype.advance = function advance (forceU) {
  20231. if ( forceU === void 0 ) forceU = false;
  20232. this.pos = this.nextIndex(this.pos, forceU);
  20233. };
  20234. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  20235. if ( forceU === void 0 ) forceU = false;
  20236. if (this.current(forceU) === ch) {
  20237. this.advance(forceU);
  20238. return true
  20239. }
  20240. return false
  20241. };
  20242. /**
  20243. * Validate the flags part of a given RegExpLiteral.
  20244. *
  20245. * @param {RegExpValidationState} state The state to validate RegExp.
  20246. * @returns {void}
  20247. */
  20248. pp$1.validateRegExpFlags = function(state) {
  20249. var validFlags = state.validFlags;
  20250. var flags = state.flags;
  20251. for (var i = 0; i < flags.length; i++) {
  20252. var flag = flags.charAt(i);
  20253. if (validFlags.indexOf(flag) === -1) {
  20254. this.raise(state.start, "Invalid regular expression flag");
  20255. }
  20256. if (flags.indexOf(flag, i + 1) > -1) {
  20257. this.raise(state.start, "Duplicate regular expression flag");
  20258. }
  20259. }
  20260. };
  20261. /**
  20262. * Validate the pattern part of a given RegExpLiteral.
  20263. *
  20264. * @param {RegExpValidationState} state The state to validate RegExp.
  20265. * @returns {void}
  20266. */
  20267. pp$1.validateRegExpPattern = function(state) {
  20268. this.regexp_pattern(state);
  20269. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  20270. // parsing contains a |GroupName|, reparse with the goal symbol
  20271. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  20272. // exception if _P_ did not conform to the grammar, if any elements of _P_
  20273. // were not matched by the parse, or if any Early Error conditions exist.
  20274. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  20275. state.switchN = true;
  20276. this.regexp_pattern(state);
  20277. }
  20278. };
  20279. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  20280. pp$1.regexp_pattern = function(state) {
  20281. state.pos = 0;
  20282. state.lastIntValue = 0;
  20283. state.lastStringValue = "";
  20284. state.lastAssertionIsQuantifiable = false;
  20285. state.numCapturingParens = 0;
  20286. state.maxBackReference = 0;
  20287. state.groupNames.length = 0;
  20288. state.backReferenceNames.length = 0;
  20289. this.regexp_disjunction(state);
  20290. if (state.pos !== state.source.length) {
  20291. // Make the same messages as V8.
  20292. if (state.eat(0x29 /* ) */)) {
  20293. state.raise("Unmatched ')'");
  20294. }
  20295. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  20296. state.raise("Lone quantifier brackets");
  20297. }
  20298. }
  20299. if (state.maxBackReference > state.numCapturingParens) {
  20300. state.raise("Invalid escape");
  20301. }
  20302. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  20303. var name = list[i];
  20304. if (state.groupNames.indexOf(name) === -1) {
  20305. state.raise("Invalid named capture referenced");
  20306. }
  20307. }
  20308. };
  20309. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  20310. pp$1.regexp_disjunction = function(state) {
  20311. this.regexp_alternative(state);
  20312. while (state.eat(0x7C /* | */)) {
  20313. this.regexp_alternative(state);
  20314. }
  20315. // Make the same message as V8.
  20316. if (this.regexp_eatQuantifier(state, true)) {
  20317. state.raise("Nothing to repeat");
  20318. }
  20319. if (state.eat(0x7B /* { */)) {
  20320. state.raise("Lone quantifier brackets");
  20321. }
  20322. };
  20323. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  20324. pp$1.regexp_alternative = function(state) {
  20325. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  20326. { }
  20327. };
  20328. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  20329. pp$1.regexp_eatTerm = function(state) {
  20330. if (this.regexp_eatAssertion(state)) {
  20331. // Handle `QuantifiableAssertion Quantifier` alternative.
  20332. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  20333. // is a QuantifiableAssertion.
  20334. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  20335. // Make the same message as V8.
  20336. if (state.switchU) {
  20337. state.raise("Invalid quantifier");
  20338. }
  20339. }
  20340. return true
  20341. }
  20342. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  20343. this.regexp_eatQuantifier(state);
  20344. return true
  20345. }
  20346. return false
  20347. };
  20348. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  20349. pp$1.regexp_eatAssertion = function(state) {
  20350. var start = state.pos;
  20351. state.lastAssertionIsQuantifiable = false;
  20352. // ^, $
  20353. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  20354. return true
  20355. }
  20356. // \b \B
  20357. if (state.eat(0x5C /* \ */)) {
  20358. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  20359. return true
  20360. }
  20361. state.pos = start;
  20362. }
  20363. // Lookahead / Lookbehind
  20364. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  20365. var lookbehind = false;
  20366. if (this.options.ecmaVersion >= 9) {
  20367. lookbehind = state.eat(0x3C /* < */);
  20368. }
  20369. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  20370. this.regexp_disjunction(state);
  20371. if (!state.eat(0x29 /* ) */)) {
  20372. state.raise("Unterminated group");
  20373. }
  20374. state.lastAssertionIsQuantifiable = !lookbehind;
  20375. return true
  20376. }
  20377. }
  20378. state.pos = start;
  20379. return false
  20380. };
  20381. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  20382. pp$1.regexp_eatQuantifier = function(state, noError) {
  20383. if ( noError === void 0 ) noError = false;
  20384. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  20385. state.eat(0x3F /* ? */);
  20386. return true
  20387. }
  20388. return false
  20389. };
  20390. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  20391. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  20392. return (
  20393. state.eat(0x2A /* * */) ||
  20394. state.eat(0x2B /* + */) ||
  20395. state.eat(0x3F /* ? */) ||
  20396. this.regexp_eatBracedQuantifier(state, noError)
  20397. )
  20398. };
  20399. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  20400. var start = state.pos;
  20401. if (state.eat(0x7B /* { */)) {
  20402. var min = 0, max = -1;
  20403. if (this.regexp_eatDecimalDigits(state)) {
  20404. min = state.lastIntValue;
  20405. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  20406. max = state.lastIntValue;
  20407. }
  20408. if (state.eat(0x7D /* } */)) {
  20409. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  20410. if (max !== -1 && max < min && !noError) {
  20411. state.raise("numbers out of order in {} quantifier");
  20412. }
  20413. return true
  20414. }
  20415. }
  20416. if (state.switchU && !noError) {
  20417. state.raise("Incomplete quantifier");
  20418. }
  20419. state.pos = start;
  20420. }
  20421. return false
  20422. };
  20423. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  20424. pp$1.regexp_eatAtom = function(state) {
  20425. return (
  20426. this.regexp_eatPatternCharacters(state) ||
  20427. state.eat(0x2E /* . */) ||
  20428. this.regexp_eatReverseSolidusAtomEscape(state) ||
  20429. this.regexp_eatCharacterClass(state) ||
  20430. this.regexp_eatUncapturingGroup(state) ||
  20431. this.regexp_eatCapturingGroup(state)
  20432. )
  20433. };
  20434. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  20435. var start = state.pos;
  20436. if (state.eat(0x5C /* \ */)) {
  20437. if (this.regexp_eatAtomEscape(state)) {
  20438. return true
  20439. }
  20440. state.pos = start;
  20441. }
  20442. return false
  20443. };
  20444. pp$1.regexp_eatUncapturingGroup = function(state) {
  20445. var start = state.pos;
  20446. if (state.eat(0x28 /* ( */)) {
  20447. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  20448. this.regexp_disjunction(state);
  20449. if (state.eat(0x29 /* ) */)) {
  20450. return true
  20451. }
  20452. state.raise("Unterminated group");
  20453. }
  20454. state.pos = start;
  20455. }
  20456. return false
  20457. };
  20458. pp$1.regexp_eatCapturingGroup = function(state) {
  20459. if (state.eat(0x28 /* ( */)) {
  20460. if (this.options.ecmaVersion >= 9) {
  20461. this.regexp_groupSpecifier(state);
  20462. } else if (state.current() === 0x3F /* ? */) {
  20463. state.raise("Invalid group");
  20464. }
  20465. this.regexp_disjunction(state);
  20466. if (state.eat(0x29 /* ) */)) {
  20467. state.numCapturingParens += 1;
  20468. return true
  20469. }
  20470. state.raise("Unterminated group");
  20471. }
  20472. return false
  20473. };
  20474. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  20475. pp$1.regexp_eatExtendedAtom = function(state) {
  20476. return (
  20477. state.eat(0x2E /* . */) ||
  20478. this.regexp_eatReverseSolidusAtomEscape(state) ||
  20479. this.regexp_eatCharacterClass(state) ||
  20480. this.regexp_eatUncapturingGroup(state) ||
  20481. this.regexp_eatCapturingGroup(state) ||
  20482. this.regexp_eatInvalidBracedQuantifier(state) ||
  20483. this.regexp_eatExtendedPatternCharacter(state)
  20484. )
  20485. };
  20486. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  20487. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  20488. if (this.regexp_eatBracedQuantifier(state, true)) {
  20489. state.raise("Nothing to repeat");
  20490. }
  20491. return false
  20492. };
  20493. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  20494. pp$1.regexp_eatSyntaxCharacter = function(state) {
  20495. var ch = state.current();
  20496. if (isSyntaxCharacter(ch)) {
  20497. state.lastIntValue = ch;
  20498. state.advance();
  20499. return true
  20500. }
  20501. return false
  20502. };
  20503. function isSyntaxCharacter(ch) {
  20504. return (
  20505. ch === 0x24 /* $ */ ||
  20506. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  20507. ch === 0x2E /* . */ ||
  20508. ch === 0x3F /* ? */ ||
  20509. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  20510. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  20511. )
  20512. }
  20513. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  20514. // But eat eager.
  20515. pp$1.regexp_eatPatternCharacters = function(state) {
  20516. var start = state.pos;
  20517. var ch = 0;
  20518. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  20519. state.advance();
  20520. }
  20521. return state.pos !== start
  20522. };
  20523. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  20524. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  20525. var ch = state.current();
  20526. if (
  20527. ch !== -1 &&
  20528. ch !== 0x24 /* $ */ &&
  20529. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  20530. ch !== 0x2E /* . */ &&
  20531. ch !== 0x3F /* ? */ &&
  20532. ch !== 0x5B /* [ */ &&
  20533. ch !== 0x5E /* ^ */ &&
  20534. ch !== 0x7C /* | */
  20535. ) {
  20536. state.advance();
  20537. return true
  20538. }
  20539. return false
  20540. };
  20541. // GroupSpecifier ::
  20542. // [empty]
  20543. // `?` GroupName
  20544. pp$1.regexp_groupSpecifier = function(state) {
  20545. if (state.eat(0x3F /* ? */)) {
  20546. if (this.regexp_eatGroupName(state)) {
  20547. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  20548. state.raise("Duplicate capture group name");
  20549. }
  20550. state.groupNames.push(state.lastStringValue);
  20551. return
  20552. }
  20553. state.raise("Invalid group");
  20554. }
  20555. };
  20556. // GroupName ::
  20557. // `<` RegExpIdentifierName `>`
  20558. // Note: this updates `state.lastStringValue` property with the eaten name.
  20559. pp$1.regexp_eatGroupName = function(state) {
  20560. state.lastStringValue = "";
  20561. if (state.eat(0x3C /* < */)) {
  20562. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  20563. return true
  20564. }
  20565. state.raise("Invalid capture group name");
  20566. }
  20567. return false
  20568. };
  20569. // RegExpIdentifierName ::
  20570. // RegExpIdentifierStart
  20571. // RegExpIdentifierName RegExpIdentifierPart
  20572. // Note: this updates `state.lastStringValue` property with the eaten name.
  20573. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  20574. state.lastStringValue = "";
  20575. if (this.regexp_eatRegExpIdentifierStart(state)) {
  20576. state.lastStringValue += codePointToString(state.lastIntValue);
  20577. while (this.regexp_eatRegExpIdentifierPart(state)) {
  20578. state.lastStringValue += codePointToString(state.lastIntValue);
  20579. }
  20580. return true
  20581. }
  20582. return false
  20583. };
  20584. // RegExpIdentifierStart ::
  20585. // UnicodeIDStart
  20586. // `$`
  20587. // `_`
  20588. // `\` RegExpUnicodeEscapeSequence[+U]
  20589. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  20590. var start = state.pos;
  20591. var forceU = this.options.ecmaVersion >= 11;
  20592. var ch = state.current(forceU);
  20593. state.advance(forceU);
  20594. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  20595. ch = state.lastIntValue;
  20596. }
  20597. if (isRegExpIdentifierStart(ch)) {
  20598. state.lastIntValue = ch;
  20599. return true
  20600. }
  20601. state.pos = start;
  20602. return false
  20603. };
  20604. function isRegExpIdentifierStart(ch) {
  20605. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  20606. }
  20607. // RegExpIdentifierPart ::
  20608. // UnicodeIDContinue
  20609. // `$`
  20610. // `_`
  20611. // `\` RegExpUnicodeEscapeSequence[+U]
  20612. // <ZWNJ>
  20613. // <ZWJ>
  20614. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  20615. var start = state.pos;
  20616. var forceU = this.options.ecmaVersion >= 11;
  20617. var ch = state.current(forceU);
  20618. state.advance(forceU);
  20619. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  20620. ch = state.lastIntValue;
  20621. }
  20622. if (isRegExpIdentifierPart(ch)) {
  20623. state.lastIntValue = ch;
  20624. return true
  20625. }
  20626. state.pos = start;
  20627. return false
  20628. };
  20629. function isRegExpIdentifierPart(ch) {
  20630. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  20631. }
  20632. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  20633. pp$1.regexp_eatAtomEscape = function(state) {
  20634. if (
  20635. this.regexp_eatBackReference(state) ||
  20636. this.regexp_eatCharacterClassEscape(state) ||
  20637. this.regexp_eatCharacterEscape(state) ||
  20638. (state.switchN && this.regexp_eatKGroupName(state))
  20639. ) {
  20640. return true
  20641. }
  20642. if (state.switchU) {
  20643. // Make the same message as V8.
  20644. if (state.current() === 0x63 /* c */) {
  20645. state.raise("Invalid unicode escape");
  20646. }
  20647. state.raise("Invalid escape");
  20648. }
  20649. return false
  20650. };
  20651. pp$1.regexp_eatBackReference = function(state) {
  20652. var start = state.pos;
  20653. if (this.regexp_eatDecimalEscape(state)) {
  20654. var n = state.lastIntValue;
  20655. if (state.switchU) {
  20656. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  20657. if (n > state.maxBackReference) {
  20658. state.maxBackReference = n;
  20659. }
  20660. return true
  20661. }
  20662. if (n <= state.numCapturingParens) {
  20663. return true
  20664. }
  20665. state.pos = start;
  20666. }
  20667. return false
  20668. };
  20669. pp$1.regexp_eatKGroupName = function(state) {
  20670. if (state.eat(0x6B /* k */)) {
  20671. if (this.regexp_eatGroupName(state)) {
  20672. state.backReferenceNames.push(state.lastStringValue);
  20673. return true
  20674. }
  20675. state.raise("Invalid named reference");
  20676. }
  20677. return false
  20678. };
  20679. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  20680. pp$1.regexp_eatCharacterEscape = function(state) {
  20681. return (
  20682. this.regexp_eatControlEscape(state) ||
  20683. this.regexp_eatCControlLetter(state) ||
  20684. this.regexp_eatZero(state) ||
  20685. this.regexp_eatHexEscapeSequence(state) ||
  20686. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  20687. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  20688. this.regexp_eatIdentityEscape(state)
  20689. )
  20690. };
  20691. pp$1.regexp_eatCControlLetter = function(state) {
  20692. var start = state.pos;
  20693. if (state.eat(0x63 /* c */)) {
  20694. if (this.regexp_eatControlLetter(state)) {
  20695. return true
  20696. }
  20697. state.pos = start;
  20698. }
  20699. return false
  20700. };
  20701. pp$1.regexp_eatZero = function(state) {
  20702. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  20703. state.lastIntValue = 0;
  20704. state.advance();
  20705. return true
  20706. }
  20707. return false
  20708. };
  20709. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  20710. pp$1.regexp_eatControlEscape = function(state) {
  20711. var ch = state.current();
  20712. if (ch === 0x74 /* t */) {
  20713. state.lastIntValue = 0x09; /* \t */
  20714. state.advance();
  20715. return true
  20716. }
  20717. if (ch === 0x6E /* n */) {
  20718. state.lastIntValue = 0x0A; /* \n */
  20719. state.advance();
  20720. return true
  20721. }
  20722. if (ch === 0x76 /* v */) {
  20723. state.lastIntValue = 0x0B; /* \v */
  20724. state.advance();
  20725. return true
  20726. }
  20727. if (ch === 0x66 /* f */) {
  20728. state.lastIntValue = 0x0C; /* \f */
  20729. state.advance();
  20730. return true
  20731. }
  20732. if (ch === 0x72 /* r */) {
  20733. state.lastIntValue = 0x0D; /* \r */
  20734. state.advance();
  20735. return true
  20736. }
  20737. return false
  20738. };
  20739. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  20740. pp$1.regexp_eatControlLetter = function(state) {
  20741. var ch = state.current();
  20742. if (isControlLetter(ch)) {
  20743. state.lastIntValue = ch % 0x20;
  20744. state.advance();
  20745. return true
  20746. }
  20747. return false
  20748. };
  20749. function isControlLetter(ch) {
  20750. return (
  20751. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  20752. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  20753. )
  20754. }
  20755. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  20756. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  20757. if ( forceU === void 0 ) forceU = false;
  20758. var start = state.pos;
  20759. var switchU = forceU || state.switchU;
  20760. if (state.eat(0x75 /* u */)) {
  20761. if (this.regexp_eatFixedHexDigits(state, 4)) {
  20762. var lead = state.lastIntValue;
  20763. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  20764. var leadSurrogateEnd = state.pos;
  20765. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  20766. var trail = state.lastIntValue;
  20767. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  20768. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  20769. return true
  20770. }
  20771. }
  20772. state.pos = leadSurrogateEnd;
  20773. state.lastIntValue = lead;
  20774. }
  20775. return true
  20776. }
  20777. if (
  20778. switchU &&
  20779. state.eat(0x7B /* { */) &&
  20780. this.regexp_eatHexDigits(state) &&
  20781. state.eat(0x7D /* } */) &&
  20782. isValidUnicode(state.lastIntValue)
  20783. ) {
  20784. return true
  20785. }
  20786. if (switchU) {
  20787. state.raise("Invalid unicode escape");
  20788. }
  20789. state.pos = start;
  20790. }
  20791. return false
  20792. };
  20793. function isValidUnicode(ch) {
  20794. return ch >= 0 && ch <= 0x10FFFF
  20795. }
  20796. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  20797. pp$1.regexp_eatIdentityEscape = function(state) {
  20798. if (state.switchU) {
  20799. if (this.regexp_eatSyntaxCharacter(state)) {
  20800. return true
  20801. }
  20802. if (state.eat(0x2F /* / */)) {
  20803. state.lastIntValue = 0x2F; /* / */
  20804. return true
  20805. }
  20806. return false
  20807. }
  20808. var ch = state.current();
  20809. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  20810. state.lastIntValue = ch;
  20811. state.advance();
  20812. return true
  20813. }
  20814. return false
  20815. };
  20816. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  20817. pp$1.regexp_eatDecimalEscape = function(state) {
  20818. state.lastIntValue = 0;
  20819. var ch = state.current();
  20820. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  20821. do {
  20822. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  20823. state.advance();
  20824. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  20825. return true
  20826. }
  20827. return false
  20828. };
  20829. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  20830. pp$1.regexp_eatCharacterClassEscape = function(state) {
  20831. var ch = state.current();
  20832. if (isCharacterClassEscape(ch)) {
  20833. state.lastIntValue = -1;
  20834. state.advance();
  20835. return true
  20836. }
  20837. if (
  20838. state.switchU &&
  20839. this.options.ecmaVersion >= 9 &&
  20840. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  20841. ) {
  20842. state.lastIntValue = -1;
  20843. state.advance();
  20844. if (
  20845. state.eat(0x7B /* { */) &&
  20846. this.regexp_eatUnicodePropertyValueExpression(state) &&
  20847. state.eat(0x7D /* } */)
  20848. ) {
  20849. return true
  20850. }
  20851. state.raise("Invalid property name");
  20852. }
  20853. return false
  20854. };
  20855. function isCharacterClassEscape(ch) {
  20856. return (
  20857. ch === 0x64 /* d */ ||
  20858. ch === 0x44 /* D */ ||
  20859. ch === 0x73 /* s */ ||
  20860. ch === 0x53 /* S */ ||
  20861. ch === 0x77 /* w */ ||
  20862. ch === 0x57 /* W */
  20863. )
  20864. }
  20865. // UnicodePropertyValueExpression ::
  20866. // UnicodePropertyName `=` UnicodePropertyValue
  20867. // LoneUnicodePropertyNameOrValue
  20868. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  20869. var start = state.pos;
  20870. // UnicodePropertyName `=` UnicodePropertyValue
  20871. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  20872. var name = state.lastStringValue;
  20873. if (this.regexp_eatUnicodePropertyValue(state)) {
  20874. var value = state.lastStringValue;
  20875. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  20876. return true
  20877. }
  20878. }
  20879. state.pos = start;
  20880. // LoneUnicodePropertyNameOrValue
  20881. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  20882. var nameOrValue = state.lastStringValue;
  20883. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  20884. return true
  20885. }
  20886. return false
  20887. };
  20888. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  20889. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  20890. { state.raise("Invalid property name"); }
  20891. if (!state.unicodeProperties.nonBinary[name].test(value))
  20892. { state.raise("Invalid property value"); }
  20893. };
  20894. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  20895. if (!state.unicodeProperties.binary.test(nameOrValue))
  20896. { state.raise("Invalid property name"); }
  20897. };
  20898. // UnicodePropertyName ::
  20899. // UnicodePropertyNameCharacters
  20900. pp$1.regexp_eatUnicodePropertyName = function(state) {
  20901. var ch = 0;
  20902. state.lastStringValue = "";
  20903. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  20904. state.lastStringValue += codePointToString(ch);
  20905. state.advance();
  20906. }
  20907. return state.lastStringValue !== ""
  20908. };
  20909. function isUnicodePropertyNameCharacter(ch) {
  20910. return isControlLetter(ch) || ch === 0x5F /* _ */
  20911. }
  20912. // UnicodePropertyValue ::
  20913. // UnicodePropertyValueCharacters
  20914. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  20915. var ch = 0;
  20916. state.lastStringValue = "";
  20917. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  20918. state.lastStringValue += codePointToString(ch);
  20919. state.advance();
  20920. }
  20921. return state.lastStringValue !== ""
  20922. };
  20923. function isUnicodePropertyValueCharacter(ch) {
  20924. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  20925. }
  20926. // LoneUnicodePropertyNameOrValue ::
  20927. // UnicodePropertyValueCharacters
  20928. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  20929. return this.regexp_eatUnicodePropertyValue(state)
  20930. };
  20931. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  20932. pp$1.regexp_eatCharacterClass = function(state) {
  20933. if (state.eat(0x5B /* [ */)) {
  20934. state.eat(0x5E /* ^ */);
  20935. this.regexp_classRanges(state);
  20936. if (state.eat(0x5D /* ] */)) {
  20937. return true
  20938. }
  20939. // Unreachable since it threw "unterminated regular expression" error before.
  20940. state.raise("Unterminated character class");
  20941. }
  20942. return false
  20943. };
  20944. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  20945. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  20946. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  20947. pp$1.regexp_classRanges = function(state) {
  20948. while (this.regexp_eatClassAtom(state)) {
  20949. var left = state.lastIntValue;
  20950. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  20951. var right = state.lastIntValue;
  20952. if (state.switchU && (left === -1 || right === -1)) {
  20953. state.raise("Invalid character class");
  20954. }
  20955. if (left !== -1 && right !== -1 && left > right) {
  20956. state.raise("Range out of order in character class");
  20957. }
  20958. }
  20959. }
  20960. };
  20961. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  20962. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  20963. pp$1.regexp_eatClassAtom = function(state) {
  20964. var start = state.pos;
  20965. if (state.eat(0x5C /* \ */)) {
  20966. if (this.regexp_eatClassEscape(state)) {
  20967. return true
  20968. }
  20969. if (state.switchU) {
  20970. // Make the same message as V8.
  20971. var ch$1 = state.current();
  20972. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  20973. state.raise("Invalid class escape");
  20974. }
  20975. state.raise("Invalid escape");
  20976. }
  20977. state.pos = start;
  20978. }
  20979. var ch = state.current();
  20980. if (ch !== 0x5D /* ] */) {
  20981. state.lastIntValue = ch;
  20982. state.advance();
  20983. return true
  20984. }
  20985. return false
  20986. };
  20987. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  20988. pp$1.regexp_eatClassEscape = function(state) {
  20989. var start = state.pos;
  20990. if (state.eat(0x62 /* b */)) {
  20991. state.lastIntValue = 0x08; /* <BS> */
  20992. return true
  20993. }
  20994. if (state.switchU && state.eat(0x2D /* - */)) {
  20995. state.lastIntValue = 0x2D; /* - */
  20996. return true
  20997. }
  20998. if (!state.switchU && state.eat(0x63 /* c */)) {
  20999. if (this.regexp_eatClassControlLetter(state)) {
  21000. return true
  21001. }
  21002. state.pos = start;
  21003. }
  21004. return (
  21005. this.regexp_eatCharacterClassEscape(state) ||
  21006. this.regexp_eatCharacterEscape(state)
  21007. )
  21008. };
  21009. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  21010. pp$1.regexp_eatClassControlLetter = function(state) {
  21011. var ch = state.current();
  21012. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  21013. state.lastIntValue = ch % 0x20;
  21014. state.advance();
  21015. return true
  21016. }
  21017. return false
  21018. };
  21019. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  21020. pp$1.regexp_eatHexEscapeSequence = function(state) {
  21021. var start = state.pos;
  21022. if (state.eat(0x78 /* x */)) {
  21023. if (this.regexp_eatFixedHexDigits(state, 2)) {
  21024. return true
  21025. }
  21026. if (state.switchU) {
  21027. state.raise("Invalid escape");
  21028. }
  21029. state.pos = start;
  21030. }
  21031. return false
  21032. };
  21033. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  21034. pp$1.regexp_eatDecimalDigits = function(state) {
  21035. var start = state.pos;
  21036. var ch = 0;
  21037. state.lastIntValue = 0;
  21038. while (isDecimalDigit(ch = state.current())) {
  21039. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  21040. state.advance();
  21041. }
  21042. return state.pos !== start
  21043. };
  21044. function isDecimalDigit(ch) {
  21045. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  21046. }
  21047. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  21048. pp$1.regexp_eatHexDigits = function(state) {
  21049. var start = state.pos;
  21050. var ch = 0;
  21051. state.lastIntValue = 0;
  21052. while (isHexDigit(ch = state.current())) {
  21053. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  21054. state.advance();
  21055. }
  21056. return state.pos !== start
  21057. };
  21058. function isHexDigit(ch) {
  21059. return (
  21060. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  21061. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  21062. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  21063. )
  21064. }
  21065. function hexToInt(ch) {
  21066. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  21067. return 10 + (ch - 0x41 /* A */)
  21068. }
  21069. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  21070. return 10 + (ch - 0x61 /* a */)
  21071. }
  21072. return ch - 0x30 /* 0 */
  21073. }
  21074. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  21075. // Allows only 0-377(octal) i.e. 0-255(decimal).
  21076. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  21077. if (this.regexp_eatOctalDigit(state)) {
  21078. var n1 = state.lastIntValue;
  21079. if (this.regexp_eatOctalDigit(state)) {
  21080. var n2 = state.lastIntValue;
  21081. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  21082. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  21083. } else {
  21084. state.lastIntValue = n1 * 8 + n2;
  21085. }
  21086. } else {
  21087. state.lastIntValue = n1;
  21088. }
  21089. return true
  21090. }
  21091. return false
  21092. };
  21093. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  21094. pp$1.regexp_eatOctalDigit = function(state) {
  21095. var ch = state.current();
  21096. if (isOctalDigit(ch)) {
  21097. state.lastIntValue = ch - 0x30; /* 0 */
  21098. state.advance();
  21099. return true
  21100. }
  21101. state.lastIntValue = 0;
  21102. return false
  21103. };
  21104. function isOctalDigit(ch) {
  21105. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  21106. }
  21107. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  21108. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  21109. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  21110. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  21111. var start = state.pos;
  21112. state.lastIntValue = 0;
  21113. for (var i = 0; i < length; ++i) {
  21114. var ch = state.current();
  21115. if (!isHexDigit(ch)) {
  21116. state.pos = start;
  21117. return false
  21118. }
  21119. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  21120. state.advance();
  21121. }
  21122. return true
  21123. };
  21124. // Object type used to represent tokens. Note that normally, tokens
  21125. // simply exist as properties on the parser object. This is only
  21126. // used for the onToken callback and the external tokenizer.
  21127. var Token = function Token(p) {
  21128. this.type = p.type;
  21129. this.value = p.value;
  21130. this.start = p.start;
  21131. this.end = p.end;
  21132. if (p.options.locations)
  21133. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  21134. if (p.options.ranges)
  21135. { this.range = [p.start, p.end]; }
  21136. };
  21137. // ## Tokenizer
  21138. var pp = Parser.prototype;
  21139. // Move to the next token
  21140. pp.next = function(ignoreEscapeSequenceInKeyword) {
  21141. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  21142. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  21143. if (this.options.onToken)
  21144. { this.options.onToken(new Token(this)); }
  21145. this.lastTokEnd = this.end;
  21146. this.lastTokStart = this.start;
  21147. this.lastTokEndLoc = this.endLoc;
  21148. this.lastTokStartLoc = this.startLoc;
  21149. this.nextToken();
  21150. };
  21151. pp.getToken = function() {
  21152. this.next();
  21153. return new Token(this)
  21154. };
  21155. // If we're in an ES6 environment, make parsers iterable
  21156. if (typeof Symbol !== "undefined")
  21157. { pp[Symbol.iterator] = function() {
  21158. var this$1$1 = this;
  21159. return {
  21160. next: function () {
  21161. var token = this$1$1.getToken();
  21162. return {
  21163. done: token.type === types$1.eof,
  21164. value: token
  21165. }
  21166. }
  21167. }
  21168. }; }
  21169. // Toggle strict mode. Re-reads the next number or string to please
  21170. // pedantic tests (`"use strict"; 010;` should fail).
  21171. // Read a single token, updating the parser object's token-related
  21172. // properties.
  21173. pp.nextToken = function() {
  21174. var curContext = this.curContext();
  21175. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  21176. this.start = this.pos;
  21177. if (this.options.locations) { this.startLoc = this.curPosition(); }
  21178. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  21179. if (curContext.override) { return curContext.override(this) }
  21180. else { this.readToken(this.fullCharCodeAtPos()); }
  21181. };
  21182. pp.readToken = function(code) {
  21183. // Identifier or keyword. '\uXXXX' sequences are allowed in
  21184. // identifiers, so '\' also dispatches to that.
  21185. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  21186. { return this.readWord() }
  21187. return this.getTokenFromCode(code)
  21188. };
  21189. pp.fullCharCodeAtPos = function() {
  21190. var code = this.input.charCodeAt(this.pos);
  21191. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  21192. var next = this.input.charCodeAt(this.pos + 1);
  21193. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  21194. };
  21195. pp.skipBlockComment = function() {
  21196. var startLoc = this.options.onComment && this.curPosition();
  21197. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  21198. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  21199. this.pos = end + 2;
  21200. if (this.options.locations) {
  21201. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  21202. ++this.curLine;
  21203. pos = this.lineStart = nextBreak;
  21204. }
  21205. }
  21206. if (this.options.onComment)
  21207. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  21208. startLoc, this.curPosition()); }
  21209. };
  21210. pp.skipLineComment = function(startSkip) {
  21211. var start = this.pos;
  21212. var startLoc = this.options.onComment && this.curPosition();
  21213. var ch = this.input.charCodeAt(this.pos += startSkip);
  21214. while (this.pos < this.input.length && !isNewLine(ch)) {
  21215. ch = this.input.charCodeAt(++this.pos);
  21216. }
  21217. if (this.options.onComment)
  21218. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  21219. startLoc, this.curPosition()); }
  21220. };
  21221. // Called at the start of the parse and after every token. Skips
  21222. // whitespace and comments, and.
  21223. pp.skipSpace = function() {
  21224. loop: while (this.pos < this.input.length) {
  21225. var ch = this.input.charCodeAt(this.pos);
  21226. switch (ch) {
  21227. case 32: case 160: // ' '
  21228. ++this.pos;
  21229. break
  21230. case 13:
  21231. if (this.input.charCodeAt(this.pos + 1) === 10) {
  21232. ++this.pos;
  21233. }
  21234. case 10: case 8232: case 8233:
  21235. ++this.pos;
  21236. if (this.options.locations) {
  21237. ++this.curLine;
  21238. this.lineStart = this.pos;
  21239. }
  21240. break
  21241. case 47: // '/'
  21242. switch (this.input.charCodeAt(this.pos + 1)) {
  21243. case 42: // '*'
  21244. this.skipBlockComment();
  21245. break
  21246. case 47:
  21247. this.skipLineComment(2);
  21248. break
  21249. default:
  21250. break loop
  21251. }
  21252. break
  21253. default:
  21254. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  21255. ++this.pos;
  21256. } else {
  21257. break loop
  21258. }
  21259. }
  21260. }
  21261. };
  21262. // Called at the end of every token. Sets `end`, `val`, and
  21263. // maintains `context` and `exprAllowed`, and skips the space after
  21264. // the token, so that the next one's `start` will point at the
  21265. // right position.
  21266. pp.finishToken = function(type, val) {
  21267. this.end = this.pos;
  21268. if (this.options.locations) { this.endLoc = this.curPosition(); }
  21269. var prevType = this.type;
  21270. this.type = type;
  21271. this.value = val;
  21272. this.updateContext(prevType);
  21273. };
  21274. // ### Token reading
  21275. // This is the function that is called to fetch the next token. It
  21276. // is somewhat obscure, because it works in character codes rather
  21277. // than characters, and because operator parsing has been inlined
  21278. // into it.
  21279. //
  21280. // All in the name of speed.
  21281. //
  21282. pp.readToken_dot = function() {
  21283. var next = this.input.charCodeAt(this.pos + 1);
  21284. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  21285. var next2 = this.input.charCodeAt(this.pos + 2);
  21286. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  21287. this.pos += 3;
  21288. return this.finishToken(types$1.ellipsis)
  21289. } else {
  21290. ++this.pos;
  21291. return this.finishToken(types$1.dot)
  21292. }
  21293. };
  21294. pp.readToken_slash = function() { // '/'
  21295. var next = this.input.charCodeAt(this.pos + 1);
  21296. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  21297. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21298. return this.finishOp(types$1.slash, 1)
  21299. };
  21300. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  21301. var next = this.input.charCodeAt(this.pos + 1);
  21302. var size = 1;
  21303. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  21304. // exponentiation operator ** and **=
  21305. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  21306. ++size;
  21307. tokentype = types$1.starstar;
  21308. next = this.input.charCodeAt(this.pos + 2);
  21309. }
  21310. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  21311. return this.finishOp(tokentype, size)
  21312. };
  21313. pp.readToken_pipe_amp = function(code) { // '|&'
  21314. var next = this.input.charCodeAt(this.pos + 1);
  21315. if (next === code) {
  21316. if (this.options.ecmaVersion >= 12) {
  21317. var next2 = this.input.charCodeAt(this.pos + 2);
  21318. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  21319. }
  21320. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  21321. }
  21322. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21323. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  21324. };
  21325. pp.readToken_caret = function() { // '^'
  21326. var next = this.input.charCodeAt(this.pos + 1);
  21327. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21328. return this.finishOp(types$1.bitwiseXOR, 1)
  21329. };
  21330. pp.readToken_plus_min = function(code) { // '+-'
  21331. var next = this.input.charCodeAt(this.pos + 1);
  21332. if (next === code) {
  21333. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  21334. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  21335. // A `-->` line comment
  21336. this.skipLineComment(3);
  21337. this.skipSpace();
  21338. return this.nextToken()
  21339. }
  21340. return this.finishOp(types$1.incDec, 2)
  21341. }
  21342. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21343. return this.finishOp(types$1.plusMin, 1)
  21344. };
  21345. pp.readToken_lt_gt = function(code) { // '<>'
  21346. var next = this.input.charCodeAt(this.pos + 1);
  21347. var size = 1;
  21348. if (next === code) {
  21349. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  21350. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  21351. return this.finishOp(types$1.bitShift, size)
  21352. }
  21353. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  21354. this.input.charCodeAt(this.pos + 3) === 45) {
  21355. // `<!--`, an XML-style comment that should be interpreted as a line comment
  21356. this.skipLineComment(4);
  21357. this.skipSpace();
  21358. return this.nextToken()
  21359. }
  21360. if (next === 61) { size = 2; }
  21361. return this.finishOp(types$1.relational, size)
  21362. };
  21363. pp.readToken_eq_excl = function(code) { // '=!'
  21364. var next = this.input.charCodeAt(this.pos + 1);
  21365. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  21366. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  21367. this.pos += 2;
  21368. return this.finishToken(types$1.arrow)
  21369. }
  21370. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  21371. };
  21372. pp.readToken_question = function() { // '?'
  21373. var ecmaVersion = this.options.ecmaVersion;
  21374. if (ecmaVersion >= 11) {
  21375. var next = this.input.charCodeAt(this.pos + 1);
  21376. if (next === 46) {
  21377. var next2 = this.input.charCodeAt(this.pos + 2);
  21378. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  21379. }
  21380. if (next === 63) {
  21381. if (ecmaVersion >= 12) {
  21382. var next2$1 = this.input.charCodeAt(this.pos + 2);
  21383. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  21384. }
  21385. return this.finishOp(types$1.coalesce, 2)
  21386. }
  21387. }
  21388. return this.finishOp(types$1.question, 1)
  21389. };
  21390. pp.readToken_numberSign = function() { // '#'
  21391. var ecmaVersion = this.options.ecmaVersion;
  21392. var code = 35; // '#'
  21393. if (ecmaVersion >= 13) {
  21394. ++this.pos;
  21395. code = this.fullCharCodeAtPos();
  21396. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  21397. return this.finishToken(types$1.privateId, this.readWord1())
  21398. }
  21399. }
  21400. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  21401. };
  21402. pp.getTokenFromCode = function(code) {
  21403. switch (code) {
  21404. // The interpretation of a dot depends on whether it is followed
  21405. // by a digit or another two dots.
  21406. case 46: // '.'
  21407. return this.readToken_dot()
  21408. // Punctuation tokens.
  21409. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  21410. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  21411. case 59: ++this.pos; return this.finishToken(types$1.semi)
  21412. case 44: ++this.pos; return this.finishToken(types$1.comma)
  21413. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  21414. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  21415. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  21416. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  21417. case 58: ++this.pos; return this.finishToken(types$1.colon)
  21418. case 96: // '`'
  21419. if (this.options.ecmaVersion < 6) { break }
  21420. ++this.pos;
  21421. return this.finishToken(types$1.backQuote)
  21422. case 48: // '0'
  21423. var next = this.input.charCodeAt(this.pos + 1);
  21424. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  21425. if (this.options.ecmaVersion >= 6) {
  21426. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  21427. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  21428. }
  21429. // Anything else beginning with a digit is an integer, octal
  21430. // number, or float.
  21431. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  21432. return this.readNumber(false)
  21433. // Quotes produce strings.
  21434. case 34: case 39: // '"', "'"
  21435. return this.readString(code)
  21436. // Operators are parsed inline in tiny state machines. '=' (61) is
  21437. // often referred to. `finishOp` simply skips the amount of
  21438. // characters it is given as second argument, and returns a token
  21439. // of the type given by its first argument.
  21440. case 47: // '/'
  21441. return this.readToken_slash()
  21442. case 37: case 42: // '%*'
  21443. return this.readToken_mult_modulo_exp(code)
  21444. case 124: case 38: // '|&'
  21445. return this.readToken_pipe_amp(code)
  21446. case 94: // '^'
  21447. return this.readToken_caret()
  21448. case 43: case 45: // '+-'
  21449. return this.readToken_plus_min(code)
  21450. case 60: case 62: // '<>'
  21451. return this.readToken_lt_gt(code)
  21452. case 61: case 33: // '=!'
  21453. return this.readToken_eq_excl(code)
  21454. case 63: // '?'
  21455. return this.readToken_question()
  21456. case 126: // '~'
  21457. return this.finishOp(types$1.prefix, 1)
  21458. case 35: // '#'
  21459. return this.readToken_numberSign()
  21460. }
  21461. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  21462. };
  21463. pp.finishOp = function(type, size) {
  21464. var str = this.input.slice(this.pos, this.pos + size);
  21465. this.pos += size;
  21466. return this.finishToken(type, str)
  21467. };
  21468. pp.readRegexp = function() {
  21469. var escaped, inClass, start = this.pos;
  21470. for (;;) {
  21471. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  21472. var ch = this.input.charAt(this.pos);
  21473. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  21474. if (!escaped) {
  21475. if (ch === "[") { inClass = true; }
  21476. else if (ch === "]" && inClass) { inClass = false; }
  21477. else if (ch === "/" && !inClass) { break }
  21478. escaped = ch === "\\";
  21479. } else { escaped = false; }
  21480. ++this.pos;
  21481. }
  21482. var pattern = this.input.slice(start, this.pos);
  21483. ++this.pos;
  21484. var flagsStart = this.pos;
  21485. var flags = this.readWord1();
  21486. if (this.containsEsc) { this.unexpected(flagsStart); }
  21487. // Validate pattern
  21488. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  21489. state.reset(start, pattern, flags);
  21490. this.validateRegExpFlags(state);
  21491. this.validateRegExpPattern(state);
  21492. // Create Literal#value property value.
  21493. var value = null;
  21494. try {
  21495. value = new RegExp(pattern, flags);
  21496. } catch (e) {
  21497. // ESTree requires null if it failed to instantiate RegExp object.
  21498. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  21499. }
  21500. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  21501. };
  21502. // Read an integer in the given radix. Return null if zero digits
  21503. // were read, the integer value otherwise. When `len` is given, this
  21504. // will return `null` unless the integer has exactly `len` digits.
  21505. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  21506. // `len` is used for character escape sequences. In that case, disallow separators.
  21507. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  21508. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  21509. // and isn't fraction part nor exponent part. In that case, if the first digit
  21510. // is zero then disallow separators.
  21511. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  21512. var start = this.pos, total = 0, lastCode = 0;
  21513. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  21514. var code = this.input.charCodeAt(this.pos), val = (void 0);
  21515. if (allowSeparators && code === 95) {
  21516. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  21517. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  21518. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  21519. lastCode = code;
  21520. continue
  21521. }
  21522. if (code >= 97) { val = code - 97 + 10; } // a
  21523. else if (code >= 65) { val = code - 65 + 10; } // A
  21524. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  21525. else { val = Infinity; }
  21526. if (val >= radix) { break }
  21527. lastCode = code;
  21528. total = total * radix + val;
  21529. }
  21530. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  21531. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  21532. return total
  21533. };
  21534. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  21535. if (isLegacyOctalNumericLiteral) {
  21536. return parseInt(str, 8)
  21537. }
  21538. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  21539. return parseFloat(str.replace(/_/g, ""))
  21540. }
  21541. function stringToBigInt(str) {
  21542. if (typeof BigInt !== "function") {
  21543. return null
  21544. }
  21545. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  21546. return BigInt(str.replace(/_/g, ""))
  21547. }
  21548. pp.readRadixNumber = function(radix) {
  21549. var start = this.pos;
  21550. this.pos += 2; // 0x
  21551. var val = this.readInt(radix);
  21552. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  21553. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  21554. val = stringToBigInt(this.input.slice(start, this.pos));
  21555. ++this.pos;
  21556. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  21557. return this.finishToken(types$1.num, val)
  21558. };
  21559. // Read an integer, octal integer, or floating-point number.
  21560. pp.readNumber = function(startsWithDot) {
  21561. var start = this.pos;
  21562. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  21563. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  21564. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  21565. var next = this.input.charCodeAt(this.pos);
  21566. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  21567. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  21568. ++this.pos;
  21569. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  21570. return this.finishToken(types$1.num, val$1)
  21571. }
  21572. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  21573. if (next === 46 && !octal) { // '.'
  21574. ++this.pos;
  21575. this.readInt(10);
  21576. next = this.input.charCodeAt(this.pos);
  21577. }
  21578. if ((next === 69 || next === 101) && !octal) { // 'eE'
  21579. next = this.input.charCodeAt(++this.pos);
  21580. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  21581. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  21582. }
  21583. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  21584. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  21585. return this.finishToken(types$1.num, val)
  21586. };
  21587. // Read a string value, interpreting backslash-escapes.
  21588. pp.readCodePoint = function() {
  21589. var ch = this.input.charCodeAt(this.pos), code;
  21590. if (ch === 123) { // '{'
  21591. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  21592. var codePos = ++this.pos;
  21593. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  21594. ++this.pos;
  21595. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  21596. } else {
  21597. code = this.readHexChar(4);
  21598. }
  21599. return code
  21600. };
  21601. pp.readString = function(quote) {
  21602. var out = "", chunkStart = ++this.pos;
  21603. for (;;) {
  21604. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  21605. var ch = this.input.charCodeAt(this.pos);
  21606. if (ch === quote) { break }
  21607. if (ch === 92) { // '\'
  21608. out += this.input.slice(chunkStart, this.pos);
  21609. out += this.readEscapedChar(false);
  21610. chunkStart = this.pos;
  21611. } else if (ch === 0x2028 || ch === 0x2029) {
  21612. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  21613. ++this.pos;
  21614. if (this.options.locations) {
  21615. this.curLine++;
  21616. this.lineStart = this.pos;
  21617. }
  21618. } else {
  21619. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  21620. ++this.pos;
  21621. }
  21622. }
  21623. out += this.input.slice(chunkStart, this.pos++);
  21624. return this.finishToken(types$1.string, out)
  21625. };
  21626. // Reads template string tokens.
  21627. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  21628. pp.tryReadTemplateToken = function() {
  21629. this.inTemplateElement = true;
  21630. try {
  21631. this.readTmplToken();
  21632. } catch (err) {
  21633. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  21634. this.readInvalidTemplateToken();
  21635. } else {
  21636. throw err
  21637. }
  21638. }
  21639. this.inTemplateElement = false;
  21640. };
  21641. pp.invalidStringToken = function(position, message) {
  21642. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  21643. throw INVALID_TEMPLATE_ESCAPE_ERROR
  21644. } else {
  21645. this.raise(position, message);
  21646. }
  21647. };
  21648. pp.readTmplToken = function() {
  21649. var out = "", chunkStart = this.pos;
  21650. for (;;) {
  21651. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  21652. var ch = this.input.charCodeAt(this.pos);
  21653. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  21654. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  21655. if (ch === 36) {
  21656. this.pos += 2;
  21657. return this.finishToken(types$1.dollarBraceL)
  21658. } else {
  21659. ++this.pos;
  21660. return this.finishToken(types$1.backQuote)
  21661. }
  21662. }
  21663. out += this.input.slice(chunkStart, this.pos);
  21664. return this.finishToken(types$1.template, out)
  21665. }
  21666. if (ch === 92) { // '\'
  21667. out += this.input.slice(chunkStart, this.pos);
  21668. out += this.readEscapedChar(true);
  21669. chunkStart = this.pos;
  21670. } else if (isNewLine(ch)) {
  21671. out += this.input.slice(chunkStart, this.pos);
  21672. ++this.pos;
  21673. switch (ch) {
  21674. case 13:
  21675. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  21676. case 10:
  21677. out += "\n";
  21678. break
  21679. default:
  21680. out += String.fromCharCode(ch);
  21681. break
  21682. }
  21683. if (this.options.locations) {
  21684. ++this.curLine;
  21685. this.lineStart = this.pos;
  21686. }
  21687. chunkStart = this.pos;
  21688. } else {
  21689. ++this.pos;
  21690. }
  21691. }
  21692. };
  21693. // Reads a template token to search for the end, without validating any escape sequences
  21694. pp.readInvalidTemplateToken = function() {
  21695. for (; this.pos < this.input.length; this.pos++) {
  21696. switch (this.input[this.pos]) {
  21697. case "\\":
  21698. ++this.pos;
  21699. break
  21700. case "$":
  21701. if (this.input[this.pos + 1] !== "{") {
  21702. break
  21703. }
  21704. // falls through
  21705. case "`":
  21706. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  21707. // no default
  21708. }
  21709. }
  21710. this.raise(this.start, "Unterminated template");
  21711. };
  21712. // Used to read escaped characters
  21713. pp.readEscapedChar = function(inTemplate) {
  21714. var ch = this.input.charCodeAt(++this.pos);
  21715. ++this.pos;
  21716. switch (ch) {
  21717. case 110: return "\n" // 'n' -> '\n'
  21718. case 114: return "\r" // 'r' -> '\r'
  21719. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  21720. case 117: return codePointToString(this.readCodePoint()) // 'u'
  21721. case 116: return "\t" // 't' -> '\t'
  21722. case 98: return "\b" // 'b' -> '\b'
  21723. case 118: return "\u000b" // 'v' -> '\u000b'
  21724. case 102: return "\f" // 'f' -> '\f'
  21725. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  21726. case 10: // ' \n'
  21727. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  21728. return ""
  21729. case 56:
  21730. case 57:
  21731. if (this.strict) {
  21732. this.invalidStringToken(
  21733. this.pos - 1,
  21734. "Invalid escape sequence"
  21735. );
  21736. }
  21737. if (inTemplate) {
  21738. var codePos = this.pos - 1;
  21739. this.invalidStringToken(
  21740. codePos,
  21741. "Invalid escape sequence in template string"
  21742. );
  21743. return null
  21744. }
  21745. default:
  21746. if (ch >= 48 && ch <= 55) {
  21747. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  21748. var octal = parseInt(octalStr, 8);
  21749. if (octal > 255) {
  21750. octalStr = octalStr.slice(0, -1);
  21751. octal = parseInt(octalStr, 8);
  21752. }
  21753. this.pos += octalStr.length - 1;
  21754. ch = this.input.charCodeAt(this.pos);
  21755. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  21756. this.invalidStringToken(
  21757. this.pos - 1 - octalStr.length,
  21758. inTemplate
  21759. ? "Octal literal in template string"
  21760. : "Octal literal in strict mode"
  21761. );
  21762. }
  21763. return String.fromCharCode(octal)
  21764. }
  21765. if (isNewLine(ch)) {
  21766. // Unicode new line characters after \ get removed from output in both
  21767. // template literals and strings
  21768. return ""
  21769. }
  21770. return String.fromCharCode(ch)
  21771. }
  21772. };
  21773. // Used to read character escape sequences ('\x', '\u', '\U').
  21774. pp.readHexChar = function(len) {
  21775. var codePos = this.pos;
  21776. var n = this.readInt(16, len);
  21777. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  21778. return n
  21779. };
  21780. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  21781. // to whether the word contained a '\u' escape.
  21782. //
  21783. // Incrementally adds only escaped chars, adding other chunks as-is
  21784. // as a micro-optimization.
  21785. pp.readWord1 = function() {
  21786. this.containsEsc = false;
  21787. var word = "", first = true, chunkStart = this.pos;
  21788. var astral = this.options.ecmaVersion >= 6;
  21789. while (this.pos < this.input.length) {
  21790. var ch = this.fullCharCodeAtPos();
  21791. if (isIdentifierChar(ch, astral)) {
  21792. this.pos += ch <= 0xffff ? 1 : 2;
  21793. } else if (ch === 92) { // "\"
  21794. this.containsEsc = true;
  21795. word += this.input.slice(chunkStart, this.pos);
  21796. var escStart = this.pos;
  21797. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  21798. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  21799. ++this.pos;
  21800. var esc = this.readCodePoint();
  21801. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  21802. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  21803. word += codePointToString(esc);
  21804. chunkStart = this.pos;
  21805. } else {
  21806. break
  21807. }
  21808. first = false;
  21809. }
  21810. return word + this.input.slice(chunkStart, this.pos)
  21811. };
  21812. // Read an identifier or keyword token. Will check for reserved
  21813. // words when necessary.
  21814. pp.readWord = function() {
  21815. var word = this.readWord1();
  21816. var type = types$1.name;
  21817. if (this.keywords.test(word)) {
  21818. type = keywords[word];
  21819. }
  21820. return this.finishToken(type, word)
  21821. };
  21822. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  21823. var version = "8.8.1";
  21824. Parser.acorn = {
  21825. Parser: Parser,
  21826. version: version,
  21827. defaultOptions: defaultOptions,
  21828. Position: Position,
  21829. SourceLocation: SourceLocation,
  21830. getLineInfo: getLineInfo,
  21831. Node: Node,
  21832. TokenType: TokenType,
  21833. tokTypes: types$1,
  21834. keywordTypes: keywords,
  21835. TokContext: TokContext,
  21836. tokContexts: types,
  21837. isIdentifierChar: isIdentifierChar,
  21838. isIdentifierStart: isIdentifierStart,
  21839. Token: Token,
  21840. isNewLine: isNewLine,
  21841. lineBreak: lineBreak,
  21842. lineBreakG: lineBreakG,
  21843. nonASCIIwhitespace: nonASCIIwhitespace
  21844. };
  21845. // The main exported interface (under `self.acorn` when in the
  21846. // browser) is a `parse` function that takes a code string and
  21847. // returns an abstract syntax tree as specified by [Mozilla parser
  21848. // API][api].
  21849. //
  21850. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  21851. function parse(input, options) {
  21852. return Parser.parse(input, options)
  21853. }
  21854. // This function tries to parse a single expression at a given
  21855. // offset in a string. Useful for parsing mixed-language formats
  21856. // that embed JavaScript expressions.
  21857. function parseExpressionAt(input, pos, options) {
  21858. return Parser.parseExpressionAt(input, pos, options)
  21859. }
  21860. // Acorn is organized as a tokenizer and a recursive-descent parser.
  21861. // The `tokenizer` export provides an interface to the tokenizer.
  21862. function tokenizer(input, options) {
  21863. return Parser.tokenizer(input, options)
  21864. }
  21865. const _acorn = /*#__PURE__*/Object.defineProperty({
  21866. __proto__: null,
  21867. Node,
  21868. Parser,
  21869. Position,
  21870. SourceLocation,
  21871. TokContext,
  21872. Token,
  21873. TokenType,
  21874. defaultOptions,
  21875. getLineInfo,
  21876. isIdentifierChar,
  21877. isIdentifierStart,
  21878. isNewLine,
  21879. keywordTypes: keywords,
  21880. lineBreak,
  21881. lineBreakG,
  21882. nonASCIIwhitespace,
  21883. parse,
  21884. parseExpressionAt,
  21885. tokContexts: types,
  21886. tokTypes: types$1,
  21887. tokenizer,
  21888. version
  21889. }, Symbol.toStringTag, { value: 'Module' });
  21890. function flru (max) {
  21891. var num, curr, prev;
  21892. var limit = max || 1;
  21893. function keep(key, value) {
  21894. if (++num > limit) {
  21895. prev = curr;
  21896. reset(1);
  21897. ++num;
  21898. }
  21899. curr[key] = value;
  21900. }
  21901. function reset(isPartial) {
  21902. num = 0;
  21903. curr = Object.create(null);
  21904. isPartial || (prev=Object.create(null));
  21905. }
  21906. reset();
  21907. return {
  21908. clear: reset,
  21909. has: function (key) {
  21910. return curr[key] !== void 0 || prev[key] !== void 0;
  21911. },
  21912. get: function (key) {
  21913. var val = curr[key];
  21914. if (val !== void 0) return val;
  21915. if ((val=prev[key]) !== void 0) {
  21916. keep(key, val);
  21917. return val;
  21918. }
  21919. },
  21920. set: function (key, value) {
  21921. if (curr[key] !== void 0) {
  21922. curr[key] = value;
  21923. } else {
  21924. keep(key, value);
  21925. }
  21926. }
  21927. };
  21928. }
  21929. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions) {
  21930. let skipped = null;
  21931. let replaceContext = null;
  21932. if (skip) {
  21933. skipped = new Set();
  21934. for (const skippedCall of skip) {
  21935. if (source === skippedCall.source && importer === skippedCall.importer) {
  21936. skipped.add(skippedCall.plugin);
  21937. }
  21938. }
  21939. replaceContext = (pluginContext, plugin) => ({
  21940. ...pluginContext,
  21941. resolve: (source, importer, { assertions, custom, isEntry, skipSelf } = BLANK) => moduleLoaderResolveId(source, importer, custom, isEntry, assertions || EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip)
  21942. });
  21943. }
  21944. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { assertions, custom: customOptions, isEntry }], replaceContext, skipped);
  21945. }
  21946. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions) {
  21947. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions);
  21948. if (pluginResult != null) {
  21949. const [resolveIdResult, plugin] = pluginResult;
  21950. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  21951. return {
  21952. ...resolveIdResult,
  21953. resolvedBy: plugin.name
  21954. };
  21955. }
  21956. if (typeof resolveIdResult === 'string') {
  21957. return {
  21958. id: resolveIdResult,
  21959. resolvedBy: plugin.name
  21960. };
  21961. }
  21962. return resolveIdResult;
  21963. }
  21964. // external modules (non-entry modules that start with neither '.' or '/')
  21965. // are skipped at this stage.
  21966. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  21967. return null;
  21968. // `resolve` processes paths from right to left, prepending them until an
  21969. // absolute path is created. Absolute importees therefore shortcircuit the
  21970. // resolve call and require no special handing on our part.
  21971. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  21972. return addJsExtensionIfNecessary(importer ? node_path.resolve(node_path.dirname(importer), source) : node_path.resolve(source), preserveSymlinks);
  21973. }
  21974. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  21975. return ((await findFile(file, preserveSymlinks)) ??
  21976. (await findFile(file + '.mjs', preserveSymlinks)) ??
  21977. (await findFile(file + '.js', preserveSymlinks)));
  21978. }
  21979. async function findFile(file, preserveSymlinks) {
  21980. try {
  21981. const stats = await promises.lstat(file);
  21982. if (!preserveSymlinks && stats.isSymbolicLink())
  21983. return await findFile(await promises.realpath(file), preserveSymlinks);
  21984. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  21985. // check case
  21986. const name = node_path.basename(file);
  21987. const files = await promises.readdir(node_path.dirname(file));
  21988. if (files.includes(name))
  21989. return file;
  21990. }
  21991. }
  21992. catch {
  21993. // suppress
  21994. }
  21995. }
  21996. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  21997. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  21998. function createPluginCache(cache) {
  21999. return {
  22000. delete(id) {
  22001. return delete cache[id];
  22002. },
  22003. get(id) {
  22004. const item = cache[id];
  22005. if (!item)
  22006. return;
  22007. item[0] = 0;
  22008. return item[1];
  22009. },
  22010. has(id) {
  22011. const item = cache[id];
  22012. if (!item)
  22013. return false;
  22014. item[0] = 0;
  22015. return true;
  22016. },
  22017. set(id, value) {
  22018. cache[id] = [0, value];
  22019. }
  22020. };
  22021. }
  22022. function getTrackedPluginCache(pluginCache, onUse) {
  22023. return {
  22024. delete(id) {
  22025. onUse();
  22026. return pluginCache.delete(id);
  22027. },
  22028. get(id) {
  22029. onUse();
  22030. return pluginCache.get(id);
  22031. },
  22032. has(id) {
  22033. onUse();
  22034. return pluginCache.has(id);
  22035. },
  22036. set(id, value) {
  22037. onUse();
  22038. return pluginCache.set(id, value);
  22039. }
  22040. };
  22041. }
  22042. const NO_CACHE = {
  22043. delete() {
  22044. return false;
  22045. },
  22046. get() {
  22047. return undefined;
  22048. },
  22049. has() {
  22050. return false;
  22051. },
  22052. set() { }
  22053. };
  22054. function uncacheablePluginError(pluginName) {
  22055. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  22056. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  22057. return error(errorAnonymousPluginCache());
  22058. }
  22059. return error(errorDuplicatePluginName(pluginName));
  22060. }
  22061. function getCacheForUncacheablePlugin(pluginName) {
  22062. return {
  22063. delete() {
  22064. return uncacheablePluginError(pluginName);
  22065. },
  22066. get() {
  22067. return uncacheablePluginError(pluginName);
  22068. },
  22069. has() {
  22070. return uncacheablePluginError(pluginName);
  22071. },
  22072. set() {
  22073. return uncacheablePluginError(pluginName);
  22074. }
  22075. };
  22076. }
  22077. async function transform(source, module, pluginDriver, warn) {
  22078. const id = module.id;
  22079. const sourcemapChain = [];
  22080. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  22081. const originalCode = source.code;
  22082. let ast = source.ast;
  22083. const transformDependencies = [];
  22084. const emittedFiles = [];
  22085. let customTransformCache = false;
  22086. const useCustomTransformCache = () => (customTransformCache = true);
  22087. let pluginName = '';
  22088. const currentSource = source.code;
  22089. function transformReducer(previousCode, result, plugin) {
  22090. let code;
  22091. let map;
  22092. if (typeof result === 'string') {
  22093. code = result;
  22094. }
  22095. else if (result && typeof result === 'object') {
  22096. module.updateOptions(result);
  22097. if (result.code == null) {
  22098. if (result.map || result.ast) {
  22099. warn(errorNoTransformMapOrAstWithoutCode(plugin.name));
  22100. }
  22101. return previousCode;
  22102. }
  22103. ({ code, map, ast } = result);
  22104. }
  22105. else {
  22106. return previousCode;
  22107. }
  22108. // strict null check allows 'null' maps to not be pushed to the chain,
  22109. // while 'undefined' gets the missing map warning
  22110. if (map !== null) {
  22111. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  22112. missing: true,
  22113. plugin: plugin.name
  22114. });
  22115. }
  22116. return code;
  22117. }
  22118. let code;
  22119. try {
  22120. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  22121. pluginName = plugin.name;
  22122. return {
  22123. ...pluginContext,
  22124. addWatchFile(id) {
  22125. transformDependencies.push(id);
  22126. pluginContext.addWatchFile(id);
  22127. },
  22128. cache: customTransformCache
  22129. ? pluginContext.cache
  22130. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  22131. emitFile(emittedFile) {
  22132. emittedFiles.push(emittedFile);
  22133. return pluginDriver.emitFile(emittedFile);
  22134. },
  22135. error(error_, pos) {
  22136. if (typeof error_ === 'string')
  22137. error_ = { message: error_ };
  22138. if (pos)
  22139. augmentCodeLocation(error_, pos, currentSource, id);
  22140. error_.id = id;
  22141. error_.hook = 'transform';
  22142. return pluginContext.error(error_);
  22143. },
  22144. getCombinedSourcemap() {
  22145. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  22146. if (!combinedMap) {
  22147. const magicString = new MagicString(originalCode);
  22148. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  22149. }
  22150. if (originalSourcemap !== combinedMap) {
  22151. originalSourcemap = combinedMap;
  22152. sourcemapChain.length = 0;
  22153. }
  22154. return new SourceMap({
  22155. ...combinedMap,
  22156. file: null,
  22157. sourcesContent: combinedMap.sourcesContent
  22158. });
  22159. },
  22160. setAssetSource() {
  22161. return this.error(errorInvalidSetAssetSourceCall());
  22162. },
  22163. warn(warning, pos) {
  22164. if (typeof warning === 'string')
  22165. warning = { message: warning };
  22166. if (pos)
  22167. augmentCodeLocation(warning, pos, currentSource, id);
  22168. warning.id = id;
  22169. warning.hook = 'transform';
  22170. pluginContext.warn(warning);
  22171. }
  22172. };
  22173. });
  22174. }
  22175. catch (error_) {
  22176. return error(errorPluginError(error_, pluginName, { hook: 'transform', id }));
  22177. }
  22178. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  22179. emittedFiles.length > 0)
  22180. module.transformFiles = emittedFiles;
  22181. return {
  22182. ast,
  22183. code,
  22184. customTransformCache,
  22185. originalCode,
  22186. originalSourcemap,
  22187. sourcemapChain,
  22188. transformDependencies
  22189. };
  22190. }
  22191. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  22192. class ModuleLoader {
  22193. constructor(graph, modulesById, options, pluginDriver) {
  22194. this.graph = graph;
  22195. this.modulesById = modulesById;
  22196. this.options = options;
  22197. this.pluginDriver = pluginDriver;
  22198. this.implicitEntryModules = new Set();
  22199. this.indexedEntryModules = [];
  22200. this.latestLoadModulesPromise = Promise.resolve();
  22201. this.moduleLoadPromises = new Map();
  22202. this.modulesWithLoadedDependencies = new Set();
  22203. this.nextChunkNamePriority = 0;
  22204. this.nextEntryModuleIndex = 0;
  22205. this.resolveId = async (source, importer, customOptions, isEntry, assertions, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  22206. ? false
  22207. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, assertions), importer, source), assertions);
  22208. this.hasModuleSideEffects = options.treeshake
  22209. ? options.treeshake.moduleSideEffects
  22210. : () => true;
  22211. }
  22212. async addAdditionalModules(unresolvedModules) {
  22213. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  22214. await this.awaitLoadModulesPromise();
  22215. return result;
  22216. }
  22217. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  22218. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  22219. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  22220. const firstChunkNamePriority = this.nextChunkNamePriority;
  22221. this.nextChunkNamePriority += unresolvedEntryModules.length;
  22222. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  22223. for (const [index, entryModule] of entryModules.entries()) {
  22224. entryModule.isUserDefinedEntryPoint =
  22225. entryModule.isUserDefinedEntryPoint || isUserDefined;
  22226. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  22227. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  22228. if (existingIndexedModule) {
  22229. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  22230. }
  22231. else {
  22232. this.indexedEntryModules.push({
  22233. index: firstEntryModuleIndex + index,
  22234. module: entryModule
  22235. });
  22236. }
  22237. }
  22238. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  22239. return entryModules;
  22240. }));
  22241. await this.awaitLoadModulesPromise();
  22242. return {
  22243. entryModules: this.indexedEntryModules.map(({ module }) => module),
  22244. implicitEntryModules: [...this.implicitEntryModules],
  22245. newEntryModules
  22246. };
  22247. }
  22248. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  22249. const unresolvedModule = {
  22250. fileName: fileName || null,
  22251. id,
  22252. importer,
  22253. name: name || null
  22254. };
  22255. const module = implicitlyLoadedAfterOneOf
  22256. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  22257. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  22258. if (preserveSignature != null) {
  22259. module.preserveSignature = preserveSignature;
  22260. }
  22261. return module;
  22262. }
  22263. async preloadModule(resolvedId) {
  22264. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  22265. return module.info;
  22266. }
  22267. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  22268. const chunkNamePriority = this.nextChunkNamePriority++;
  22269. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  22270. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  22271. if (!entryModule.info.isEntry) {
  22272. this.implicitEntryModules.add(entryModule);
  22273. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  22274. for (const module of implicitlyLoadedAfterModules) {
  22275. entryModule.implicitlyLoadedAfter.add(module);
  22276. }
  22277. for (const dependant of entryModule.implicitlyLoadedAfter) {
  22278. dependant.implicitlyLoadedBefore.add(entryModule);
  22279. }
  22280. }
  22281. return entryModule;
  22282. }));
  22283. }
  22284. async addModuleSource(id, importer, module) {
  22285. let source;
  22286. try {
  22287. source = await this.graph.fileOperationQueue.run(async () => (await this.pluginDriver.hookFirst('load', [id])) ?? (await promises.readFile(id, 'utf8')));
  22288. }
  22289. catch (error_) {
  22290. let message = `Could not load ${id}`;
  22291. if (importer)
  22292. message += ` (imported by ${relativeId(importer)})`;
  22293. message += `: ${error_.message}`;
  22294. error_.message = message;
  22295. throw error_;
  22296. }
  22297. const sourceDescription = typeof source === 'string'
  22298. ? { code: source }
  22299. : source != null && typeof source === 'object' && typeof source.code === 'string'
  22300. ? source
  22301. : error(errorBadLoader(id));
  22302. const cachedModule = this.graph.cachedModules.get(id);
  22303. if (cachedModule &&
  22304. !cachedModule.customTransformCache &&
  22305. cachedModule.originalCode === sourceDescription.code &&
  22306. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  22307. {
  22308. ast: cachedModule.ast,
  22309. code: cachedModule.code,
  22310. id: cachedModule.id,
  22311. meta: cachedModule.meta,
  22312. moduleSideEffects: cachedModule.moduleSideEffects,
  22313. resolvedSources: cachedModule.resolvedIds,
  22314. syntheticNamedExports: cachedModule.syntheticNamedExports
  22315. }
  22316. ]))) {
  22317. if (cachedModule.transformFiles) {
  22318. for (const emittedFile of cachedModule.transformFiles)
  22319. this.pluginDriver.emitFile(emittedFile);
  22320. }
  22321. module.setSource(cachedModule);
  22322. }
  22323. else {
  22324. module.updateOptions(sourceDescription);
  22325. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  22326. }
  22327. }
  22328. async awaitLoadModulesPromise() {
  22329. let startingPromise;
  22330. do {
  22331. startingPromise = this.latestLoadModulesPromise;
  22332. await startingPromise;
  22333. } while (startingPromise !== this.latestLoadModulesPromise);
  22334. }
  22335. extendLoadModulesPromise(loadNewModulesPromise) {
  22336. this.latestLoadModulesPromise = Promise.all([
  22337. loadNewModulesPromise,
  22338. this.latestLoadModulesPromise
  22339. ]);
  22340. this.latestLoadModulesPromise.catch(() => {
  22341. /* Avoid unhandled Promise rejections */
  22342. });
  22343. return loadNewModulesPromise;
  22344. }
  22345. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  22346. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  22347. if (resolvedId === null)
  22348. return null;
  22349. if (typeof resolvedId === 'string') {
  22350. dynamicImport.resolution = resolvedId;
  22351. return null;
  22352. }
  22353. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  22354. })));
  22355. for (const dependency of dependencies) {
  22356. if (dependency) {
  22357. module.dynamicDependencies.add(dependency);
  22358. dependency.dynamicImporters.push(module.id);
  22359. }
  22360. }
  22361. }
  22362. // If this is a preload, then this method always waits for the dependencies of
  22363. // the module to be resolved.
  22364. // Otherwise, if the module does not exist, it waits for the module and all
  22365. // its dependencies to be loaded.
  22366. // Otherwise, it returns immediately.
  22367. async fetchModule({ assertions, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  22368. const existingModule = this.modulesById.get(id);
  22369. if (existingModule instanceof Module) {
  22370. if (importer && doAssertionsDiffer(assertions, existingModule.info.assertions)) {
  22371. this.options.onwarn(errorInconsistentImportAssertions(existingModule.info.assertions, assertions, id, importer));
  22372. }
  22373. await this.handleExistingModule(existingModule, isEntry, isPreload);
  22374. return existingModule;
  22375. }
  22376. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, assertions);
  22377. this.modulesById.set(id, module);
  22378. this.graph.watchFiles[id] = true;
  22379. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  22380. this.getResolveStaticDependencyPromises(module),
  22381. this.getResolveDynamicImportPromises(module),
  22382. loadAndResolveDependenciesPromise
  22383. ]);
  22384. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  22385. loadAndResolveDependenciesPromise.catch(() => {
  22386. /* avoid unhandled promise rejections */
  22387. });
  22388. this.moduleLoadPromises.set(module, loadPromise);
  22389. const resolveDependencyPromises = await loadPromise;
  22390. if (!isPreload) {
  22391. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  22392. }
  22393. else if (isPreload === RESOLVE_DEPENDENCIES) {
  22394. await loadAndResolveDependenciesPromise;
  22395. }
  22396. return module;
  22397. }
  22398. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  22399. if (this.modulesWithLoadedDependencies.has(module)) {
  22400. return;
  22401. }
  22402. this.modulesWithLoadedDependencies.add(module);
  22403. await Promise.all([
  22404. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  22405. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  22406. ]);
  22407. module.linkImports();
  22408. // To handle errors when resolving dependencies or in moduleParsed
  22409. await loadAndResolveDependenciesPromise;
  22410. }
  22411. fetchResolvedDependency(source, importer, resolvedId) {
  22412. if (resolvedId.external) {
  22413. const { assertions, external, id, moduleSideEffects, meta } = resolvedId;
  22414. let externalModule = this.modulesById.get(id);
  22415. if (!externalModule) {
  22416. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id), assertions);
  22417. this.modulesById.set(id, externalModule);
  22418. }
  22419. else if (!(externalModule instanceof ExternalModule)) {
  22420. return error(errorInternalIdCannotBeExternal(source, importer));
  22421. }
  22422. else if (doAssertionsDiffer(externalModule.info.assertions, assertions)) {
  22423. this.options.onwarn(errorInconsistentImportAssertions(externalModule.info.assertions, assertions, source, importer));
  22424. }
  22425. return Promise.resolve(externalModule);
  22426. }
  22427. return this.fetchModule(resolvedId, importer, false, false);
  22428. }
  22429. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  22430. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  22431. module.dependencies.add(dependency);
  22432. dependency.importers.push(module.id);
  22433. }
  22434. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  22435. for (const dependency of module.dependencies) {
  22436. if (dependency instanceof Module) {
  22437. dependency.importedFromNotTreeshaken = true;
  22438. }
  22439. }
  22440. }
  22441. }
  22442. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  22443. const { makeAbsoluteExternalsRelative } = this.options;
  22444. if (resolveIdResult) {
  22445. if (typeof resolveIdResult === 'object') {
  22446. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  22447. return {
  22448. ...resolveIdResult,
  22449. external: external &&
  22450. (external === 'relative' ||
  22451. !isAbsolute(resolveIdResult.id) ||
  22452. (external === true &&
  22453. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  22454. 'absolute')
  22455. };
  22456. }
  22457. const external = this.options.external(resolveIdResult, importer, true);
  22458. return {
  22459. external: external &&
  22460. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  22461. 'absolute'),
  22462. id: external && makeAbsoluteExternalsRelative
  22463. ? normalizeRelativeExternalId(resolveIdResult, importer)
  22464. : resolveIdResult
  22465. };
  22466. }
  22467. const id = makeAbsoluteExternalsRelative
  22468. ? normalizeRelativeExternalId(source, importer)
  22469. : source;
  22470. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  22471. return null;
  22472. }
  22473. return {
  22474. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  22475. id
  22476. };
  22477. }
  22478. getResolveDynamicImportPromises(module) {
  22479. return module.dynamicImports.map(async (dynamicImport) => {
  22480. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  22481. ? dynamicImport.argument
  22482. : dynamicImport.argument.esTreeNode, module.id, getAssertionsFromImportExpression(dynamicImport.node));
  22483. if (resolvedId && typeof resolvedId === 'object') {
  22484. dynamicImport.id = resolvedId.id;
  22485. }
  22486. return [dynamicImport, resolvedId];
  22487. });
  22488. }
  22489. getResolveStaticDependencyPromises(module) {
  22490. // eslint-disable-next-line unicorn/prefer-spread
  22491. return Array.from(module.sourcesWithAssertions, async ([source, assertions]) => [
  22492. source,
  22493. (module.resolvedIds[source] =
  22494. module.resolvedIds[source] ||
  22495. this.handleInvalidResolvedId(await this.resolveId(source, module.id, EMPTY_OBJECT, false, assertions), source, module.id, assertions))
  22496. ]);
  22497. }
  22498. getResolvedIdWithDefaults(resolvedId, assertions) {
  22499. if (!resolvedId) {
  22500. return null;
  22501. }
  22502. const external = resolvedId.external || false;
  22503. return {
  22504. assertions: resolvedId.assertions || assertions,
  22505. external,
  22506. id: resolvedId.id,
  22507. meta: resolvedId.meta || {},
  22508. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  22509. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  22510. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  22511. };
  22512. }
  22513. async handleExistingModule(module, isEntry, isPreload) {
  22514. const loadPromise = this.moduleLoadPromises.get(module);
  22515. if (isPreload) {
  22516. return isPreload === RESOLVE_DEPENDENCIES
  22517. ? waitForDependencyResolution(loadPromise)
  22518. : loadPromise;
  22519. }
  22520. if (isEntry) {
  22521. module.info.isEntry = true;
  22522. this.implicitEntryModules.delete(module);
  22523. for (const dependant of module.implicitlyLoadedAfter) {
  22524. dependant.implicitlyLoadedBefore.delete(module);
  22525. }
  22526. module.implicitlyLoadedAfter.clear();
  22527. }
  22528. return this.fetchModuleDependencies(module, ...(await loadPromise));
  22529. }
  22530. handleInvalidResolvedId(resolvedId, source, importer, assertions) {
  22531. if (resolvedId === null) {
  22532. if (isRelative(source)) {
  22533. return error(errorUnresolvedImport(source, importer));
  22534. }
  22535. this.options.onwarn(errorUnresolvedImportTreatedAsExternal(source, importer));
  22536. return {
  22537. assertions,
  22538. external: true,
  22539. id: source,
  22540. meta: {},
  22541. moduleSideEffects: this.hasModuleSideEffects(source, true),
  22542. resolvedBy: 'rollup',
  22543. syntheticNamedExports: false
  22544. };
  22545. }
  22546. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  22547. this.options.onwarn(errorExternalSyntheticExports(source, importer));
  22548. }
  22549. return resolvedId;
  22550. }
  22551. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  22552. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT);
  22553. if (resolveIdResult == null) {
  22554. return error(implicitlyLoadedBefore === null
  22555. ? errorUnresolvedEntry(unresolvedId)
  22556. : errorUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  22557. }
  22558. if (resolveIdResult === false ||
  22559. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  22560. return error(implicitlyLoadedBefore === null
  22561. ? errorEntryCannotBeExternal(unresolvedId)
  22562. : errorImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  22563. }
  22564. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  22565. ? resolveIdResult
  22566. : { id: resolveIdResult }, EMPTY_OBJECT), undefined, isEntry, false);
  22567. }
  22568. async resolveDynamicImport(module, specifier, importer, assertions) {
  22569. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  22570. specifier,
  22571. importer,
  22572. { assertions }
  22573. ]);
  22574. if (typeof specifier !== 'string') {
  22575. if (typeof resolution === 'string') {
  22576. return resolution;
  22577. }
  22578. if (!resolution) {
  22579. return null;
  22580. }
  22581. return this.getResolvedIdWithDefaults(resolution, assertions);
  22582. }
  22583. if (resolution == null) {
  22584. const existingResolution = module.resolvedIds[specifier];
  22585. if (existingResolution) {
  22586. if (doAssertionsDiffer(existingResolution.assertions, assertions)) {
  22587. this.options.onwarn(errorInconsistentImportAssertions(existingResolution.assertions, assertions, specifier, importer));
  22588. }
  22589. return existingResolution;
  22590. }
  22591. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false, assertions), specifier, module.id, assertions));
  22592. }
  22593. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), assertions), specifier, importer, assertions);
  22594. }
  22595. }
  22596. function normalizeRelativeExternalId(source, importer) {
  22597. return isRelative(source)
  22598. ? importer
  22599. ? node_path.resolve(importer, '..', source)
  22600. : node_path.resolve(source)
  22601. : source;
  22602. }
  22603. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  22604. if (fileName !== null) {
  22605. module.chunkFileNames.add(fileName);
  22606. }
  22607. else if (name !== null) {
  22608. // Always keep chunkNames sorted by priority
  22609. let namePosition = 0;
  22610. while (module.chunkNames[namePosition]?.priority < priority)
  22611. namePosition++;
  22612. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  22613. }
  22614. }
  22615. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  22616. return (makeAbsoluteExternalsRelative === true ||
  22617. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  22618. !isAbsolute(id));
  22619. }
  22620. async function waitForDependencyResolution(loadPromise) {
  22621. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  22622. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  22623. }
  22624. class GlobalScope extends Scope$1 {
  22625. constructor() {
  22626. super();
  22627. this.parent = null;
  22628. this.variables.set('undefined', new UndefinedVariable());
  22629. }
  22630. findVariable(name) {
  22631. let variable = this.variables.get(name);
  22632. if (!variable) {
  22633. variable = new GlobalVariable(name);
  22634. this.variables.set(name, variable);
  22635. }
  22636. return variable;
  22637. }
  22638. }
  22639. function getSourceHash(source) {
  22640. return createHash().update(source).digest('hex');
  22641. }
  22642. function generateAssetFileName(name, source, sourceHash, outputOptions, bundle) {
  22643. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  22644. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  22645. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  22646. : outputOptions.assetFileNames, 'output.assetFileNames', {
  22647. ext: () => node_path.extname(emittedName).slice(1),
  22648. extname: () => node_path.extname(emittedName),
  22649. hash: size => sourceHash.slice(0, Math.max(0, size || defaultHashSize)),
  22650. name: () => emittedName.slice(0, Math.max(0, emittedName.length - node_path.extname(emittedName).length))
  22651. }), bundle);
  22652. }
  22653. function reserveFileNameInBundle(fileName, { bundle }, warn) {
  22654. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  22655. warn(errorFileNameConflict(fileName));
  22656. }
  22657. else {
  22658. bundle[fileName] = FILE_PLACEHOLDER;
  22659. }
  22660. }
  22661. function hasValidType(emittedFile) {
  22662. return Boolean(emittedFile &&
  22663. (emittedFile.type === 'asset' ||
  22664. emittedFile.type === 'chunk'));
  22665. }
  22666. function hasValidName(emittedFile) {
  22667. const validatedName = emittedFile.fileName || emittedFile.name;
  22668. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  22669. }
  22670. function getValidSource(source, emittedFile, fileReferenceId) {
  22671. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  22672. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  22673. return error(errorFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
  22674. }
  22675. return source;
  22676. }
  22677. function getAssetFileName(file, referenceId) {
  22678. if (typeof file.fileName !== 'string') {
  22679. return error(errorAssetNotFinalisedForFileName(file.name || referenceId));
  22680. }
  22681. return file.fileName;
  22682. }
  22683. function getChunkFileName(file, facadeChunkByModule) {
  22684. if (file.fileName) {
  22685. return file.fileName;
  22686. }
  22687. if (facadeChunkByModule) {
  22688. return facadeChunkByModule.get(file.module).getFileName();
  22689. }
  22690. return error(errorChunkNotGeneratedForFileName(file.fileName || file.name));
  22691. }
  22692. class FileEmitter {
  22693. constructor(graph, options, baseFileEmitter) {
  22694. this.graph = graph;
  22695. this.options = options;
  22696. this.facadeChunkByModule = null;
  22697. this.nextIdBase = 1;
  22698. this.output = null;
  22699. this.outputFileEmitters = [];
  22700. this.emitFile = (emittedFile) => {
  22701. if (!hasValidType(emittedFile)) {
  22702. return error(errorFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
  22703. }
  22704. if (!hasValidName(emittedFile)) {
  22705. return error(errorFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
  22706. }
  22707. if (emittedFile.type === 'chunk') {
  22708. return this.emitChunk(emittedFile);
  22709. }
  22710. return this.emitAsset(emittedFile);
  22711. };
  22712. this.finaliseAssets = () => {
  22713. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  22714. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  22715. return error(errorNoAssetSourceSet(emittedFile.name || referenceId));
  22716. }
  22717. };
  22718. this.getFileName = (fileReferenceId) => {
  22719. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  22720. if (!emittedFile)
  22721. return error(errorFileReferenceIdNotFoundForFilename(fileReferenceId));
  22722. if (emittedFile.type === 'chunk') {
  22723. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  22724. }
  22725. return getAssetFileName(emittedFile, fileReferenceId);
  22726. };
  22727. this.setAssetSource = (referenceId, requestedSource) => {
  22728. const consumedFile = this.filesByReferenceId.get(referenceId);
  22729. if (!consumedFile)
  22730. return error(errorAssetReferenceIdNotFoundForSetSource(referenceId));
  22731. if (consumedFile.type !== 'asset') {
  22732. return error(errorFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  22733. }
  22734. if (consumedFile.source !== undefined) {
  22735. return error(errorAssetSourceAlreadySet(consumedFile.name || referenceId));
  22736. }
  22737. const source = getValidSource(requestedSource, consumedFile, referenceId);
  22738. if (this.output) {
  22739. this.finalizeAsset(consumedFile, source, referenceId, this.output);
  22740. }
  22741. else {
  22742. consumedFile.source = source;
  22743. for (const emitter of this.outputFileEmitters) {
  22744. emitter.finalizeAsset(consumedFile, source, referenceId, emitter.output);
  22745. }
  22746. }
  22747. };
  22748. this.setChunkInformation = (facadeChunkByModule) => {
  22749. this.facadeChunkByModule = facadeChunkByModule;
  22750. };
  22751. this.setOutputBundle = (bundle, outputOptions) => {
  22752. const output = (this.output = {
  22753. bundle,
  22754. fileNamesBySource: new Map(),
  22755. outputOptions
  22756. });
  22757. for (const emittedFile of this.filesByReferenceId.values()) {
  22758. if (emittedFile.fileName) {
  22759. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onwarn);
  22760. }
  22761. }
  22762. for (const [referenceId, consumedFile] of this.filesByReferenceId) {
  22763. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  22764. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, output);
  22765. }
  22766. }
  22767. };
  22768. this.filesByReferenceId = baseFileEmitter
  22769. ? new Map(baseFileEmitter.filesByReferenceId)
  22770. : new Map();
  22771. baseFileEmitter?.addOutputFileEmitter(this);
  22772. }
  22773. addOutputFileEmitter(outputFileEmitter) {
  22774. this.outputFileEmitters.push(outputFileEmitter);
  22775. }
  22776. assignReferenceId(file, idBase) {
  22777. let referenceId = idBase;
  22778. do {
  22779. referenceId = createHash().update(referenceId).digest('hex').slice(0, 8);
  22780. } while (this.filesByReferenceId.has(referenceId) ||
  22781. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  22782. this.filesByReferenceId.set(referenceId, file);
  22783. for (const { filesByReferenceId } of this.outputFileEmitters) {
  22784. filesByReferenceId.set(referenceId, file);
  22785. }
  22786. return referenceId;
  22787. }
  22788. emitAsset(emittedAsset) {
  22789. const source = emittedAsset.source === undefined
  22790. ? undefined
  22791. : getValidSource(emittedAsset.source, emittedAsset, null);
  22792. const consumedAsset = {
  22793. fileName: emittedAsset.fileName,
  22794. name: emittedAsset.name,
  22795. needsCodeReference: !!emittedAsset.needsCodeReference,
  22796. source,
  22797. type: 'asset'
  22798. };
  22799. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  22800. if (this.output) {
  22801. this.emitAssetWithReferenceId(consumedAsset, referenceId, this.output);
  22802. }
  22803. else {
  22804. for (const fileEmitter of this.outputFileEmitters) {
  22805. fileEmitter.emitAssetWithReferenceId(consumedAsset, referenceId, fileEmitter.output);
  22806. }
  22807. }
  22808. return referenceId;
  22809. }
  22810. emitAssetWithReferenceId(consumedAsset, referenceId, output) {
  22811. const { fileName, source } = consumedAsset;
  22812. if (fileName) {
  22813. reserveFileNameInBundle(fileName, output, this.options.onwarn);
  22814. }
  22815. if (source !== undefined) {
  22816. this.finalizeAsset(consumedAsset, source, referenceId, output);
  22817. }
  22818. }
  22819. emitChunk(emittedChunk) {
  22820. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  22821. return error(errorInvalidRollupPhaseForChunkEmission());
  22822. }
  22823. if (typeof emittedChunk.id !== 'string') {
  22824. return error(errorFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  22825. }
  22826. const consumedChunk = {
  22827. fileName: emittedChunk.fileName,
  22828. module: null,
  22829. name: emittedChunk.name || emittedChunk.id,
  22830. type: 'chunk'
  22831. };
  22832. this.graph.moduleLoader
  22833. .emitChunk(emittedChunk)
  22834. .then(module => (consumedChunk.module = module))
  22835. .catch(() => {
  22836. // Avoid unhandled Promise rejection as the error will be thrown later
  22837. // once module loading has finished
  22838. });
  22839. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  22840. }
  22841. finalizeAsset(consumedFile, source, referenceId, { bundle, fileNamesBySource, outputOptions }) {
  22842. let fileName = consumedFile.fileName;
  22843. // Deduplicate assets if an explicit fileName is not provided
  22844. if (!fileName) {
  22845. const sourceHash = getSourceHash(source);
  22846. fileName = fileNamesBySource.get(sourceHash);
  22847. if (!fileName) {
  22848. fileName = generateAssetFileName(consumedFile.name, source, sourceHash, outputOptions, bundle);
  22849. fileNamesBySource.set(sourceHash, fileName);
  22850. }
  22851. }
  22852. // We must not modify the original assets to avoid interaction between outputs
  22853. const assetWithFileName = { ...consumedFile, fileName, source };
  22854. this.filesByReferenceId.set(referenceId, assetWithFileName);
  22855. bundle[fileName] = {
  22856. fileName,
  22857. name: consumedFile.name,
  22858. needsCodeReference: consumedFile.needsCodeReference,
  22859. source,
  22860. type: 'asset'
  22861. };
  22862. }
  22863. }
  22864. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  22865. let cacheable = true;
  22866. if (typeof plugin.cacheKey !== 'string') {
  22867. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  22868. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  22869. existingPluginNames.has(plugin.name)) {
  22870. cacheable = false;
  22871. }
  22872. else {
  22873. existingPluginNames.add(plugin.name);
  22874. }
  22875. }
  22876. let cacheInstance;
  22877. if (!pluginCache) {
  22878. cacheInstance = NO_CACHE;
  22879. }
  22880. else if (cacheable) {
  22881. const cacheKey = plugin.cacheKey || plugin.name;
  22882. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  22883. }
  22884. else {
  22885. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  22886. }
  22887. return {
  22888. addWatchFile(id) {
  22889. if (graph.phase >= BuildPhase.GENERATE) {
  22890. return this.error(errorInvalidRollupPhaseForAddWatchFile());
  22891. }
  22892. graph.watchFiles[id] = true;
  22893. },
  22894. cache: cacheInstance,
  22895. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  22896. error(error_) {
  22897. return error(errorPluginError(error_, plugin.name));
  22898. },
  22899. getFileName: fileEmitter.getFileName,
  22900. getModuleIds: () => graph.modulesById.keys(),
  22901. getModuleInfo: graph.getModuleInfo,
  22902. getWatchFiles: () => Object.keys(graph.watchFiles),
  22903. load(resolvedId) {
  22904. return graph.moduleLoader.preloadModule(resolvedId);
  22905. },
  22906. meta: {
  22907. rollupVersion: version$1,
  22908. watchMode: graph.watchMode
  22909. },
  22910. get moduleIds() {
  22911. function* wrappedModuleIds() {
  22912. // We are wrapping this in a generator to only show the message once we are actually iterating
  22913. warnDeprecation(`Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`, URL_THIS_GETMODULEIDS, true, options, plugin.name);
  22914. yield* moduleIds;
  22915. }
  22916. const moduleIds = graph.modulesById.keys();
  22917. return wrappedModuleIds();
  22918. },
  22919. parse: graph.contextParse.bind(graph),
  22920. resolve(source, importer, { assertions, custom, isEntry, skipSelf } = BLANK) {
  22921. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, assertions || EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  22922. },
  22923. setAssetSource: fileEmitter.setAssetSource,
  22924. warn(warning) {
  22925. if (typeof warning === 'string')
  22926. warning = { message: warning };
  22927. if (warning.code)
  22928. warning.pluginCode = warning.code;
  22929. warning.code = 'PLUGIN_WARNING';
  22930. warning.plugin = plugin.name;
  22931. options.onwarn(warning);
  22932. }
  22933. };
  22934. }
  22935. // This will make sure no input hook is omitted
  22936. const inputHookNames = {
  22937. buildEnd: 1,
  22938. buildStart: 1,
  22939. closeBundle: 1,
  22940. closeWatcher: 1,
  22941. load: 1,
  22942. moduleParsed: 1,
  22943. options: 1,
  22944. resolveDynamicImport: 1,
  22945. resolveId: 1,
  22946. shouldTransformCachedModule: 1,
  22947. transform: 1,
  22948. watchChange: 1
  22949. };
  22950. const inputHooks = Object.keys(inputHookNames);
  22951. class PluginDriver {
  22952. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  22953. this.graph = graph;
  22954. this.options = options;
  22955. this.pluginCache = pluginCache;
  22956. this.sortedPlugins = new Map();
  22957. this.unfulfilledActions = new Set();
  22958. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  22959. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  22960. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  22961. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  22962. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  22963. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  22964. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  22965. const existingPluginNames = new Set();
  22966. this.pluginContexts = new Map(this.plugins.map(plugin => [
  22967. plugin,
  22968. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  22969. ]));
  22970. if (basePluginDriver) {
  22971. for (const plugin of userPlugins) {
  22972. for (const hook of inputHooks) {
  22973. if (hook in plugin) {
  22974. options.onwarn(errorInputHookInOutputPlugin(plugin.name, hook));
  22975. }
  22976. }
  22977. }
  22978. }
  22979. }
  22980. createOutputPluginDriver(plugins) {
  22981. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  22982. }
  22983. getUnfulfilledHookActions() {
  22984. return this.unfulfilledActions;
  22985. }
  22986. // chains, first non-null result stops and returns
  22987. hookFirst(hookName, parameters, replaceContext, skipped) {
  22988. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  22989. }
  22990. // chains, first non-null result stops and returns result and last plugin
  22991. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  22992. for (const plugin of this.getSortedPlugins(hookName)) {
  22993. if (skipped?.has(plugin))
  22994. continue;
  22995. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  22996. if (result != null)
  22997. return [result, plugin];
  22998. }
  22999. return null;
  23000. }
  23001. // chains synchronously, first non-null result stops and returns
  23002. hookFirstSync(hookName, parameters, replaceContext) {
  23003. for (const plugin of this.getSortedPlugins(hookName)) {
  23004. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  23005. if (result != null)
  23006. return result;
  23007. }
  23008. return null;
  23009. }
  23010. // parallel, ignores returns
  23011. async hookParallel(hookName, parameters, replaceContext) {
  23012. const parallelPromises = [];
  23013. for (const plugin of this.getSortedPlugins(hookName)) {
  23014. if (plugin[hookName].sequential) {
  23015. await Promise.all(parallelPromises);
  23016. parallelPromises.length = 0;
  23017. await this.runHook(hookName, parameters, plugin, replaceContext);
  23018. }
  23019. else {
  23020. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  23021. }
  23022. }
  23023. await Promise.all(parallelPromises);
  23024. }
  23025. // chains, reduces returned value, handling the reduced value as the first hook argument
  23026. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  23027. let promise = Promise.resolve(argument0);
  23028. for (const plugin of this.getSortedPlugins(hookName)) {
  23029. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  23030. }
  23031. return promise;
  23032. }
  23033. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  23034. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  23035. for (const plugin of this.getSortedPlugins(hookName)) {
  23036. const parameters = [argument0, ...rest];
  23037. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  23038. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  23039. }
  23040. return argument0;
  23041. }
  23042. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  23043. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  23044. const results = [];
  23045. const parallelResults = [];
  23046. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  23047. if (plugin[hookName].sequential) {
  23048. results.push(...(await Promise.all(parallelResults)));
  23049. parallelResults.length = 0;
  23050. results.push(await this.runHook(hookName, parameters, plugin));
  23051. }
  23052. else {
  23053. parallelResults.push(this.runHook(hookName, parameters, plugin));
  23054. }
  23055. }
  23056. results.push(...(await Promise.all(parallelResults)));
  23057. return results.reduce(reducer, await initialValue);
  23058. }
  23059. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  23060. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  23061. let accumulator = initialValue;
  23062. for (const plugin of this.getSortedPlugins(hookName)) {
  23063. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  23064. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  23065. }
  23066. return accumulator;
  23067. }
  23068. // chains, ignores returns
  23069. hookSeq(hookName, parameters, replaceContext) {
  23070. let promise = Promise.resolve();
  23071. for (const plugin of this.getSortedPlugins(hookName)) {
  23072. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  23073. }
  23074. return promise.then(noReturn);
  23075. }
  23076. getSortedPlugins(hookName, validateHandler) {
  23077. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  23078. }
  23079. // Implementation signature
  23080. runHook(hookName, parameters, plugin, replaceContext) {
  23081. // We always filter for plugins that support the hook before running it
  23082. const hook = plugin[hookName];
  23083. const handler = typeof hook === 'object' ? hook.handler : hook;
  23084. let context = this.pluginContexts.get(plugin);
  23085. if (replaceContext) {
  23086. context = replaceContext(context, plugin);
  23087. }
  23088. let action = null;
  23089. return Promise.resolve()
  23090. .then(() => {
  23091. if (typeof handler !== 'function') {
  23092. return handler;
  23093. }
  23094. // eslint-disable-next-line @typescript-eslint/ban-types
  23095. const hookResult = handler.apply(context, parameters);
  23096. if (!hookResult?.then) {
  23097. // short circuit for non-thenables and non-Promises
  23098. return hookResult;
  23099. }
  23100. // Track pending hook actions to properly error out when
  23101. // unfulfilled promises cause rollup to abruptly and confusingly
  23102. // exit with a successful 0 return code but without producing any
  23103. // output, errors or warnings.
  23104. action = [plugin.name, hookName, parameters];
  23105. this.unfulfilledActions.add(action);
  23106. // Although it would be more elegant to just return hookResult here
  23107. // and put the .then() handler just above the .catch() handler below,
  23108. // doing so would subtly change the defacto async event dispatch order
  23109. // which at least one test and some plugins in the wild may depend on.
  23110. return Promise.resolve(hookResult).then(result => {
  23111. // action was fulfilled
  23112. this.unfulfilledActions.delete(action);
  23113. return result;
  23114. });
  23115. })
  23116. .catch(error_ => {
  23117. if (action !== null) {
  23118. // action considered to be fulfilled since error being handled
  23119. this.unfulfilledActions.delete(action);
  23120. }
  23121. return error(errorPluginError(error_, plugin.name, { hook: hookName }));
  23122. });
  23123. }
  23124. /**
  23125. * Run a sync plugin hook and return the result.
  23126. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  23127. * @param args Arguments passed to the plugin hook.
  23128. * @param plugin The acutal plugin
  23129. * @param replaceContext When passed, the plugin context can be overridden.
  23130. */
  23131. runHookSync(hookName, parameters, plugin, replaceContext) {
  23132. const hook = plugin[hookName];
  23133. const handler = typeof hook === 'object' ? hook.handler : hook;
  23134. let context = this.pluginContexts.get(plugin);
  23135. if (replaceContext) {
  23136. context = replaceContext(context, plugin);
  23137. }
  23138. try {
  23139. // eslint-disable-next-line @typescript-eslint/ban-types
  23140. return handler.apply(context, parameters);
  23141. }
  23142. catch (error_) {
  23143. return error(errorPluginError(error_, plugin.name, { hook: hookName }));
  23144. }
  23145. }
  23146. }
  23147. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  23148. const pre = [];
  23149. const normal = [];
  23150. const post = [];
  23151. for (const plugin of plugins) {
  23152. const hook = plugin[hookName];
  23153. if (hook) {
  23154. if (typeof hook === 'object') {
  23155. validateHandler(hook.handler, hookName, plugin);
  23156. if (hook.order === 'pre') {
  23157. pre.push(plugin);
  23158. continue;
  23159. }
  23160. if (hook.order === 'post') {
  23161. post.push(plugin);
  23162. continue;
  23163. }
  23164. }
  23165. else {
  23166. validateHandler(hook, hookName, plugin);
  23167. }
  23168. normal.push(plugin);
  23169. }
  23170. }
  23171. return [...pre, ...normal, ...post];
  23172. }
  23173. function validateFunctionPluginHandler(handler, hookName, plugin) {
  23174. if (typeof handler !== 'function') {
  23175. error(errorInvalidFunctionPluginHook(hookName, plugin.name));
  23176. }
  23177. }
  23178. function validateAddonPluginHandler(handler, hookName, plugin) {
  23179. if (typeof handler !== 'string' && typeof handler !== 'function') {
  23180. return error(errorInvalidAddonPluginHook(hookName, plugin.name));
  23181. }
  23182. }
  23183. function noReturn() { }
  23184. class Queue {
  23185. constructor(maxParallel) {
  23186. this.maxParallel = maxParallel;
  23187. this.queue = [];
  23188. this.workerCount = 0;
  23189. }
  23190. run(task) {
  23191. return new Promise((resolve, reject) => {
  23192. this.queue.push({ reject, resolve, task });
  23193. this.work();
  23194. });
  23195. }
  23196. async work() {
  23197. if (this.workerCount >= this.maxParallel)
  23198. return;
  23199. this.workerCount++;
  23200. let entry;
  23201. while ((entry = this.queue.shift())) {
  23202. const { reject, resolve, task } = entry;
  23203. try {
  23204. const result = await task();
  23205. resolve(result);
  23206. }
  23207. catch (error) {
  23208. reject(error);
  23209. }
  23210. }
  23211. this.workerCount--;
  23212. }
  23213. }
  23214. function normalizeEntryModules(entryModules) {
  23215. if (Array.isArray(entryModules)) {
  23216. return entryModules.map(id => ({
  23217. fileName: null,
  23218. id,
  23219. implicitlyLoadedAfter: [],
  23220. importer: undefined,
  23221. name: null
  23222. }));
  23223. }
  23224. return Object.entries(entryModules).map(([name, id]) => ({
  23225. fileName: null,
  23226. id,
  23227. implicitlyLoadedAfter: [],
  23228. importer: undefined,
  23229. name
  23230. }));
  23231. }
  23232. class Graph {
  23233. constructor(options, watcher) {
  23234. this.options = options;
  23235. this.astLru = flru(5);
  23236. this.cachedModules = new Map();
  23237. this.deoptimizationTracker = new PathTracker();
  23238. this.entryModules = [];
  23239. this.modulesById = new Map();
  23240. this.needsTreeshakingPass = false;
  23241. this.phase = BuildPhase.LOAD_AND_PARSE;
  23242. this.scope = new GlobalScope();
  23243. this.watchFiles = Object.create(null);
  23244. this.watchMode = false;
  23245. this.externalModules = [];
  23246. this.implicitEntryModules = [];
  23247. this.modules = [];
  23248. this.getModuleInfo = (moduleId) => {
  23249. const foundModule = this.modulesById.get(moduleId);
  23250. if (!foundModule)
  23251. return null;
  23252. return foundModule.info;
  23253. };
  23254. if (options.cache !== false) {
  23255. if (options.cache?.modules) {
  23256. for (const module of options.cache.modules)
  23257. this.cachedModules.set(module.id, module);
  23258. }
  23259. this.pluginCache = options.cache?.plugins || Object.create(null);
  23260. // increment access counter
  23261. for (const name in this.pluginCache) {
  23262. const cache = this.pluginCache[name];
  23263. for (const value of Object.values(cache))
  23264. value[0]++;
  23265. }
  23266. }
  23267. if (watcher) {
  23268. this.watchMode = true;
  23269. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  23270. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  23271. watcher.onCurrentRun('change', handleChange);
  23272. watcher.onCurrentRun('close', handleClose);
  23273. }
  23274. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  23275. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  23276. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  23277. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  23278. this.pureFunctions = getPureFunctions(options);
  23279. }
  23280. async build() {
  23281. timeStart('generate module graph', 2);
  23282. await this.generateModuleGraph();
  23283. timeEnd('generate module graph', 2);
  23284. timeStart('sort and bind modules', 2);
  23285. this.phase = BuildPhase.ANALYSE;
  23286. this.sortModules();
  23287. timeEnd('sort and bind modules', 2);
  23288. timeStart('mark included statements', 2);
  23289. this.includeStatements();
  23290. timeEnd('mark included statements', 2);
  23291. this.phase = BuildPhase.GENERATE;
  23292. }
  23293. contextParse(code, options = {}) {
  23294. const onCommentOrig = options.onComment;
  23295. const comments = [];
  23296. options.onComment =
  23297. onCommentOrig && typeof onCommentOrig == 'function'
  23298. ? (block, text, start, end, ...parameters) => {
  23299. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  23300. return onCommentOrig.call(options, block, text, start, end, ...parameters);
  23301. }
  23302. : comments;
  23303. const ast = this.acornParser.parse(code, {
  23304. ...this.options.acorn,
  23305. ...options
  23306. });
  23307. if (typeof onCommentOrig == 'object') {
  23308. onCommentOrig.push(...comments);
  23309. }
  23310. options.onComment = onCommentOrig;
  23311. addAnnotations(comments, ast, code);
  23312. return ast;
  23313. }
  23314. getCache() {
  23315. // handle plugin cache eviction
  23316. for (const name in this.pluginCache) {
  23317. const cache = this.pluginCache[name];
  23318. let allDeleted = true;
  23319. for (const [key, value] of Object.entries(cache)) {
  23320. if (value[0] >= this.options.experimentalCacheExpiry)
  23321. delete cache[key];
  23322. else
  23323. allDeleted = false;
  23324. }
  23325. if (allDeleted)
  23326. delete this.pluginCache[name];
  23327. }
  23328. return {
  23329. modules: this.modules.map(module => module.toJSON()),
  23330. plugins: this.pluginCache
  23331. };
  23332. }
  23333. async generateModuleGraph() {
  23334. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  23335. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  23336. if (this.entryModules.length === 0) {
  23337. throw new Error('You must supply options.input to rollup');
  23338. }
  23339. for (const module of this.modulesById.values()) {
  23340. if (module instanceof Module) {
  23341. this.modules.push(module);
  23342. }
  23343. else {
  23344. this.externalModules.push(module);
  23345. }
  23346. }
  23347. }
  23348. includeStatements() {
  23349. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  23350. for (const module of entryModules) {
  23351. markModuleAndImpureDependenciesAsExecuted(module);
  23352. }
  23353. if (this.options.treeshake) {
  23354. let treeshakingPass = 1;
  23355. do {
  23356. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  23357. this.needsTreeshakingPass = false;
  23358. for (const module of this.modules) {
  23359. if (module.isExecuted) {
  23360. if (module.info.moduleSideEffects === 'no-treeshake') {
  23361. module.includeAllInBundle();
  23362. }
  23363. else {
  23364. module.include();
  23365. }
  23366. }
  23367. }
  23368. if (treeshakingPass === 1) {
  23369. // We only include exports after the first pass to avoid issues with
  23370. // the TDZ detection logic
  23371. for (const module of entryModules) {
  23372. if (module.preserveSignature !== false) {
  23373. module.includeAllExports(false);
  23374. this.needsTreeshakingPass = true;
  23375. }
  23376. }
  23377. }
  23378. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  23379. } while (this.needsTreeshakingPass);
  23380. }
  23381. else {
  23382. for (const module of this.modules)
  23383. module.includeAllInBundle();
  23384. }
  23385. for (const externalModule of this.externalModules)
  23386. externalModule.warnUnusedImports();
  23387. for (const module of this.implicitEntryModules) {
  23388. for (const dependant of module.implicitlyLoadedAfter) {
  23389. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  23390. error(errorImplicitDependantIsNotIncluded(dependant));
  23391. }
  23392. }
  23393. }
  23394. }
  23395. sortModules() {
  23396. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  23397. for (const cyclePath of cyclePaths) {
  23398. this.options.onwarn(errorCircularDependency(cyclePath));
  23399. }
  23400. this.modules = orderedModules;
  23401. for (const module of this.modules) {
  23402. module.bindReferences();
  23403. }
  23404. this.warnForMissingExports();
  23405. }
  23406. warnForMissingExports() {
  23407. for (const module of this.modules) {
  23408. for (const importDescription of module.importDescriptions.values()) {
  23409. if (importDescription.name !== '*' &&
  23410. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  23411. module.warn(errorMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  23412. }
  23413. }
  23414. }
  23415. }
  23416. }
  23417. function formatAction([pluginName, hookName, parameters]) {
  23418. const action = `(${pluginName}) ${hookName}`;
  23419. const s = JSON.stringify;
  23420. switch (hookName) {
  23421. case 'resolveId': {
  23422. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  23423. }
  23424. case 'load': {
  23425. return `${action} ${s(parameters[0])}`;
  23426. }
  23427. case 'transform': {
  23428. return `${action} ${s(parameters[1])}`;
  23429. }
  23430. case 'shouldTransformCachedModule': {
  23431. return `${action} ${s(parameters[0].id)}`;
  23432. }
  23433. case 'moduleParsed': {
  23434. return `${action} ${s(parameters[0].id)}`;
  23435. }
  23436. }
  23437. return action;
  23438. }
  23439. // We do not directly listen on process to avoid max listeners warnings for
  23440. // complicated build processes
  23441. const beforeExitEvent = 'beforeExit';
  23442. const beforeExitEmitter = new node_events.EventEmitter();
  23443. beforeExitEmitter.setMaxListeners(0);
  23444. process$1.on(beforeExitEvent, () => beforeExitEmitter.emit(beforeExitEvent));
  23445. async function catchUnfinishedHookActions(pluginDriver, callback) {
  23446. let handleEmptyEventLoop;
  23447. const emptyEventLoopPromise = new Promise((_, reject) => {
  23448. handleEmptyEventLoop = () => {
  23449. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  23450. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  23451. [...unfulfilledActions].map(formatAction).join('\n')));
  23452. };
  23453. beforeExitEmitter.once(beforeExitEvent, handleEmptyEventLoop);
  23454. });
  23455. const result = await Promise.race([callback(), emptyEventLoopPromise]);
  23456. beforeExitEmitter.off(beforeExitEvent, handleEmptyEventLoop);
  23457. return result;
  23458. }
  23459. const leftCurlyBrace = "{".charCodeAt(0);
  23460. const space = " ".charCodeAt(0);
  23461. const keyword = "assert";
  23462. const FUNC_STATEMENT = 1, FUNC_NULLABLE_ID = 4;
  23463. function importAssertions(Parser) {
  23464. // Use supplied version acorn version if present, to avoid
  23465. // reference mismatches due to different acorn versions. This
  23466. // allows this plugin to be used with Rollup which supplies
  23467. // its own internal version of acorn and thereby sidesteps
  23468. // the package manager.
  23469. const acorn = Parser.acorn || _acorn;
  23470. const { tokTypes: tt, TokenType } = acorn;
  23471. return class extends Parser {
  23472. constructor(...args) {
  23473. super(...args);
  23474. this.assertToken = new TokenType(keyword);
  23475. }
  23476. _codeAt(i) {
  23477. return this.input.charCodeAt(i);
  23478. }
  23479. _eat(t) {
  23480. if (this.type !== t) {
  23481. this.unexpected();
  23482. }
  23483. this.next();
  23484. }
  23485. readToken(code) {
  23486. let i = 0;
  23487. for (; i < keyword.length; i++) {
  23488. if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) {
  23489. return super.readToken(code);
  23490. }
  23491. }
  23492. // ensure that the keyword is at the correct location
  23493. // ie `assert{...` or `assert {...`
  23494. for (;; i++) {
  23495. if (this._codeAt(this.pos + i) === leftCurlyBrace) {
  23496. // Found '{'
  23497. break;
  23498. } else if (this._codeAt(this.pos + i) === space) {
  23499. // white space is allowed between `assert` and `{`, so continue.
  23500. continue;
  23501. } else {
  23502. return super.readToken(code);
  23503. }
  23504. }
  23505. // If we're inside a dynamic import expression we'll parse
  23506. // the `assert` keyword as a standard object property name
  23507. // ie `import(""./foo.json", { assert: { type: "json" } })`
  23508. if (this.type.label === "{") {
  23509. return super.readToken(code);
  23510. }
  23511. this.pos += keyword.length;
  23512. return this.finishToken(this.assertToken);
  23513. }
  23514. parseDynamicImport(node) {
  23515. this.next(); // skip `(`
  23516. // Parse node.source.
  23517. node.source = this.parseMaybeAssign();
  23518. if (this.eat(tt.comma)) {
  23519. const obj = this.parseObj(false);
  23520. node.arguments = [obj];
  23521. }
  23522. this._eat(tt.parenR);
  23523. return this.finishNode(node, "ImportExpression");
  23524. }
  23525. // ported from acorn/src/statement.js pp.parseExport
  23526. parseExport(node, exports) {
  23527. this.next();
  23528. // export * from '...'
  23529. if (this.eat(tt.star)) {
  23530. if (this.options.ecmaVersion >= 11) {
  23531. if (this.eatContextual("as")) {
  23532. node.exported = this.parseIdent(true);
  23533. this.checkExport(exports, node.exported.name, this.lastTokStart);
  23534. } else {
  23535. node.exported = null;
  23536. }
  23537. }
  23538. this.expectContextual("from");
  23539. if (this.type !== tt.string) { this.unexpected(); }
  23540. node.source = this.parseExprAtom();
  23541. if (this.type === this.assertToken) {
  23542. this.next();
  23543. const assertions = this.parseImportAssertions();
  23544. if (assertions) {
  23545. node.assertions = assertions;
  23546. }
  23547. }
  23548. this.semicolon();
  23549. return this.finishNode(node, "ExportAllDeclaration")
  23550. }
  23551. if (this.eat(tt._default)) { // export default ...
  23552. this.checkExport(exports, "default", this.lastTokStart);
  23553. var isAsync;
  23554. if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
  23555. var fNode = this.startNode();
  23556. this.next();
  23557. if (isAsync) { this.next(); }
  23558. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  23559. } else if (this.type === tt._class) {
  23560. var cNode = this.startNode();
  23561. node.declaration = this.parseClass(cNode, "nullableID");
  23562. } else {
  23563. node.declaration = this.parseMaybeAssign();
  23564. this.semicolon();
  23565. }
  23566. return this.finishNode(node, "ExportDefaultDeclaration")
  23567. }
  23568. // export var|const|let|function|class ...
  23569. if (this.shouldParseExportStatement()) {
  23570. node.declaration = this.parseStatement(null);
  23571. if (node.declaration.type === "VariableDeclaration")
  23572. { this.checkVariableExport(exports, node.declaration.declarations); }
  23573. else
  23574. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  23575. node.specifiers = [];
  23576. node.source = null;
  23577. } else { // export { x, y as z } [from '...']
  23578. node.declaration = null;
  23579. node.specifiers = this.parseExportSpecifiers(exports);
  23580. if (this.eatContextual("from")) {
  23581. if (this.type !== tt.string) { this.unexpected(); }
  23582. node.source = this.parseExprAtom();
  23583. if (this.type === this.assertToken) {
  23584. this.next();
  23585. const assertions = this.parseImportAssertions();
  23586. if (assertions) {
  23587. node.assertions = assertions;
  23588. }
  23589. }
  23590. } else {
  23591. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  23592. // check for keywords used as local names
  23593. var spec = list[i];
  23594. this.checkUnreserved(spec.local);
  23595. // check if export is defined
  23596. this.checkLocalExport(spec.local);
  23597. }
  23598. node.source = null;
  23599. }
  23600. this.semicolon();
  23601. }
  23602. return this.finishNode(node, "ExportNamedDeclaration")
  23603. }
  23604. parseImport(node) {
  23605. this.next();
  23606. // import '...'
  23607. if (this.type === tt.string) {
  23608. node.specifiers = [];
  23609. node.source = this.parseExprAtom();
  23610. } else {
  23611. node.specifiers = this.parseImportSpecifiers();
  23612. this.expectContextual("from");
  23613. node.source =
  23614. this.type === tt.string ? this.parseExprAtom() : this.unexpected();
  23615. }
  23616. if (this.type === this.assertToken) {
  23617. this.next();
  23618. const assertions = this.parseImportAssertions();
  23619. if (assertions) {
  23620. node.assertions = assertions;
  23621. }
  23622. }
  23623. this.semicolon();
  23624. return this.finishNode(node, "ImportDeclaration");
  23625. }
  23626. parseImportAssertions() {
  23627. this._eat(tt.braceL);
  23628. const attrs = this.parseAssertEntries();
  23629. this._eat(tt.braceR);
  23630. return attrs;
  23631. }
  23632. parseAssertEntries() {
  23633. const attrs = [];
  23634. const attrNames = new Set();
  23635. do {
  23636. if (this.type === tt.braceR) {
  23637. break;
  23638. }
  23639. const node = this.startNode();
  23640. // parse AssertionKey : IdentifierName, StringLiteral
  23641. let assertionKeyNode;
  23642. if (this.type === tt.string) {
  23643. assertionKeyNode = this.parseLiteral(this.value);
  23644. } else {
  23645. assertionKeyNode = this.parseIdent(true);
  23646. }
  23647. this.next();
  23648. node.key = assertionKeyNode;
  23649. // check if we already have an entry for an attribute
  23650. // if a duplicate entry is found, throw an error
  23651. // for now this logic will come into play only when someone declares `type` twice
  23652. if (attrNames.has(node.key.name)) {
  23653. this.raise(this.pos, "Duplicated key in assertions");
  23654. }
  23655. attrNames.add(node.key.name);
  23656. if (this.type !== tt.string) {
  23657. this.raise(
  23658. this.pos,
  23659. "Only string is supported as an assertion value"
  23660. );
  23661. }
  23662. node.value = this.parseLiteral(this.value);
  23663. attrs.push(this.finishNode(node, "ImportAttribute"));
  23664. } while (this.eat(tt.comma));
  23665. return attrs;
  23666. }
  23667. };
  23668. }
  23669. async function normalizeInputOptions(config) {
  23670. // These are options that may trigger special warnings or behaviour later
  23671. // if the user did not select an explicit value
  23672. const unsetOptions = new Set();
  23673. const context = config.context ?? 'undefined';
  23674. const onwarn = getOnwarn(config);
  23675. const strictDeprecations = config.strictDeprecations || false;
  23676. const maxParallelFileOps = getmaxParallelFileOps(config, onwarn, strictDeprecations);
  23677. const options = {
  23678. acorn: getAcorn(config),
  23679. acornInjectPlugins: getAcornInjectPlugins(config),
  23680. cache: getCache(config),
  23681. context,
  23682. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  23683. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  23684. external: getIdMatcher(config.external),
  23685. inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
  23686. input: getInput(config),
  23687. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  23688. manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
  23689. maxParallelFileOps,
  23690. maxParallelFileReads: maxParallelFileOps,
  23691. moduleContext: getModuleContext(config, context),
  23692. onwarn,
  23693. perf: config.perf || false,
  23694. plugins: await normalizePluginOption(config.plugins),
  23695. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  23696. preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
  23697. preserveSymlinks: config.preserveSymlinks || false,
  23698. shimMissingExports: config.shimMissingExports || false,
  23699. strictDeprecations,
  23700. treeshake: getTreeshake(config)
  23701. };
  23702. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  23703. return { options, unsetOptions };
  23704. }
  23705. const getOnwarn = (config) => {
  23706. const { onwarn } = config;
  23707. return onwarn
  23708. ? warning => {
  23709. warning.toString = () => {
  23710. let warningString = '';
  23711. if (warning.plugin)
  23712. warningString += `(${warning.plugin} plugin) `;
  23713. if (warning.loc)
  23714. warningString += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  23715. warningString += warning.message;
  23716. return warningString;
  23717. };
  23718. onwarn(warning, defaultOnWarn);
  23719. }
  23720. : defaultOnWarn;
  23721. };
  23722. const getAcorn = (config) => ({
  23723. ecmaVersion: 'latest',
  23724. sourceType: 'module',
  23725. ...config.acorn
  23726. });
  23727. const getAcornInjectPlugins = (config) => [
  23728. importAssertions,
  23729. ...ensureArray$1(config.acornInjectPlugins)
  23730. ];
  23731. const getCache = (config) => config.cache === true // `true` is the default
  23732. ? undefined
  23733. : config.cache?.cache || config.cache;
  23734. const getIdMatcher = (option) => {
  23735. if (option === true) {
  23736. return () => true;
  23737. }
  23738. if (typeof option === 'function') {
  23739. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  23740. }
  23741. if (option) {
  23742. const ids = new Set();
  23743. const matchers = [];
  23744. for (const value of ensureArray$1(option)) {
  23745. if (value instanceof RegExp) {
  23746. matchers.push(value);
  23747. }
  23748. else {
  23749. ids.add(value);
  23750. }
  23751. }
  23752. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  23753. }
  23754. return () => false;
  23755. };
  23756. const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
  23757. const configInlineDynamicImports = config.inlineDynamicImports;
  23758. if (configInlineDynamicImports) {
  23759. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', URL_OUTPUT_INLINEDYNAMICIMPORTS, true, warn, strictDeprecations);
  23760. }
  23761. return configInlineDynamicImports;
  23762. };
  23763. const getInput = (config) => {
  23764. const configInput = config.input;
  23765. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  23766. };
  23767. const getManualChunks$1 = (config, warn, strictDeprecations) => {
  23768. const configManualChunks = config.manualChunks;
  23769. if (configManualChunks) {
  23770. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', URL_OUTPUT_MANUALCHUNKS, true, warn, strictDeprecations);
  23771. }
  23772. return configManualChunks;
  23773. };
  23774. const getmaxParallelFileOps = (config, warn, strictDeprecations) => {
  23775. const maxParallelFileReads = config.maxParallelFileReads;
  23776. if (typeof maxParallelFileReads === 'number') {
  23777. warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', URL_MAXPARALLELFILEOPS, true, warn, strictDeprecations);
  23778. }
  23779. const maxParallelFileOps = config.maxParallelFileOps ?? maxParallelFileReads;
  23780. if (typeof maxParallelFileOps === 'number') {
  23781. if (maxParallelFileOps <= 0)
  23782. return Infinity;
  23783. return maxParallelFileOps;
  23784. }
  23785. return 20;
  23786. };
  23787. const getModuleContext = (config, context) => {
  23788. const configModuleContext = config.moduleContext;
  23789. if (typeof configModuleContext === 'function') {
  23790. return id => configModuleContext(id) ?? context;
  23791. }
  23792. if (configModuleContext) {
  23793. const contextByModuleId = Object.create(null);
  23794. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  23795. contextByModuleId[node_path.resolve(key)] = moduleContext;
  23796. }
  23797. return id => contextByModuleId[id] ?? context;
  23798. }
  23799. return () => context;
  23800. };
  23801. const getPreserveModules$1 = (config, warn, strictDeprecations) => {
  23802. const configPreserveModules = config.preserveModules;
  23803. if (configPreserveModules) {
  23804. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', URL_OUTPUT_PRESERVEMODULES, true, warn, strictDeprecations);
  23805. }
  23806. return configPreserveModules;
  23807. };
  23808. const getTreeshake = (config) => {
  23809. const configTreeshake = config.treeshake;
  23810. if (configTreeshake === false) {
  23811. return false;
  23812. }
  23813. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ');
  23814. return {
  23815. annotations: configWithPreset.annotations !== false,
  23816. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  23817. manualPureFunctions: configWithPreset.manualPureFunctions ?? EMPTY_ARRAY,
  23818. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  23819. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  23820. ? 'always'
  23821. : configWithPreset.propertyReadSideEffects !== false,
  23822. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  23823. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  23824. };
  23825. };
  23826. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  23827. if (typeof moduleSideEffectsOption === 'boolean') {
  23828. return () => moduleSideEffectsOption;
  23829. }
  23830. if (moduleSideEffectsOption === 'no-external') {
  23831. return (_id, external) => !external;
  23832. }
  23833. if (typeof moduleSideEffectsOption === 'function') {
  23834. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  23835. }
  23836. if (Array.isArray(moduleSideEffectsOption)) {
  23837. const ids = new Set(moduleSideEffectsOption);
  23838. return id => ids.has(id);
  23839. }
  23840. if (moduleSideEffectsOption) {
  23841. error(errorInvalidOption('treeshake.moduleSideEffects', URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  23842. }
  23843. return () => true;
  23844. };
  23845. // https://datatracker.ietf.org/doc/html/rfc2396
  23846. // eslint-disable-next-line no-control-regex
  23847. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$&*+,:;<=>?[\]^`{|}\u007F]/g;
  23848. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  23849. function sanitizeFileName(name) {
  23850. const match = DRIVE_LETTER_REGEX.exec(name);
  23851. const driveLetter = match ? match[0] : '';
  23852. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  23853. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  23854. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  23855. }
  23856. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  23857. // These are options that may trigger special warnings or behaviour later
  23858. // if the user did not select an explicit value
  23859. const unsetOptions = new Set(unsetInputOptions);
  23860. const compact = config.compact || false;
  23861. const format = getFormat(config);
  23862. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  23863. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  23864. const file = getFile(config, preserveModules, inputOptions);
  23865. const preferConst = getPreferConst(config, inputOptions);
  23866. const generatedCode = getGeneratedCode(config, preferConst);
  23867. const outputOptions = {
  23868. amd: getAmd(config),
  23869. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  23870. banner: getAddon(config, 'banner'),
  23871. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  23872. compact,
  23873. dir: getDir(config, file),
  23874. dynamicImportFunction: getDynamicImportFunction(config, inputOptions, format),
  23875. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  23876. entryFileNames: getEntryFileNames(config, unsetOptions),
  23877. esModule: config.esModule ?? 'if-default-prop',
  23878. experimentalDeepDynamicChunkOptimization: getExperimentalDeepDynamicChunkOptimization(config, inputOptions),
  23879. experimentalMinChunkSize: config.experimentalMinChunkSize || 0,
  23880. exports: getExports(config, unsetOptions),
  23881. extend: config.extend || false,
  23882. externalImportAssertions: config.externalImportAssertions ?? true,
  23883. externalLiveBindings: config.externalLiveBindings ?? true,
  23884. file,
  23885. footer: getAddon(config, 'footer'),
  23886. format,
  23887. freeze: config.freeze ?? true,
  23888. generatedCode,
  23889. globals: config.globals || {},
  23890. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  23891. indent: getIndent(config, compact),
  23892. inlineDynamicImports,
  23893. interop: getInterop(config),
  23894. intro: getAddon(config, 'intro'),
  23895. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  23896. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  23897. name: config.name,
  23898. namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
  23899. noConflict: config.noConflict || false,
  23900. outro: getAddon(config, 'outro'),
  23901. paths: config.paths || {},
  23902. plugins: await normalizePluginOption(config.plugins),
  23903. preferConst,
  23904. preserveModules,
  23905. preserveModulesRoot: getPreserveModulesRoot(config),
  23906. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  23907. ? config.sanitizeFileName
  23908. : config.sanitizeFileName === false
  23909. ? id => id
  23910. : sanitizeFileName,
  23911. sourcemap: config.sourcemap || false,
  23912. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  23913. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  23914. sourcemapFile: config.sourcemapFile,
  23915. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  23916. ? config.sourcemapIgnoreList
  23917. : config.sourcemapIgnoreList === false
  23918. ? () => false
  23919. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  23920. sourcemapPathTransform: config.sourcemapPathTransform,
  23921. strict: config.strict ?? true,
  23922. systemNullSetters: config.systemNullSetters ?? true,
  23923. validate: config.validate || false
  23924. };
  23925. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  23926. return { options: outputOptions, unsetOptions };
  23927. }
  23928. const getFile = (config, preserveModules, inputOptions) => {
  23929. const { file } = config;
  23930. if (typeof file === 'string') {
  23931. if (preserveModules) {
  23932. return error(errorInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  23933. }
  23934. if (!Array.isArray(inputOptions.input))
  23935. return error(errorInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  23936. }
  23937. return file;
  23938. };
  23939. const getFormat = (config) => {
  23940. const configFormat = config.format;
  23941. switch (configFormat) {
  23942. case undefined:
  23943. case 'es':
  23944. case 'esm':
  23945. case 'module': {
  23946. return 'es';
  23947. }
  23948. case 'cjs':
  23949. case 'commonjs': {
  23950. return 'cjs';
  23951. }
  23952. case 'system':
  23953. case 'systemjs': {
  23954. return 'system';
  23955. }
  23956. case 'amd':
  23957. case 'iife':
  23958. case 'umd': {
  23959. return configFormat;
  23960. }
  23961. default: {
  23962. return error(errorInvalidOption('output.format', URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  23963. }
  23964. }
  23965. };
  23966. const getInlineDynamicImports = (config, inputOptions) => {
  23967. const inlineDynamicImports = (config.inlineDynamicImports ?? inputOptions.inlineDynamicImports) || false;
  23968. const { input } = inputOptions;
  23969. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  23970. return error(errorInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  23971. }
  23972. return inlineDynamicImports;
  23973. };
  23974. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  23975. const preserveModules = (config.preserveModules ?? inputOptions.preserveModules) || false;
  23976. if (preserveModules) {
  23977. if (inlineDynamicImports) {
  23978. return error(errorInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  23979. }
  23980. if (inputOptions.preserveEntrySignatures === false) {
  23981. return error(errorInvalidOption('preserveEntrySignatures', URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  23982. }
  23983. }
  23984. return preserveModules;
  23985. };
  23986. const getPreferConst = (config, inputOptions) => {
  23987. const configPreferConst = config.preferConst;
  23988. if (configPreferConst != null) {
  23989. warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, URL_OUTPUT_GENERATEDCODE_CONSTBINDINGS, true, inputOptions);
  23990. }
  23991. return !!configPreferConst;
  23992. };
  23993. const getPreserveModulesRoot = (config) => {
  23994. const { preserveModulesRoot } = config;
  23995. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  23996. return undefined;
  23997. }
  23998. return node_path.resolve(preserveModulesRoot);
  23999. };
  24000. const getAmd = (config) => {
  24001. const mergedOption = {
  24002. autoId: false,
  24003. basePath: '',
  24004. define: 'define',
  24005. forceJsExtensionForImports: false,
  24006. ...config.amd
  24007. };
  24008. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  24009. return error(errorInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  24010. }
  24011. if (mergedOption.basePath && !mergedOption.autoId) {
  24012. return error(errorInvalidOption('output.amd.basePath', URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  24013. }
  24014. return mergedOption.autoId
  24015. ? {
  24016. autoId: true,
  24017. basePath: mergedOption.basePath,
  24018. define: mergedOption.define,
  24019. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  24020. }
  24021. : {
  24022. autoId: false,
  24023. define: mergedOption.define,
  24024. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  24025. id: mergedOption.id
  24026. };
  24027. };
  24028. const getAddon = (config, name) => {
  24029. const configAddon = config[name];
  24030. if (typeof configAddon === 'function') {
  24031. return configAddon;
  24032. }
  24033. return () => configAddon || '';
  24034. };
  24035. // eslint-disable-next-line unicorn/prevent-abbreviations
  24036. const getDir = (config, file) => {
  24037. const { dir } = config;
  24038. if (typeof dir === 'string' && typeof file === 'string') {
  24039. return error(errorInvalidOption('output.dir', URL_OUTPUT_DIR, 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
  24040. }
  24041. return dir;
  24042. };
  24043. const getDynamicImportFunction = (config, inputOptions, format) => {
  24044. const configDynamicImportFunction = config.dynamicImportFunction;
  24045. if (configDynamicImportFunction) {
  24046. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, URL_RENDERDYNAMICIMPORT, true, inputOptions);
  24047. if (format !== 'es') {
  24048. inputOptions.onwarn(errorInvalidOption('output.dynamicImportFunction', URL_OUTPUT_DYNAMICIMPORTFUNCTION, 'this option is ignored for formats other than "es"'));
  24049. }
  24050. }
  24051. return configDynamicImportFunction;
  24052. };
  24053. const getEntryFileNames = (config, unsetOptions) => {
  24054. const configEntryFileNames = config.entryFileNames;
  24055. if (configEntryFileNames == null) {
  24056. unsetOptions.add('entryFileNames');
  24057. }
  24058. return configEntryFileNames ?? '[name].js';
  24059. };
  24060. function getExperimentalDeepDynamicChunkOptimization(config, inputOptions) {
  24061. const configExperimentalDeepDynamicChunkOptimization = config.experimentalDeepDynamicChunkOptimization;
  24062. if (configExperimentalDeepDynamicChunkOptimization != null) {
  24063. warnDeprecation(`The "output.experimentalDeepDynamicChunkOptimization" option is deprecated as Rollup always runs the full chunking algorithm now. The option should be removed.`, URL_OUTPUT_EXPERIMENTALDEEPCHUNKOPTIMIZATION, true, inputOptions);
  24064. }
  24065. return configExperimentalDeepDynamicChunkOptimization || false;
  24066. }
  24067. function getExports(config, unsetOptions) {
  24068. const configExports = config.exports;
  24069. if (configExports == null) {
  24070. unsetOptions.add('exports');
  24071. }
  24072. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  24073. return error(errorInvalidExportOptionValue(configExports));
  24074. }
  24075. return configExports || 'auto';
  24076. }
  24077. const getGeneratedCode = (config, preferConst) => {
  24078. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
  24079. return {
  24080. arrowFunctions: configWithPreset.arrowFunctions === true,
  24081. constBindings: configWithPreset.constBindings === true || preferConst,
  24082. objectShorthand: configWithPreset.objectShorthand === true,
  24083. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  24084. symbols: configWithPreset.symbols === true
  24085. };
  24086. };
  24087. const getIndent = (config, compact) => {
  24088. if (compact) {
  24089. return '';
  24090. }
  24091. const configIndent = config.indent;
  24092. return configIndent === false ? '' : configIndent ?? true;
  24093. };
  24094. const ALLOWED_INTEROP_TYPES = new Set([
  24095. 'compat',
  24096. 'auto',
  24097. 'esModule',
  24098. 'default',
  24099. 'defaultOnly'
  24100. ]);
  24101. const getInterop = (config) => {
  24102. const configInterop = config.interop;
  24103. if (typeof configInterop === 'function') {
  24104. const interopPerId = Object.create(null);
  24105. let defaultInterop = null;
  24106. return id => id === null
  24107. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  24108. : id in interopPerId
  24109. ? interopPerId[id]
  24110. : validateInterop((interopPerId[id] = configInterop(id)));
  24111. }
  24112. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  24113. };
  24114. const validateInterop = (interop) => {
  24115. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  24116. return error(errorInvalidOption('output.interop', URL_OUTPUT_INTEROP,
  24117. // eslint-disable-next-line unicorn/prefer-spread
  24118. `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  24119. }
  24120. return interop;
  24121. };
  24122. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  24123. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  24124. if (configManualChunks) {
  24125. if (inlineDynamicImports) {
  24126. return error(errorInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  24127. }
  24128. if (preserveModules) {
  24129. return error(errorInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  24130. }
  24131. }
  24132. return configManualChunks || {};
  24133. };
  24134. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  24135. const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
  24136. const configNamespaceToStringTag = config.namespaceToStringTag;
  24137. if (configNamespaceToStringTag != null) {
  24138. warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, URL_OUTPUT_GENERATEDCODE_SYMBOLS, true, inputOptions);
  24139. return configNamespaceToStringTag;
  24140. }
  24141. return generatedCode.symbols || false;
  24142. };
  24143. const getSourcemapBaseUrl = (config) => {
  24144. const { sourcemapBaseUrl } = config;
  24145. if (sourcemapBaseUrl) {
  24146. if (isValidUrl(sourcemapBaseUrl)) {
  24147. return sourcemapBaseUrl;
  24148. }
  24149. return error(errorInvalidOption('output.sourcemapBaseUrl', URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  24150. }
  24151. };
  24152. function rollup(rawInputOptions) {
  24153. return rollupInternal(rawInputOptions, null);
  24154. }
  24155. async function rollupInternal(rawInputOptions, watcher) {
  24156. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  24157. initialiseTimers(inputOptions);
  24158. const graph = new Graph(inputOptions, watcher);
  24159. // remove the cache object from the memory after graph creation (cache is not used anymore)
  24160. const useCache = rawInputOptions.cache !== false;
  24161. if (rawInputOptions.cache) {
  24162. inputOptions.cache = undefined;
  24163. rawInputOptions.cache = undefined;
  24164. }
  24165. timeStart('BUILD', 1);
  24166. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  24167. try {
  24168. timeStart('initialize', 2);
  24169. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  24170. timeEnd('initialize', 2);
  24171. await graph.build();
  24172. }
  24173. catch (error_) {
  24174. const watchFiles = Object.keys(graph.watchFiles);
  24175. if (watchFiles.length > 0) {
  24176. error_.watchFiles = watchFiles;
  24177. }
  24178. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  24179. await graph.pluginDriver.hookParallel('closeBundle', []);
  24180. throw error_;
  24181. }
  24182. await graph.pluginDriver.hookParallel('buildEnd', []);
  24183. });
  24184. timeEnd('BUILD', 1);
  24185. const result = {
  24186. cache: useCache ? graph.getCache() : undefined,
  24187. async close() {
  24188. if (result.closed)
  24189. return;
  24190. result.closed = true;
  24191. await graph.pluginDriver.hookParallel('closeBundle', []);
  24192. },
  24193. closed: false,
  24194. async generate(rawOutputOptions) {
  24195. if (result.closed)
  24196. return error(errorAlreadyClosed());
  24197. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  24198. },
  24199. watchFiles: Object.keys(graph.watchFiles),
  24200. async write(rawOutputOptions) {
  24201. if (result.closed)
  24202. return error(errorAlreadyClosed());
  24203. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  24204. }
  24205. };
  24206. if (inputOptions.perf)
  24207. result.getTimings = getTimings;
  24208. return result;
  24209. }
  24210. async function getInputOptions(rawInputOptions, watchMode) {
  24211. if (!rawInputOptions) {
  24212. throw new Error('You must supply an options object to rollup');
  24213. }
  24214. const rawPlugins = getSortedValidatedPlugins('options', await normalizePluginOption(rawInputOptions.plugins));
  24215. const { options, unsetOptions } = await normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  24216. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  24217. return { options, unsetOptions };
  24218. }
  24219. function applyOptionHook(watchMode) {
  24220. return async (inputOptions, plugin) => {
  24221. const handler = 'handler' in plugin.options ? plugin.options.handler : plugin.options;
  24222. return ((await handler.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) ||
  24223. inputOptions);
  24224. };
  24225. }
  24226. function normalizePlugins(plugins, anonymousPrefix) {
  24227. for (const [index, plugin] of plugins.entries()) {
  24228. if (!plugin.name) {
  24229. plugin.name = `${anonymousPrefix}${index + 1}`;
  24230. }
  24231. }
  24232. }
  24233. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  24234. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  24235. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  24236. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  24237. const generated = await bundle.generate(isWrite);
  24238. if (isWrite) {
  24239. timeStart('WRITE', 1);
  24240. if (!outputOptions.dir && !outputOptions.file) {
  24241. return error(errorMissingFileOrDirOption());
  24242. }
  24243. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  24244. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  24245. timeEnd('WRITE', 1);
  24246. }
  24247. return createOutput(generated);
  24248. });
  24249. }
  24250. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  24251. if (!rawOutputOptions) {
  24252. throw new Error('You must supply an options object');
  24253. }
  24254. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  24255. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  24256. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  24257. return {
  24258. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  24259. outputPluginDriver
  24260. };
  24261. }
  24262. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  24263. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  24264. const emitError = () => pluginContext.error(errorCannotEmitFromOptionsHook());
  24265. return {
  24266. ...pluginContext,
  24267. emitFile: emitError,
  24268. setAssetSource: emitError
  24269. };
  24270. }), inputOptions, unsetInputOptions);
  24271. }
  24272. function createOutput(outputBundle) {
  24273. return {
  24274. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  24275. };
  24276. }
  24277. var SortingFileType;
  24278. (function (SortingFileType) {
  24279. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  24280. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  24281. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  24282. })(SortingFileType || (SortingFileType = {}));
  24283. function getSortingFileType(file) {
  24284. if (file.type === 'asset') {
  24285. return SortingFileType.ASSET;
  24286. }
  24287. if (file.isEntry) {
  24288. return SortingFileType.ENTRY_CHUNK;
  24289. }
  24290. return SortingFileType.SECONDARY_CHUNK;
  24291. }
  24292. async function writeOutputFile(outputFile, outputOptions) {
  24293. const fileName = node_path.resolve(outputOptions.dir || node_path.dirname(outputOptions.file), outputFile.fileName);
  24294. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  24295. await promises.mkdir(node_path.dirname(fileName), { recursive: true });
  24296. return promises.writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  24297. }
  24298. /**
  24299. * Auxiliary function for defining rollup configuration
  24300. * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
  24301. * @param options
  24302. */
  24303. function defineConfig(options) {
  24304. return options;
  24305. }
  24306. exports.URL_AVOIDING_EVAL = URL_AVOIDING_EVAL;
  24307. exports.URL_NAME_IS_NOT_EXPORTED = URL_NAME_IS_NOT_EXPORTED;
  24308. exports.URL_OUTPUT_EXPORTS = URL_OUTPUT_EXPORTS;
  24309. exports.URL_OUTPUT_GLOBALS = URL_OUTPUT_GLOBALS;
  24310. exports.URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT = URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT;
  24311. exports.URL_THIS_IS_UNDEFINED = URL_THIS_IS_UNDEFINED;
  24312. exports.URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY = URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY;
  24313. exports.URL_WATCH = URL_WATCH;
  24314. exports.bold = bold;
  24315. exports.commandAliases = commandAliases;
  24316. exports.commonjsGlobal = commonjsGlobal;
  24317. exports.createFilter = createFilter;
  24318. exports.cyan = cyan;
  24319. exports.defineConfig = defineConfig;
  24320. exports.ensureArray = ensureArray$1;
  24321. exports.error = error;
  24322. exports.errorCannotBundleConfigAsEsm = errorCannotBundleConfigAsEsm;
  24323. exports.errorCannotLoadConfigAsCjs = errorCannotLoadConfigAsCjs;
  24324. exports.errorCannotLoadConfigAsEsm = errorCannotLoadConfigAsEsm;
  24325. exports.errorDuplicateImportOptions = errorDuplicateImportOptions;
  24326. exports.errorFailAfterWarnings = errorFailAfterWarnings;
  24327. exports.errorInvalidOption = errorInvalidOption;
  24328. exports.errorMissingConfig = errorMissingConfig;
  24329. exports.errorMissingExternalConfig = errorMissingExternalConfig;
  24330. exports.errorOnlyInlineSourcemapsForStdout = errorOnlyInlineSourcemapsForStdout;
  24331. exports.getAliasName = getAliasName;
  24332. exports.getAugmentedNamespace = getAugmentedNamespace;
  24333. exports.getNewArray = getNewArray;
  24334. exports.getOrCreate = getOrCreate;
  24335. exports.getRollupUrl = getRollupUrl;
  24336. exports.gray = gray;
  24337. exports.green = green;
  24338. exports.handleError = handleError;
  24339. exports.isWatchEnabled = isWatchEnabled;
  24340. exports.mergeOptions = mergeOptions;
  24341. exports.normalizePluginOption = normalizePluginOption;
  24342. exports.printQuotedStringList = printQuotedStringList;
  24343. exports.relativeId = relativeId;
  24344. exports.rollup = rollup;
  24345. exports.rollupInternal = rollupInternal;
  24346. exports.stderr = stderr;
  24347. exports.underline = underline;
  24348. exports.version = version$1;
  24349. exports.yellow = yellow;
  24350. //# sourceMappingURL=rollup.js.map