rollup.js 973 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460
  1. /*
  2. @license
  3. Rollup.js v3.23.1
  4. Sun, 04 Jun 2023 18:41:19 GMT - commit d83684788ef0e8bf0fc4449680960c3783a37def
  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. function _interopNamespaceDefault(e) {
  17. const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
  18. if (e) {
  19. for (const k in e) {
  20. n[k] = e[k];
  21. }
  22. }
  23. n.default = e;
  24. return n;
  25. }
  26. const tty__namespace = /*#__PURE__*/_interopNamespaceDefault(tty);
  27. var version$1 = "3.23.1";
  28. function ensureArray$1(items) {
  29. if (Array.isArray(items)) {
  30. return items.filter(Boolean);
  31. }
  32. if (items) {
  33. return [items];
  34. }
  35. return [];
  36. }
  37. // troubleshooting
  38. const URL_AVOIDING_EVAL = 'troubleshooting/#avoiding-eval';
  39. const URL_NAME_IS_NOT_EXPORTED = 'troubleshooting/#error-name-is-not-exported-by-module';
  40. const URL_THIS_IS_UNDEFINED = 'troubleshooting/#error-this-is-undefined';
  41. const URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY = 'troubleshooting/#warning-treating-module-as-external-dependency';
  42. const URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT = 'troubleshooting/#warning-sourcemap-is-likely-to-be-incorrect';
  43. // configuration-options
  44. const URL_MAXPARALLELFILEOPS = 'configuration-options/#maxparallelfileops';
  45. const URL_OUTPUT_AMD_ID = 'configuration-options/#output-amd-id';
  46. const URL_OUTPUT_AMD_BASEPATH = 'configuration-options/#output-amd-basepath';
  47. const URL_OUTPUT_DIR = 'configuration-options/#output-dir';
  48. const URL_OUTPUT_DYNAMICIMPORTFUNCTION = 'configuration-options/#output-dynamicimportfunction';
  49. const URL_OUTPUT_EXPORTS = 'configuration-options/#output-exports';
  50. const URL_OUTPUT_EXTEND = 'configuration-options/#output-extend';
  51. const URL_OUTPUT_FORMAT = 'configuration-options/#output-format';
  52. const URL_OUTPUT_GENERATEDCODE = 'configuration-options/#output-generatedcode';
  53. const URL_OUTPUT_EXPERIMENTALDEEPCHUNKOPTIMIZATION = 'configuration-options/#output-experimentaldeepdynamicchunkoptimization';
  54. const URL_OUTPUT_GENERATEDCODE_CONSTBINDINGS = 'configuration-options/#output-generatedcode-constbindings';
  55. const URL_OUTPUT_GENERATEDCODE_SYMBOLS = 'configuration-options/#output-generatedcode-symbols';
  56. const URL_OUTPUT_GLOBALS = 'configuration-options/#output-globals';
  57. const URL_OUTPUT_INLINEDYNAMICIMPORTS = 'configuration-options/#output-inlinedynamicimports';
  58. const URL_OUTPUT_INTEROP = 'configuration-options/#output-interop';
  59. const URL_OUTPUT_MANUALCHUNKS = 'configuration-options/#output-manualchunks';
  60. const URL_OUTPUT_NAME = 'configuration-options/#output-name';
  61. const URL_OUTPUT_PRESERVEMODULES = 'configuration-options/#output-preservemodules';
  62. const URL_OUTPUT_SOURCEMAPBASEURL = 'configuration-options/#output-sourcemapbaseurl';
  63. const URL_OUTPUT_SOURCEMAPFILE = 'configuration-options/#output-sourcemapfile';
  64. const URL_PRESERVEENTRYSIGNATURES = 'configuration-options/#preserveentrysignatures';
  65. const URL_TREESHAKE = 'configuration-options/#treeshake';
  66. const URL_TREESHAKE_MODULESIDEEFFECTS = 'configuration-options/#treeshake-modulesideeffects';
  67. const URL_WATCH = 'configuration-options/#watch';
  68. // command-line-interface
  69. const URL_BUNDLE_CONFIG_AS_CJS = 'command-line-interface/#bundleconfigascjs';
  70. const URL_CONFIGURATION_FILES = 'command-line-interface/#configuration-files';
  71. const URL_RENDERDYNAMICIMPORT = 'plugin-development/#renderdynamicimport';
  72. const URL_THIS_GETMODULEIDS = 'plugin-development/#this-getmoduleids';
  73. const URL_THIS_GETMODULEINFO = 'plugin-development/#this-getmoduleinfo';
  74. async function asyncFlatten(array) {
  75. do {
  76. array = (await Promise.all(array)).flat(Infinity);
  77. } while (array.some((v) => v?.then));
  78. return array;
  79. }
  80. const BLANK = Object.freeze(Object.create(null));
  81. const EMPTY_OBJECT = Object.freeze({});
  82. const EMPTY_ARRAY = Object.freeze([]);
  83. const EMPTY_SET = Object.freeze(new (class extends Set {
  84. add() {
  85. throw new Error('Cannot add to empty set');
  86. }
  87. })());
  88. function getLocator$1(source, options) {
  89. if (options === void 0) { options = {}; }
  90. var offsetLine = options.offsetLine || 0;
  91. var offsetColumn = options.offsetColumn || 0;
  92. var originalLines = source.split('\n');
  93. var start = 0;
  94. var lineRanges = originalLines.map(function (line, i) {
  95. var end = start + line.length + 1;
  96. var range = { start: start, end: end, line: i };
  97. start = end;
  98. return range;
  99. });
  100. var i = 0;
  101. function rangeContains(range, index) {
  102. return range.start <= index && index < range.end;
  103. }
  104. function getLocation(range, index) {
  105. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  106. }
  107. function locate(search, startIndex) {
  108. if (typeof search === 'string') {
  109. search = source.indexOf(search, startIndex || 0);
  110. }
  111. var range = lineRanges[i];
  112. var d = search >= range.end ? 1 : -1;
  113. while (range) {
  114. if (rangeContains(range, search))
  115. return getLocation(range, search);
  116. i += d;
  117. range = lineRanges[i];
  118. }
  119. }
  120. return locate;
  121. }
  122. function locate(source, search, options) {
  123. if (typeof options === 'number') {
  124. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  125. }
  126. return getLocator$1(source, options)(search, options && options.startIndex);
  127. }
  128. function spaces(index) {
  129. let result = '';
  130. while (index--)
  131. result += ' ';
  132. return result;
  133. }
  134. function tabsToSpaces(value) {
  135. return value.replace(/^\t+/, match => match.split('\t').join(' '));
  136. }
  137. const LINE_TRUNCATE_LENGTH = 120;
  138. const MIN_CHARACTERS_SHOWN_AFTER_LOCATION = 10;
  139. const ELLIPSIS = '...';
  140. function getCodeFrame(source, line, column) {
  141. let lines = source.split('\n');
  142. // Needed if a plugin did not generate correct sourcemaps
  143. if (line > lines.length)
  144. return '';
  145. const maxLineLength = Math.max(tabsToSpaces(lines[line - 1].slice(0, column)).length +
  146. MIN_CHARACTERS_SHOWN_AFTER_LOCATION +
  147. ELLIPSIS.length, LINE_TRUNCATE_LENGTH);
  148. const frameStart = Math.max(0, line - 3);
  149. let frameEnd = Math.min(line + 2, lines.length);
  150. lines = lines.slice(frameStart, frameEnd);
  151. while (!/\S/.test(lines[lines.length - 1])) {
  152. lines.pop();
  153. frameEnd -= 1;
  154. }
  155. const digits = String(frameEnd).length;
  156. return lines
  157. .map((sourceLine, index) => {
  158. const isErrorLine = frameStart + index + 1 === line;
  159. let lineNumber = String(index + frameStart + 1);
  160. while (lineNumber.length < digits)
  161. lineNumber = ` ${lineNumber}`;
  162. let displayedLine = tabsToSpaces(sourceLine);
  163. if (displayedLine.length > maxLineLength) {
  164. displayedLine = `${displayedLine.slice(0, maxLineLength - ELLIPSIS.length)}${ELLIPSIS}`;
  165. }
  166. if (isErrorLine) {
  167. const indicator = spaces(digits + 2 + tabsToSpaces(sourceLine.slice(0, column)).length) + '^';
  168. return `${lineNumber}: ${displayedLine}\n${indicator}`;
  169. }
  170. return `${lineNumber}: ${displayedLine}`;
  171. })
  172. .join('\n');
  173. }
  174. const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[/\\|])/;
  175. const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
  176. function isAbsolute(path) {
  177. return ABSOLUTE_PATH_REGEX.test(path);
  178. }
  179. function isRelative(path) {
  180. return RELATIVE_PATH_REGEX.test(path);
  181. }
  182. const BACKSLASH_REGEX = /\\/g;
  183. function normalize(path) {
  184. return path.replace(BACKSLASH_REGEX, '/');
  185. }
  186. function printQuotedStringList(list, verbs) {
  187. const isSingleItem = list.length <= 1;
  188. const quotedList = list.map(item => `"${item}"`);
  189. let output = isSingleItem
  190. ? quotedList[0]
  191. : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
  192. if (verbs) {
  193. output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
  194. }
  195. return output;
  196. }
  197. const ANY_SLASH_REGEX = /[/\\]/;
  198. function relative(from, to) {
  199. const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
  200. const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
  201. if (fromParts[0] === '.')
  202. fromParts.shift();
  203. if (toParts[0] === '.')
  204. toParts.shift();
  205. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  206. fromParts.shift();
  207. toParts.shift();
  208. }
  209. while (toParts[0] === '..' && fromParts.length > 0) {
  210. toParts.shift();
  211. fromParts.pop();
  212. }
  213. while (fromParts.pop()) {
  214. toParts.unshift('..');
  215. }
  216. return toParts.join('/');
  217. }
  218. function getAliasName(id) {
  219. const base = node_path.basename(id);
  220. return base.slice(0, Math.max(0, base.length - node_path.extname(id).length));
  221. }
  222. function relativeId(id) {
  223. if (!isAbsolute(id))
  224. return id;
  225. return relative(node_path.resolve(), id);
  226. }
  227. function isPathFragment(name) {
  228. // starting with "/", "./", "../", "C:/"
  229. return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
  230. }
  231. const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
  232. function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
  233. let relativePath = normalize(relative(node_path.dirname(importerId), targetPath));
  234. if (stripJsExtension && relativePath.endsWith('.js')) {
  235. relativePath = relativePath.slice(0, -3);
  236. }
  237. if (ensureFileName) {
  238. if (relativePath === '')
  239. return '../' + node_path.basename(targetPath);
  240. if (UPPER_DIR_REGEX.test(relativePath)) {
  241. return [...relativePath.split('/'), '..', node_path.basename(targetPath)].join('/');
  242. }
  243. }
  244. return relativePath ? (relativePath.startsWith('..') ? relativePath : './' + relativePath) : '.';
  245. }
  246. function isValidUrl(url) {
  247. try {
  248. new URL(url);
  249. }
  250. catch {
  251. return false;
  252. }
  253. return true;
  254. }
  255. function getRollupUrl(snippet) {
  256. return `https://rollupjs.org/${snippet}`;
  257. }
  258. function addTrailingSlashIfMissed(url) {
  259. if (!url.endsWith('/')) {
  260. return url + '/';
  261. }
  262. return url;
  263. }
  264. function error(base) {
  265. if (!(base instanceof Error)) {
  266. base = Object.assign(new Error(base.message), base);
  267. Object.defineProperty(base, 'name', { value: 'RollupError' });
  268. }
  269. throw base;
  270. }
  271. function augmentCodeLocation(properties, pos, source, id) {
  272. if (typeof pos === 'object') {
  273. const { line, column } = pos;
  274. properties.loc = { column, file: id, line };
  275. }
  276. else {
  277. properties.pos = pos;
  278. const { line, column } = locate(source, pos, { offsetLine: 1 });
  279. properties.loc = { column, file: id, line };
  280. }
  281. if (properties.frame === undefined) {
  282. const { line, column } = properties.loc;
  283. properties.frame = getCodeFrame(source, line, column);
  284. }
  285. }
  286. // Error codes should be sorted alphabetically while errors should be sorted by
  287. // error code below
  288. 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';
  289. function errorAddonNotGenerated(message, hook, plugin) {
  290. return {
  291. code: ADDON_ERROR,
  292. message: `Could not retrieve "${hook}". Check configuration of plugin "${plugin}".
  293. \tError Message: ${message}`
  294. };
  295. }
  296. function errorAlreadyClosed() {
  297. return {
  298. code: ALREADY_CLOSED,
  299. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  300. };
  301. }
  302. function errorAmbiguousExternalNamespaces(binding, reexportingModule, usedModule, sources) {
  303. return {
  304. binding,
  305. code: AMBIGUOUS_EXTERNAL_NAMESPACES,
  306. ids: sources,
  307. 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)}".`,
  308. reexporter: reexportingModule
  309. };
  310. }
  311. function errorAnonymousPluginCache() {
  312. return {
  313. code: ANONYMOUS_PLUGIN_CACHE,
  314. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  315. };
  316. }
  317. function errorAssetNotFinalisedForFileName(name) {
  318. return {
  319. code: ASSET_NOT_FINALISED,
  320. 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.`
  321. };
  322. }
  323. function errorAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  324. return {
  325. code: ASSET_NOT_FOUND,
  326. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  327. };
  328. }
  329. function errorAssetSourceAlreadySet(name) {
  330. return {
  331. code: ASSET_SOURCE_ALREADY_SET,
  332. message: `Unable to set the source for asset "${name}", source already set.`
  333. };
  334. }
  335. function errorNoAssetSourceSet(assetName) {
  336. return {
  337. code: ASSET_SOURCE_MISSING,
  338. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  339. };
  340. }
  341. function errorBadLoader(id) {
  342. return {
  343. code: BAD_LOADER,
  344. message: `Error loading "${relativeId(id)}": plugin load hook should return a string, a { code, map } object, or nothing/null.`
  345. };
  346. }
  347. function errorCannotCallNamespace(name) {
  348. return {
  349. code: CANNOT_CALL_NAMESPACE,
  350. message: `Cannot call a namespace ("${name}").`
  351. };
  352. }
  353. function errorCannotEmitFromOptionsHook() {
  354. return {
  355. code: CANNOT_EMIT_FROM_OPTIONS_HOOK,
  356. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  357. };
  358. }
  359. function errorChunkNotGeneratedForFileName(name) {
  360. return {
  361. code: CHUNK_NOT_GENERATED,
  362. 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.`
  363. };
  364. }
  365. function errorChunkInvalid({ fileName, code }, exception) {
  366. const errorProperties = {
  367. code: CHUNK_INVALID,
  368. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  369. };
  370. augmentCodeLocation(errorProperties, exception.loc, code, fileName);
  371. return errorProperties;
  372. }
  373. function errorCircularDependency(cyclePath) {
  374. return {
  375. code: CIRCULAR_DEPENDENCY,
  376. ids: cyclePath,
  377. message: `Circular dependency: ${cyclePath.map(relativeId).join(' -> ')}`
  378. };
  379. }
  380. function errorCircularReexport(exportName, exporter) {
  381. return {
  382. code: CIRCULAR_REEXPORT,
  383. exporter,
  384. message: `"${exportName}" cannot be exported from "${relativeId(exporter)}" as it is a reexport that references itself.`
  385. };
  386. }
  387. function errorCyclicCrossChunkReexport(exportName, exporter, reexporter, importer, preserveModules) {
  388. return {
  389. code: CYCLIC_CROSS_CHUNK_REEXPORT,
  390. exporter,
  391. id: importer,
  392. 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.`,
  393. reexporter
  394. };
  395. }
  396. function errorDeprecation(deprecation, urlSnippet, plugin) {
  397. return {
  398. code: DEPRECATED_FEATURE,
  399. message: deprecation,
  400. url: getRollupUrl(urlSnippet),
  401. ...(plugin ? { plugin } : {})
  402. };
  403. }
  404. function errorDuplicateImportOptions() {
  405. return {
  406. code: DUPLICATE_IMPORT_OPTIONS,
  407. message: 'Either use --input, or pass input path as argument'
  408. };
  409. }
  410. function errorDuplicatePluginName(plugin) {
  411. return {
  412. code: DUPLICATE_PLUGIN_NAME,
  413. 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).`
  414. };
  415. }
  416. function errorEmptyChunk(chunkName) {
  417. return {
  418. code: EMPTY_BUNDLE,
  419. message: `Generated an empty chunk: "${chunkName}".`,
  420. names: [chunkName]
  421. };
  422. }
  423. function errorEval(id) {
  424. return {
  425. code: EVAL,
  426. id,
  427. message: `Use of eval in "${relativeId(id)}" is strongly discouraged as it poses security risks and may cause issues with minification.`,
  428. url: getRollupUrl(URL_AVOIDING_EVAL)
  429. };
  430. }
  431. function errorExternalSyntheticExports(id, importer) {
  432. return {
  433. code: EXTERNAL_SYNTHETIC_EXPORTS,
  434. exporter: id,
  435. message: `External "${id}" cannot have "syntheticNamedExports" enabled (imported by "${relativeId(importer)}").`
  436. };
  437. }
  438. function errorFailAfterWarnings() {
  439. return {
  440. code: FAIL_AFTER_WARNINGS,
  441. message: 'Warnings occurred and --failAfterWarnings flag present.'
  442. };
  443. }
  444. function errorFileNameConflict(fileName) {
  445. return {
  446. code: FILE_NAME_CONFLICT,
  447. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  448. };
  449. }
  450. function errorFileReferenceIdNotFoundForFilename(assetReferenceId) {
  451. return {
  452. code: FILE_NOT_FOUND,
  453. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  454. };
  455. }
  456. function errorIllegalIdentifierAsName(name) {
  457. return {
  458. code: ILLEGAL_IDENTIFIER_AS_NAME,
  459. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`,
  460. url: getRollupUrl(URL_OUTPUT_EXTEND)
  461. };
  462. }
  463. function errorIllegalImportReassignment(name, importingId) {
  464. return {
  465. code: ILLEGAL_REASSIGNMENT,
  466. message: `Illegal reassignment of import "${name}" in "${relativeId(importingId)}".`
  467. };
  468. }
  469. function errorInconsistentImportAssertions(existingAssertions, newAssertions, source, importer) {
  470. return {
  471. code: INCONSISTENT_IMPORT_ASSERTIONS,
  472. 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.`
  473. };
  474. }
  475. const formatAssertions$1 = (assertions) => {
  476. const entries = Object.entries(assertions);
  477. if (entries.length === 0)
  478. return 'no';
  479. return entries.map(([key, value]) => `"${key}": "${value}"`).join(', ');
  480. };
  481. function errorInputHookInOutputPlugin(pluginName, hookName) {
  482. return {
  483. code: INPUT_HOOK_IN_OUTPUT_PLUGIN,
  484. 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.`
  485. };
  486. }
  487. function errorCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  488. return {
  489. code: INVALID_CHUNK,
  490. message: `Cannot assign "${relativeId(moduleId)}" to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  491. };
  492. }
  493. function errorCannotBundleConfigAsEsm(originalError) {
  494. return {
  495. cause: originalError,
  496. code: INVALID_CONFIG_MODULE_FORMAT,
  497. 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}`,
  498. stack: originalError.stack,
  499. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  500. };
  501. }
  502. function errorCannotLoadConfigAsCjs(originalError) {
  503. return {
  504. cause: originalError,
  505. code: INVALID_CONFIG_MODULE_FORMAT,
  506. 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}`,
  507. stack: originalError.stack,
  508. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  509. };
  510. }
  511. function errorCannotLoadConfigAsEsm(originalError) {
  512. return {
  513. cause: originalError,
  514. code: INVALID_CONFIG_MODULE_FORMAT,
  515. 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}`,
  516. stack: originalError.stack,
  517. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  518. };
  519. }
  520. function errorInvalidExportOptionValue(optionValue) {
  521. return {
  522. code: INVALID_EXPORT_OPTION,
  523. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}".`,
  524. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  525. };
  526. }
  527. function errorIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  528. return {
  529. code: INVALID_EXPORT_OPTION,
  530. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${printQuotedStringList(keys)}`,
  531. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  532. };
  533. }
  534. function errorInternalIdCannotBeExternal(source, importer) {
  535. return {
  536. code: INVALID_EXTERNAL_ID,
  537. message: `"${source}" is imported as an external by "${relativeId(importer)}", but is already an existing non-external module id.`
  538. };
  539. }
  540. function errorInvalidOption(option, urlSnippet, explanation, value) {
  541. return {
  542. code: INVALID_OPTION,
  543. message: `Invalid value ${value === undefined ? '' : `${JSON.stringify(value)} `}for option "${option}" - ${explanation}.`,
  544. url: getRollupUrl(urlSnippet)
  545. };
  546. }
  547. function errorInvalidAddonPluginHook(hook, plugin) {
  548. return {
  549. code: INVALID_PLUGIN_HOOK,
  550. hook,
  551. message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a string, a function hook or an object with a "handler" string or function.`,
  552. plugin
  553. };
  554. }
  555. function errorInvalidFunctionPluginHook(hook, plugin) {
  556. return {
  557. code: INVALID_PLUGIN_HOOK,
  558. hook,
  559. message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a function hook or an object with a "handler" function.`,
  560. plugin
  561. };
  562. }
  563. function errorInvalidRollupPhaseForAddWatchFile() {
  564. return {
  565. code: INVALID_ROLLUP_PHASE,
  566. message: `Cannot call "addWatchFile" after the build has finished.`
  567. };
  568. }
  569. function errorInvalidRollupPhaseForChunkEmission() {
  570. return {
  571. code: INVALID_ROLLUP_PHASE,
  572. message: `Cannot emit chunks after module loading has finished.`
  573. };
  574. }
  575. function errorInvalidSetAssetSourceCall() {
  576. return {
  577. code: INVALID_SETASSETSOURCE,
  578. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  579. };
  580. }
  581. function errorInvalidFormatForTopLevelAwait(id, format) {
  582. return {
  583. code: INVALID_TLA_FORMAT,
  584. id,
  585. message: `Module format "${format}" does not support top-level await. Use the "es" or "system" output formats rather.`
  586. };
  587. }
  588. function errorMissingConfig() {
  589. return {
  590. code: MISSING_CONFIG,
  591. message: 'Config file must export an options object, or an array of options objects',
  592. url: getRollupUrl(URL_CONFIGURATION_FILES)
  593. };
  594. }
  595. function errorMissingExport(binding, importingModule, exporter) {
  596. const isJson = node_path.extname(exporter) === '.json';
  597. return {
  598. binding,
  599. code: MISSING_EXPORT,
  600. exporter,
  601. id: importingModule,
  602. message: `"${binding}" is not exported by "${relativeId(exporter)}", imported by "${relativeId(importingModule)}".${isJson ? ' (Note that you need @rollup/plugin-json to import JSON files)' : ''}`,
  603. url: getRollupUrl(URL_NAME_IS_NOT_EXPORTED)
  604. };
  605. }
  606. function errorMissingExternalConfig(file) {
  607. return {
  608. code: MISSING_EXTERNAL_CONFIG,
  609. message: `Could not resolve config file "${file}"`
  610. };
  611. }
  612. function errorMissingGlobalName(externalId, guess) {
  613. return {
  614. code: MISSING_GLOBAL_NAME,
  615. id: externalId,
  616. message: `No name was provided for external module "${externalId}" in "output.globals" – guessing "${guess}".`,
  617. names: [guess],
  618. url: getRollupUrl(URL_OUTPUT_GLOBALS)
  619. };
  620. }
  621. function errorImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  622. return {
  623. code: MISSING_IMPLICIT_DEPENDANT,
  624. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  625. };
  626. }
  627. function errorUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  628. return {
  629. code: MISSING_IMPLICIT_DEPENDANT,
  630. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  631. };
  632. }
  633. function errorImplicitDependantIsNotIncluded(module) {
  634. const implicitDependencies = [...module.implicitlyLoadedBefore]
  635. .map(dependency => relativeId(dependency.id))
  636. .sort();
  637. return {
  638. code: MISSING_IMPLICIT_DEPENDANT,
  639. 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.`
  640. };
  641. }
  642. function errorMissingNameOptionForIifeExport() {
  643. return {
  644. code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
  645. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`,
  646. url: getRollupUrl(URL_OUTPUT_NAME)
  647. };
  648. }
  649. function errorMissingNameOptionForUmdExport() {
  650. return {
  651. code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
  652. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.',
  653. url: getRollupUrl(URL_OUTPUT_NAME)
  654. };
  655. }
  656. function errorMissingNodeBuiltins(externalBuiltins) {
  657. return {
  658. code: MISSING_NODE_BUILTINS,
  659. ids: externalBuiltins,
  660. 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`
  661. };
  662. }
  663. // eslint-disable-next-line unicorn/prevent-abbreviations
  664. function errorMissingFileOrDirOption() {
  665. return {
  666. code: MISSING_OPTION,
  667. message: 'You must specify "output.file" or "output.dir" for the build.',
  668. url: getRollupUrl(URL_OUTPUT_DIR)
  669. };
  670. }
  671. function errorMixedExport(facadeModuleId, name) {
  672. return {
  673. code: MIXED_EXPORTS,
  674. id: facadeModuleId,
  675. 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.`,
  676. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  677. };
  678. }
  679. function errorModuleLevelDirective(directive, id) {
  680. return {
  681. code: MODULE_LEVEL_DIRECTIVE,
  682. id,
  683. message: `Module level directives cause errors when bundled, "${directive}" in "${relativeId(id)}" was ignored.`
  684. };
  685. }
  686. function errorNamespaceConflict(binding, reexportingModuleId, sources) {
  687. return {
  688. binding,
  689. code: NAMESPACE_CONFLICT,
  690. ids: sources,
  691. message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${binding}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored).`,
  692. reexporter: reexportingModuleId
  693. };
  694. }
  695. function errorNoTransformMapOrAstWithoutCode(pluginName) {
  696. return {
  697. code: NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  698. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  699. 'a "code". This will be ignored.'
  700. };
  701. }
  702. function errorOnlyInlineSourcemapsForStdout() {
  703. return {
  704. code: ONLY_INLINE_SOURCEMAPS,
  705. message: 'Only inline sourcemaps are supported when bundling to stdout.'
  706. };
  707. }
  708. function errorParseError(error, moduleId) {
  709. let message = error.message.replace(/ \(\d+:\d+\)$/, '');
  710. if (moduleId.endsWith('.json')) {
  711. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  712. }
  713. else if (!moduleId.endsWith('.js')) {
  714. message += ' (Note that you need plugins to import files that are not JavaScript)';
  715. }
  716. return {
  717. cause: error,
  718. code: PARSE_ERROR,
  719. id: moduleId,
  720. message
  721. };
  722. }
  723. function errorPluginError(error, plugin, { hook, id } = {}) {
  724. if (typeof error === 'string')
  725. error = { message: error };
  726. if (error.code && error.code !== PLUGIN_ERROR) {
  727. error.pluginCode = error.code;
  728. }
  729. error.code = PLUGIN_ERROR;
  730. error.plugin = plugin;
  731. if (hook) {
  732. error.hook = hook;
  733. }
  734. if (id) {
  735. error.id = id;
  736. }
  737. return error;
  738. }
  739. function errorShimmedExport(id, binding) {
  740. return {
  741. binding,
  742. code: SHIMMED_EXPORT,
  743. exporter: id,
  744. message: `Missing export "${binding}" has been shimmed in module "${relativeId(id)}".`
  745. };
  746. }
  747. function errorSourcemapBroken(plugin) {
  748. return {
  749. code: SOURCEMAP_BROKEN,
  750. 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`,
  751. plugin,
  752. url: getRollupUrl(URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT)
  753. };
  754. }
  755. function errorConflictingSourcemapSources(filename) {
  756. return {
  757. code: SOURCEMAP_BROKEN,
  758. message: `Multiple conflicting contents for sourcemap source ${filename}`
  759. };
  760. }
  761. function errorInvalidSourcemapForError(error, id, column, line, pos) {
  762. return {
  763. cause: error,
  764. code: SOURCEMAP_ERROR,
  765. id,
  766. loc: {
  767. column,
  768. file: id,
  769. line
  770. },
  771. message: `Error when using sourcemap for reporting an error: ${error.message}`,
  772. pos
  773. };
  774. }
  775. function errorSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  776. return {
  777. code: SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  778. exporter: id,
  779. message: `Module "${relativeId(id)}" that is marked with \`syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}\` needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  780. ? `an explicit export named "${syntheticNamedExportsOption}"`
  781. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  782. };
  783. }
  784. function errorThisIsUndefined() {
  785. return {
  786. code: THIS_IS_UNDEFINED,
  787. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  788. url: getRollupUrl(URL_THIS_IS_UNDEFINED)
  789. };
  790. }
  791. function errorUnexpectedNamedImport(id, imported, isReexport) {
  792. const importType = isReexport ? 'reexport' : 'import';
  793. return {
  794. code: UNEXPECTED_NAMED_IMPORT,
  795. exporter: id,
  796. 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.`,
  797. url: getRollupUrl(URL_OUTPUT_INTEROP)
  798. };
  799. }
  800. function errorUnexpectedNamespaceReexport(id) {
  801. return {
  802. code: UNEXPECTED_NAMED_IMPORT,
  803. exporter: id,
  804. 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.`,
  805. url: getRollupUrl(URL_OUTPUT_INTEROP)
  806. };
  807. }
  808. function errorUnknownOption(optionType, unknownOptions, validOptions) {
  809. return {
  810. code: UNKNOWN_OPTION,
  811. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.join(', ')}`
  812. };
  813. }
  814. function errorEntryCannotBeExternal(unresolvedId) {
  815. return {
  816. code: UNRESOLVED_ENTRY,
  817. message: `Entry module "${relativeId(unresolvedId)}" cannot be external.`
  818. };
  819. }
  820. function errorUnresolvedEntry(unresolvedId) {
  821. return {
  822. code: UNRESOLVED_ENTRY,
  823. message: `Could not resolve entry module "${relativeId(unresolvedId)}".`
  824. };
  825. }
  826. function errorUnresolvedImport(source, importer) {
  827. return {
  828. code: UNRESOLVED_IMPORT,
  829. exporter: source,
  830. id: importer,
  831. message: `Could not resolve "${source}" from "${relativeId(importer)}"`
  832. };
  833. }
  834. function errorUnresolvedImportTreatedAsExternal(source, importer) {
  835. return {
  836. code: UNRESOLVED_IMPORT,
  837. exporter: source,
  838. id: importer,
  839. message: `"${source}" is imported by "${relativeId(importer)}", but could not be resolved – treating it as an external dependency.`,
  840. url: getRollupUrl(URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY)
  841. };
  842. }
  843. function errorUnusedExternalImports(externalId, names, importers) {
  844. return {
  845. code: UNUSED_EXTERNAL_IMPORT,
  846. exporter: externalId,
  847. ids: importers,
  848. message: `${printQuotedStringList(names, [
  849. 'is',
  850. 'are'
  851. ])} imported from external module "${externalId}" but never used in ${printQuotedStringList(importers.map(importer => relativeId(importer)))}.`,
  852. names
  853. };
  854. }
  855. function errorFailedValidation(message) {
  856. return {
  857. code: VALIDATION_ERROR,
  858. message
  859. };
  860. }
  861. function warnDeprecation(deprecation, urlSnippet, activeDeprecation, options, plugin) {
  862. warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, options.onwarn, options.strictDeprecations, plugin);
  863. }
  864. function warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, warn, strictDeprecations, plugin) {
  865. if (activeDeprecation || strictDeprecations) {
  866. const warning = errorDeprecation(deprecation, urlSnippet, plugin);
  867. if (strictDeprecations) {
  868. return error(warning);
  869. }
  870. warn(warning);
  871. }
  872. }
  873. const defaultOnWarn = warning => console.warn(warning.message || warning);
  874. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  875. const validOptionSet = new Set(validOptions);
  876. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  877. if (unknownOptions.length > 0) {
  878. warn(errorUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  879. }
  880. }
  881. const treeshakePresets = {
  882. recommended: {
  883. annotations: true,
  884. correctVarValueBeforeDeclaration: false,
  885. manualPureFunctions: EMPTY_ARRAY,
  886. moduleSideEffects: () => true,
  887. propertyReadSideEffects: true,
  888. tryCatchDeoptimization: true,
  889. unknownGlobalSideEffects: false
  890. },
  891. safest: {
  892. annotations: true,
  893. correctVarValueBeforeDeclaration: true,
  894. manualPureFunctions: EMPTY_ARRAY,
  895. moduleSideEffects: () => true,
  896. propertyReadSideEffects: true,
  897. tryCatchDeoptimization: true,
  898. unknownGlobalSideEffects: true
  899. },
  900. smallest: {
  901. annotations: true,
  902. correctVarValueBeforeDeclaration: false,
  903. manualPureFunctions: EMPTY_ARRAY,
  904. moduleSideEffects: () => false,
  905. propertyReadSideEffects: false,
  906. tryCatchDeoptimization: false,
  907. unknownGlobalSideEffects: false
  908. }
  909. };
  910. const generatedCodePresets = {
  911. es2015: {
  912. arrowFunctions: true,
  913. constBindings: true,
  914. objectShorthand: true,
  915. reservedNamesAsProps: true,
  916. symbols: true
  917. },
  918. es5: {
  919. arrowFunctions: false,
  920. constBindings: false,
  921. objectShorthand: false,
  922. reservedNamesAsProps: true,
  923. symbols: false
  924. }
  925. };
  926. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  927. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  928. if (typeof value === 'string') {
  929. const preset = presets[value];
  930. if (preset) {
  931. return preset;
  932. }
  933. error(errorInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  934. }
  935. return objectifyOption(value);
  936. };
  937. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  938. const presetName = value?.preset;
  939. if (presetName) {
  940. const preset = presets[presetName];
  941. if (preset) {
  942. return { ...preset, ...value };
  943. }
  944. else {
  945. error(errorInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  946. }
  947. }
  948. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  949. };
  950. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  951. const commandAliases = {
  952. c: 'config',
  953. d: 'dir',
  954. e: 'external',
  955. f: 'format',
  956. g: 'globals',
  957. h: 'help',
  958. i: 'input',
  959. m: 'sourcemap',
  960. n: 'name',
  961. o: 'file',
  962. p: 'plugin',
  963. v: 'version',
  964. w: 'watch'
  965. };
  966. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  967. async function mergeOptions(config, rawCommandOptions = EMPTY_COMMAND_OPTIONS, defaultOnWarnHandler = defaultOnWarn) {
  968. const command = getCommandOptions(rawCommandOptions);
  969. const inputOptions = await mergeInputOptions(config, command, defaultOnWarnHandler);
  970. const warn = inputOptions.onwarn;
  971. if (command.output) {
  972. Object.assign(command, command.output);
  973. }
  974. const outputOptionsArray = ensureArray$1(config.output);
  975. if (outputOptionsArray.length === 0)
  976. outputOptionsArray.push({});
  977. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, warn)));
  978. warnUnknownOptions(command, [
  979. ...Object.keys(inputOptions),
  980. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  981. ...Object.keys(commandAliases),
  982. 'bundleConfigAsCjs',
  983. 'config',
  984. 'environment',
  985. 'plugin',
  986. 'silent',
  987. 'failAfterWarnings',
  988. 'stdin',
  989. 'waitForBundleInput',
  990. 'configPlugin'
  991. ], 'CLI flags', warn, /^_$|output$|config/);
  992. inputOptions.output = outputOptions;
  993. return inputOptions;
  994. }
  995. function getCommandOptions(rawCommandOptions) {
  996. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  997. ? rawCommandOptions.external.split(',')
  998. : [];
  999. return {
  1000. ...rawCommandOptions,
  1001. external,
  1002. globals: typeof rawCommandOptions.globals === 'string'
  1003. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  1004. const [id, variableName] = globalDefinition.split(':');
  1005. globals[id] = variableName;
  1006. if (!external.includes(id)) {
  1007. external.push(id);
  1008. }
  1009. return globals;
  1010. }, Object.create(null))
  1011. : undefined
  1012. };
  1013. }
  1014. async function mergeInputOptions(config, overrides, defaultOnWarnHandler) {
  1015. const getOption = (name) => overrides[name] ?? config[name];
  1016. const inputOptions = {
  1017. acorn: getOption('acorn'),
  1018. acornInjectPlugins: config.acornInjectPlugins,
  1019. cache: config.cache,
  1020. context: getOption('context'),
  1021. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  1022. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  1023. external: getExternal(config, overrides),
  1024. inlineDynamicImports: getOption('inlineDynamicImports'),
  1025. input: getOption('input') || [],
  1026. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  1027. manualChunks: getOption('manualChunks'),
  1028. maxParallelFileOps: getOption('maxParallelFileOps'),
  1029. maxParallelFileReads: getOption('maxParallelFileReads'),
  1030. moduleContext: getOption('moduleContext'),
  1031. onwarn: getOnWarn(config, defaultOnWarnHandler),
  1032. perf: getOption('perf'),
  1033. plugins: await normalizePluginOption(config.plugins),
  1034. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  1035. preserveModules: getOption('preserveModules'),
  1036. preserveSymlinks: getOption('preserveSymlinks'),
  1037. shimMissingExports: getOption('shimMissingExports'),
  1038. strictDeprecations: getOption('strictDeprecations'),
  1039. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ')),
  1040. watch: getWatch(config, overrides)
  1041. };
  1042. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', inputOptions.onwarn, /^output$/);
  1043. return inputOptions;
  1044. }
  1045. const getExternal = (config, overrides) => {
  1046. const configExternal = config.external;
  1047. return typeof configExternal === 'function'
  1048. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  1049. : [...ensureArray$1(configExternal), ...overrides.external];
  1050. };
  1051. const getOnWarn = (config, defaultOnWarnHandler) => config.onwarn ? warning => config.onwarn(warning, defaultOnWarnHandler) : defaultOnWarnHandler;
  1052. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  1053. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  1054. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  1055. if (commandOption !== undefined) {
  1056. return commandOption && { ...configOption, ...commandOption };
  1057. }
  1058. return configOption;
  1059. };
  1060. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  1061. const isWatchEnabled = (optionValue) => {
  1062. if (Array.isArray(optionValue)) {
  1063. return optionValue.reduce((result, value) => (typeof value === 'boolean' ? value : result), false);
  1064. }
  1065. return optionValue === true;
  1066. };
  1067. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  1068. if (!optionValue) {
  1069. return optionValue;
  1070. }
  1071. if (Array.isArray(optionValue)) {
  1072. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  1073. }
  1074. return objectifyValue(optionValue);
  1075. };
  1076. async function mergeOutputOptions(config, overrides, warn) {
  1077. const getOption = (name) => overrides[name] ?? config[name];
  1078. const outputOptions = {
  1079. amd: getObjectOption(config, overrides, 'amd'),
  1080. assetFileNames: getOption('assetFileNames'),
  1081. banner: getOption('banner'),
  1082. chunkFileNames: getOption('chunkFileNames'),
  1083. compact: getOption('compact'),
  1084. dir: getOption('dir'),
  1085. dynamicImportFunction: getOption('dynamicImportFunction'),
  1086. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  1087. entryFileNames: getOption('entryFileNames'),
  1088. esModule: getOption('esModule'),
  1089. experimentalDeepDynamicChunkOptimization: getOption('experimentalDeepDynamicChunkOptimization'),
  1090. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  1091. exports: getOption('exports'),
  1092. extend: getOption('extend'),
  1093. externalImportAssertions: getOption('externalImportAssertions'),
  1094. externalLiveBindings: getOption('externalLiveBindings'),
  1095. file: getOption('file'),
  1096. footer: getOption('footer'),
  1097. format: getOption('format'),
  1098. freeze: getOption('freeze'),
  1099. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '')),
  1100. globals: getOption('globals'),
  1101. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  1102. indent: getOption('indent'),
  1103. inlineDynamicImports: getOption('inlineDynamicImports'),
  1104. interop: getOption('interop'),
  1105. intro: getOption('intro'),
  1106. manualChunks: getOption('manualChunks'),
  1107. minifyInternalExports: getOption('minifyInternalExports'),
  1108. name: getOption('name'),
  1109. namespaceToStringTag: getOption('namespaceToStringTag'),
  1110. noConflict: getOption('noConflict'),
  1111. outro: getOption('outro'),
  1112. paths: getOption('paths'),
  1113. plugins: await normalizePluginOption(config.plugins),
  1114. preferConst: getOption('preferConst'),
  1115. preserveModules: getOption('preserveModules'),
  1116. preserveModulesRoot: getOption('preserveModulesRoot'),
  1117. sanitizeFileName: getOption('sanitizeFileName'),
  1118. sourcemap: getOption('sourcemap'),
  1119. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  1120. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  1121. sourcemapFile: getOption('sourcemapFile'),
  1122. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  1123. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  1124. strict: getOption('strict'),
  1125. systemNullSetters: getOption('systemNullSetters'),
  1126. validate: getOption('validate')
  1127. };
  1128. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', warn);
  1129. return outputOptions;
  1130. }
  1131. const {
  1132. env = {},
  1133. argv = [],
  1134. platform = "",
  1135. } = typeof process === "undefined" ? {} : process;
  1136. const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
  1137. const isForced = "FORCE_COLOR" in env || argv.includes("--color");
  1138. const isWindows = platform === "win32";
  1139. const isDumbTerminal = env.TERM === "dumb";
  1140. const isCompatibleTerminal =
  1141. tty__namespace && tty__namespace.isatty && tty__namespace.isatty(1) && env.TERM && !isDumbTerminal;
  1142. const isCI =
  1143. "CI" in env &&
  1144. ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
  1145. const isColorSupported =
  1146. !isDisabled &&
  1147. (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);
  1148. const replaceClose = (
  1149. index,
  1150. string,
  1151. close,
  1152. replace,
  1153. head = string.substring(0, index) + replace,
  1154. tail = string.substring(index + close.length),
  1155. next = tail.indexOf(close)
  1156. ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
  1157. const clearBleed = (index, string, open, close, replace) =>
  1158. index < 0
  1159. ? open + string + close
  1160. : open + replaceClose(index, string, close, replace) + close;
  1161. const filterEmpty =
  1162. (open, close, replace = open, at = open.length + 1) =>
  1163. (string) =>
  1164. string || !(string === "" || string === undefined)
  1165. ? clearBleed(
  1166. ("" + string).indexOf(close, at),
  1167. string,
  1168. open,
  1169. close,
  1170. replace
  1171. )
  1172. : "";
  1173. const init = (open, close, replace) =>
  1174. filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
  1175. const colors = {
  1176. reset: init(0, 0),
  1177. bold: init(1, 22, "\x1b[22m\x1b[1m"),
  1178. dim: init(2, 22, "\x1b[22m\x1b[2m"),
  1179. italic: init(3, 23),
  1180. underline: init(4, 24),
  1181. inverse: init(7, 27),
  1182. hidden: init(8, 28),
  1183. strikethrough: init(9, 29),
  1184. black: init(30, 39),
  1185. red: init(31, 39),
  1186. green: init(32, 39),
  1187. yellow: init(33, 39),
  1188. blue: init(34, 39),
  1189. magenta: init(35, 39),
  1190. cyan: init(36, 39),
  1191. white: init(37, 39),
  1192. gray: init(90, 39),
  1193. bgBlack: init(40, 49),
  1194. bgRed: init(41, 49),
  1195. bgGreen: init(42, 49),
  1196. bgYellow: init(43, 49),
  1197. bgBlue: init(44, 49),
  1198. bgMagenta: init(45, 49),
  1199. bgCyan: init(46, 49),
  1200. bgWhite: init(47, 49),
  1201. blackBright: init(90, 39),
  1202. redBright: init(91, 39),
  1203. greenBright: init(92, 39),
  1204. yellowBright: init(93, 39),
  1205. blueBright: init(94, 39),
  1206. magentaBright: init(95, 39),
  1207. cyanBright: init(96, 39),
  1208. whiteBright: init(97, 39),
  1209. bgBlackBright: init(100, 49),
  1210. bgRedBright: init(101, 49),
  1211. bgGreenBright: init(102, 49),
  1212. bgYellowBright: init(103, 49),
  1213. bgBlueBright: init(104, 49),
  1214. bgMagentaBright: init(105, 49),
  1215. bgCyanBright: init(106, 49),
  1216. bgWhiteBright: init(107, 49),
  1217. };
  1218. const createColors = ({ useColor = isColorSupported } = {}) =>
  1219. useColor
  1220. ? colors
  1221. : Object.keys(colors).reduce(
  1222. (colors, key) => ({ ...colors, [key]: String }),
  1223. {}
  1224. );
  1225. createColors();
  1226. // @see https://no-color.org
  1227. // @see https://www.npmjs.com/package/chalk
  1228. const { bold, cyan, dim, gray, green, red, underline, yellow } = createColors({
  1229. useColor: process$1.env.FORCE_COLOR !== '0' && !process$1.env.NO_COLOR
  1230. });
  1231. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  1232. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  1233. function handleError(error, recover = false) {
  1234. const name = error.name || error.cause?.name;
  1235. const nameSection = name ? `${name}: ` : '';
  1236. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  1237. const message = `${pluginSection}${nameSection}${error.message}`;
  1238. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  1239. if (error.url) {
  1240. outputLines.push(cyan(error.url));
  1241. }
  1242. if (error.loc) {
  1243. outputLines.push(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  1244. }
  1245. else if (error.id) {
  1246. outputLines.push(relativeId(error.id));
  1247. }
  1248. if (error.frame) {
  1249. outputLines.push(dim(error.frame));
  1250. }
  1251. if (error.stack) {
  1252. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  1253. }
  1254. outputLines.push('', '');
  1255. stderr(outputLines.join('\n'));
  1256. if (!recover)
  1257. process$1.exit(1);
  1258. }
  1259. const comma = ','.charCodeAt(0);
  1260. const semicolon = ';'.charCodeAt(0);
  1261. const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  1262. const intToChar = new Uint8Array(64); // 64 possible chars.
  1263. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  1264. for (let i = 0; i < chars$1.length; i++) {
  1265. const c = chars$1.charCodeAt(i);
  1266. intToChar[i] = c;
  1267. charToInt[c] = i;
  1268. }
  1269. // Provide a fallback for older environments.
  1270. const td = typeof TextDecoder !== 'undefined'
  1271. ? /* #__PURE__ */ new TextDecoder()
  1272. : typeof Buffer !== 'undefined'
  1273. ? {
  1274. decode(buf) {
  1275. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  1276. return out.toString();
  1277. },
  1278. }
  1279. : {
  1280. decode(buf) {
  1281. let out = '';
  1282. for (let i = 0; i < buf.length; i++) {
  1283. out += String.fromCharCode(buf[i]);
  1284. }
  1285. return out;
  1286. },
  1287. };
  1288. function decode(mappings) {
  1289. const state = new Int32Array(5);
  1290. const decoded = [];
  1291. let index = 0;
  1292. do {
  1293. const semi = indexOf(mappings, index);
  1294. const line = [];
  1295. let sorted = true;
  1296. let lastCol = 0;
  1297. state[0] = 0;
  1298. for (let i = index; i < semi; i++) {
  1299. let seg;
  1300. i = decodeInteger(mappings, i, state, 0); // genColumn
  1301. const col = state[0];
  1302. if (col < lastCol)
  1303. sorted = false;
  1304. lastCol = col;
  1305. if (hasMoreVlq(mappings, i, semi)) {
  1306. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  1307. i = decodeInteger(mappings, i, state, 2); // sourceLine
  1308. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  1309. if (hasMoreVlq(mappings, i, semi)) {
  1310. i = decodeInteger(mappings, i, state, 4); // namesIndex
  1311. seg = [col, state[1], state[2], state[3], state[4]];
  1312. }
  1313. else {
  1314. seg = [col, state[1], state[2], state[3]];
  1315. }
  1316. }
  1317. else {
  1318. seg = [col];
  1319. }
  1320. line.push(seg);
  1321. }
  1322. if (!sorted)
  1323. sort(line);
  1324. decoded.push(line);
  1325. index = semi + 1;
  1326. } while (index <= mappings.length);
  1327. return decoded;
  1328. }
  1329. function indexOf(mappings, index) {
  1330. const idx = mappings.indexOf(';', index);
  1331. return idx === -1 ? mappings.length : idx;
  1332. }
  1333. function decodeInteger(mappings, pos, state, j) {
  1334. let value = 0;
  1335. let shift = 0;
  1336. let integer = 0;
  1337. do {
  1338. const c = mappings.charCodeAt(pos++);
  1339. integer = charToInt[c];
  1340. value |= (integer & 31) << shift;
  1341. shift += 5;
  1342. } while (integer & 32);
  1343. const shouldNegate = value & 1;
  1344. value >>>= 1;
  1345. if (shouldNegate) {
  1346. value = -0x80000000 | -value;
  1347. }
  1348. state[j] += value;
  1349. return pos;
  1350. }
  1351. function hasMoreVlq(mappings, i, length) {
  1352. if (i >= length)
  1353. return false;
  1354. return mappings.charCodeAt(i) !== comma;
  1355. }
  1356. function sort(line) {
  1357. line.sort(sortComparator);
  1358. }
  1359. function sortComparator(a, b) {
  1360. return a[0] - b[0];
  1361. }
  1362. function encode(decoded) {
  1363. const state = new Int32Array(5);
  1364. const bufLength = 1024 * 16;
  1365. const subLength = bufLength - 36;
  1366. const buf = new Uint8Array(bufLength);
  1367. const sub = buf.subarray(0, subLength);
  1368. let pos = 0;
  1369. let out = '';
  1370. for (let i = 0; i < decoded.length; i++) {
  1371. const line = decoded[i];
  1372. if (i > 0) {
  1373. if (pos === bufLength) {
  1374. out += td.decode(buf);
  1375. pos = 0;
  1376. }
  1377. buf[pos++] = semicolon;
  1378. }
  1379. if (line.length === 0)
  1380. continue;
  1381. state[0] = 0;
  1382. for (let j = 0; j < line.length; j++) {
  1383. const segment = line[j];
  1384. // We can push up to 5 ints, each int can take at most 7 chars, and we
  1385. // may push a comma.
  1386. if (pos > subLength) {
  1387. out += td.decode(sub);
  1388. buf.copyWithin(0, subLength, pos);
  1389. pos -= subLength;
  1390. }
  1391. if (j > 0)
  1392. buf[pos++] = comma;
  1393. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  1394. if (segment.length === 1)
  1395. continue;
  1396. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  1397. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  1398. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  1399. if (segment.length === 4)
  1400. continue;
  1401. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  1402. }
  1403. }
  1404. return out + td.decode(buf.subarray(0, pos));
  1405. }
  1406. function encodeInteger(buf, pos, state, segment, j) {
  1407. const next = segment[j];
  1408. let num = next - state[j];
  1409. state[j] = next;
  1410. num = num < 0 ? (-num << 1) | 1 : num << 1;
  1411. do {
  1412. let clamped = num & 0b011111;
  1413. num >>>= 5;
  1414. if (num > 0)
  1415. clamped |= 0b100000;
  1416. buf[pos++] = intToChar[clamped];
  1417. } while (num > 0);
  1418. return pos;
  1419. }
  1420. class BitSet {
  1421. constructor(arg) {
  1422. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  1423. }
  1424. add(n) {
  1425. this.bits[n >> 5] |= 1 << (n & 31);
  1426. }
  1427. has(n) {
  1428. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  1429. }
  1430. }
  1431. let Chunk$1 = class Chunk {
  1432. constructor(start, end, content) {
  1433. this.start = start;
  1434. this.end = end;
  1435. this.original = content;
  1436. this.intro = '';
  1437. this.outro = '';
  1438. this.content = content;
  1439. this.storeName = false;
  1440. this.edited = false;
  1441. {
  1442. this.previous = null;
  1443. this.next = null;
  1444. }
  1445. }
  1446. appendLeft(content) {
  1447. this.outro += content;
  1448. }
  1449. appendRight(content) {
  1450. this.intro = this.intro + content;
  1451. }
  1452. clone() {
  1453. const chunk = new Chunk(this.start, this.end, this.original);
  1454. chunk.intro = this.intro;
  1455. chunk.outro = this.outro;
  1456. chunk.content = this.content;
  1457. chunk.storeName = this.storeName;
  1458. chunk.edited = this.edited;
  1459. return chunk;
  1460. }
  1461. contains(index) {
  1462. return this.start < index && index < this.end;
  1463. }
  1464. eachNext(fn) {
  1465. let chunk = this;
  1466. while (chunk) {
  1467. fn(chunk);
  1468. chunk = chunk.next;
  1469. }
  1470. }
  1471. eachPrevious(fn) {
  1472. let chunk = this;
  1473. while (chunk) {
  1474. fn(chunk);
  1475. chunk = chunk.previous;
  1476. }
  1477. }
  1478. edit(content, storeName, contentOnly) {
  1479. this.content = content;
  1480. if (!contentOnly) {
  1481. this.intro = '';
  1482. this.outro = '';
  1483. }
  1484. this.storeName = storeName;
  1485. this.edited = true;
  1486. return this;
  1487. }
  1488. prependLeft(content) {
  1489. this.outro = content + this.outro;
  1490. }
  1491. prependRight(content) {
  1492. this.intro = content + this.intro;
  1493. }
  1494. split(index) {
  1495. const sliceIndex = index - this.start;
  1496. const originalBefore = this.original.slice(0, sliceIndex);
  1497. const originalAfter = this.original.slice(sliceIndex);
  1498. this.original = originalBefore;
  1499. const newChunk = new Chunk(index, this.end, originalAfter);
  1500. newChunk.outro = this.outro;
  1501. this.outro = '';
  1502. this.end = index;
  1503. if (this.edited) {
  1504. // TODO is this block necessary?...
  1505. newChunk.edit('', false);
  1506. this.content = '';
  1507. } else {
  1508. this.content = originalBefore;
  1509. }
  1510. newChunk.next = this.next;
  1511. if (newChunk.next) newChunk.next.previous = newChunk;
  1512. newChunk.previous = this;
  1513. this.next = newChunk;
  1514. return newChunk;
  1515. }
  1516. toString() {
  1517. return this.intro + this.content + this.outro;
  1518. }
  1519. trimEnd(rx) {
  1520. this.outro = this.outro.replace(rx, '');
  1521. if (this.outro.length) return true;
  1522. const trimmed = this.content.replace(rx, '');
  1523. if (trimmed.length) {
  1524. if (trimmed !== this.content) {
  1525. this.split(this.start + trimmed.length).edit('', undefined, true);
  1526. }
  1527. return true;
  1528. } else {
  1529. this.edit('', undefined, true);
  1530. this.intro = this.intro.replace(rx, '');
  1531. if (this.intro.length) return true;
  1532. }
  1533. }
  1534. trimStart(rx) {
  1535. this.intro = this.intro.replace(rx, '');
  1536. if (this.intro.length) return true;
  1537. const trimmed = this.content.replace(rx, '');
  1538. if (trimmed.length) {
  1539. if (trimmed !== this.content) {
  1540. this.split(this.end - trimmed.length);
  1541. this.edit('', undefined, true);
  1542. }
  1543. return true;
  1544. } else {
  1545. this.edit('', undefined, true);
  1546. this.outro = this.outro.replace(rx, '');
  1547. if (this.outro.length) return true;
  1548. }
  1549. }
  1550. };
  1551. function getBtoa () {
  1552. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  1553. return (str) => window.btoa(unescape(encodeURIComponent(str)));
  1554. } else if (typeof Buffer === 'function') {
  1555. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  1556. } else {
  1557. return () => {
  1558. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  1559. };
  1560. }
  1561. }
  1562. const btoa = /*#__PURE__*/ getBtoa();
  1563. class SourceMap {
  1564. constructor(properties) {
  1565. this.version = 3;
  1566. this.file = properties.file;
  1567. this.sources = properties.sources;
  1568. this.sourcesContent = properties.sourcesContent;
  1569. this.names = properties.names;
  1570. this.mappings = encode(properties.mappings);
  1571. if (typeof properties.x_google_ignoreList !== 'undefined') {
  1572. this.x_google_ignoreList = properties.x_google_ignoreList;
  1573. }
  1574. }
  1575. toString() {
  1576. return JSON.stringify(this);
  1577. }
  1578. toUrl() {
  1579. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  1580. }
  1581. }
  1582. function guessIndent(code) {
  1583. const lines = code.split('\n');
  1584. const tabbed = lines.filter((line) => /^\t+/.test(line));
  1585. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  1586. if (tabbed.length === 0 && spaced.length === 0) {
  1587. return null;
  1588. }
  1589. // More lines tabbed than spaced? Assume tabs, and
  1590. // default to tabs in the case of a tie (or nothing
  1591. // to go on)
  1592. if (tabbed.length >= spaced.length) {
  1593. return '\t';
  1594. }
  1595. // Otherwise, we need to guess the multiple
  1596. const min = spaced.reduce((previous, current) => {
  1597. const numSpaces = /^ +/.exec(current)[0].length;
  1598. return Math.min(numSpaces, previous);
  1599. }, Infinity);
  1600. return new Array(min + 1).join(' ');
  1601. }
  1602. function getRelativePath(from, to) {
  1603. const fromParts = from.split(/[/\\]/);
  1604. const toParts = to.split(/[/\\]/);
  1605. fromParts.pop(); // get dirname
  1606. while (fromParts[0] === toParts[0]) {
  1607. fromParts.shift();
  1608. toParts.shift();
  1609. }
  1610. if (fromParts.length) {
  1611. let i = fromParts.length;
  1612. while (i--) fromParts[i] = '..';
  1613. }
  1614. return fromParts.concat(toParts).join('/');
  1615. }
  1616. const toString$1 = Object.prototype.toString;
  1617. function isObject$1(thing) {
  1618. return toString$1.call(thing) === '[object Object]';
  1619. }
  1620. function getLocator(source) {
  1621. const originalLines = source.split('\n');
  1622. const lineOffsets = [];
  1623. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  1624. lineOffsets.push(pos);
  1625. pos += originalLines[i].length + 1;
  1626. }
  1627. return function locate(index) {
  1628. let i = 0;
  1629. let j = lineOffsets.length;
  1630. while (i < j) {
  1631. const m = (i + j) >> 1;
  1632. if (index < lineOffsets[m]) {
  1633. j = m;
  1634. } else {
  1635. i = m + 1;
  1636. }
  1637. }
  1638. const line = i - 1;
  1639. const column = index - lineOffsets[line];
  1640. return { line, column };
  1641. };
  1642. }
  1643. class Mappings {
  1644. constructor(hires) {
  1645. this.hires = hires;
  1646. this.generatedCodeLine = 0;
  1647. this.generatedCodeColumn = 0;
  1648. this.raw = [];
  1649. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  1650. this.pending = null;
  1651. }
  1652. addEdit(sourceIndex, content, loc, nameIndex) {
  1653. if (content.length) {
  1654. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  1655. if (nameIndex >= 0) {
  1656. segment.push(nameIndex);
  1657. }
  1658. this.rawSegments.push(segment);
  1659. } else if (this.pending) {
  1660. this.rawSegments.push(this.pending);
  1661. }
  1662. this.advance(content);
  1663. this.pending = null;
  1664. }
  1665. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  1666. let originalCharIndex = chunk.start;
  1667. let first = true;
  1668. while (originalCharIndex < chunk.end) {
  1669. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  1670. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  1671. }
  1672. if (original[originalCharIndex] === '\n') {
  1673. loc.line += 1;
  1674. loc.column = 0;
  1675. this.generatedCodeLine += 1;
  1676. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1677. this.generatedCodeColumn = 0;
  1678. first = true;
  1679. } else {
  1680. loc.column += 1;
  1681. this.generatedCodeColumn += 1;
  1682. first = false;
  1683. }
  1684. originalCharIndex += 1;
  1685. }
  1686. this.pending = null;
  1687. }
  1688. advance(str) {
  1689. if (!str) return;
  1690. const lines = str.split('\n');
  1691. if (lines.length > 1) {
  1692. for (let i = 0; i < lines.length - 1; i++) {
  1693. this.generatedCodeLine++;
  1694. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1695. }
  1696. this.generatedCodeColumn = 0;
  1697. }
  1698. this.generatedCodeColumn += lines[lines.length - 1].length;
  1699. }
  1700. }
  1701. const n = '\n';
  1702. const warned = {
  1703. insertLeft: false,
  1704. insertRight: false,
  1705. storeName: false,
  1706. };
  1707. class MagicString {
  1708. constructor(string, options = {}) {
  1709. const chunk = new Chunk$1(0, string.length, string);
  1710. Object.defineProperties(this, {
  1711. original: { writable: true, value: string },
  1712. outro: { writable: true, value: '' },
  1713. intro: { writable: true, value: '' },
  1714. firstChunk: { writable: true, value: chunk },
  1715. lastChunk: { writable: true, value: chunk },
  1716. lastSearchedChunk: { writable: true, value: chunk },
  1717. byStart: { writable: true, value: {} },
  1718. byEnd: { writable: true, value: {} },
  1719. filename: { writable: true, value: options.filename },
  1720. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  1721. sourcemapLocations: { writable: true, value: new BitSet() },
  1722. storedNames: { writable: true, value: {} },
  1723. indentStr: { writable: true, value: undefined },
  1724. ignoreList: { writable: true, value: options.ignoreList },
  1725. });
  1726. this.byStart[0] = chunk;
  1727. this.byEnd[string.length] = chunk;
  1728. }
  1729. addSourcemapLocation(char) {
  1730. this.sourcemapLocations.add(char);
  1731. }
  1732. append(content) {
  1733. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  1734. this.outro += content;
  1735. return this;
  1736. }
  1737. appendLeft(index, content) {
  1738. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1739. this._split(index);
  1740. const chunk = this.byEnd[index];
  1741. if (chunk) {
  1742. chunk.appendLeft(content);
  1743. } else {
  1744. this.intro += content;
  1745. }
  1746. return this;
  1747. }
  1748. appendRight(index, content) {
  1749. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1750. this._split(index);
  1751. const chunk = this.byStart[index];
  1752. if (chunk) {
  1753. chunk.appendRight(content);
  1754. } else {
  1755. this.outro += content;
  1756. }
  1757. return this;
  1758. }
  1759. clone() {
  1760. const cloned = new MagicString(this.original, { filename: this.filename });
  1761. let originalChunk = this.firstChunk;
  1762. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  1763. while (originalChunk) {
  1764. cloned.byStart[clonedChunk.start] = clonedChunk;
  1765. cloned.byEnd[clonedChunk.end] = clonedChunk;
  1766. const nextOriginalChunk = originalChunk.next;
  1767. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  1768. if (nextClonedChunk) {
  1769. clonedChunk.next = nextClonedChunk;
  1770. nextClonedChunk.previous = clonedChunk;
  1771. clonedChunk = nextClonedChunk;
  1772. }
  1773. originalChunk = nextOriginalChunk;
  1774. }
  1775. cloned.lastChunk = clonedChunk;
  1776. if (this.indentExclusionRanges) {
  1777. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  1778. }
  1779. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  1780. cloned.intro = this.intro;
  1781. cloned.outro = this.outro;
  1782. return cloned;
  1783. }
  1784. generateDecodedMap(options) {
  1785. options = options || {};
  1786. const sourceIndex = 0;
  1787. const names = Object.keys(this.storedNames);
  1788. const mappings = new Mappings(options.hires);
  1789. const locate = getLocator(this.original);
  1790. if (this.intro) {
  1791. mappings.advance(this.intro);
  1792. }
  1793. this.firstChunk.eachNext((chunk) => {
  1794. const loc = locate(chunk.start);
  1795. if (chunk.intro.length) mappings.advance(chunk.intro);
  1796. if (chunk.edited) {
  1797. mappings.addEdit(
  1798. sourceIndex,
  1799. chunk.content,
  1800. loc,
  1801. chunk.storeName ? names.indexOf(chunk.original) : -1
  1802. );
  1803. } else {
  1804. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  1805. }
  1806. if (chunk.outro.length) mappings.advance(chunk.outro);
  1807. });
  1808. return {
  1809. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  1810. sources: [options.source ? getRelativePath(options.file || '', options.source) : (options.file || '')],
  1811. sourcesContent: options.includeContent ? [this.original] : undefined,
  1812. names,
  1813. mappings: mappings.raw,
  1814. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined
  1815. };
  1816. }
  1817. generateMap(options) {
  1818. return new SourceMap(this.generateDecodedMap(options));
  1819. }
  1820. _ensureindentStr() {
  1821. if (this.indentStr === undefined) {
  1822. this.indentStr = guessIndent(this.original);
  1823. }
  1824. }
  1825. _getRawIndentString() {
  1826. this._ensureindentStr();
  1827. return this.indentStr;
  1828. }
  1829. getIndentString() {
  1830. this._ensureindentStr();
  1831. return this.indentStr === null ? '\t' : this.indentStr;
  1832. }
  1833. indent(indentStr, options) {
  1834. const pattern = /^[^\r\n]/gm;
  1835. if (isObject$1(indentStr)) {
  1836. options = indentStr;
  1837. indentStr = undefined;
  1838. }
  1839. if (indentStr === undefined) {
  1840. this._ensureindentStr();
  1841. indentStr = this.indentStr || '\t';
  1842. }
  1843. if (indentStr === '') return this; // noop
  1844. options = options || {};
  1845. // Process exclusion ranges
  1846. const isExcluded = {};
  1847. if (options.exclude) {
  1848. const exclusions =
  1849. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  1850. exclusions.forEach((exclusion) => {
  1851. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  1852. isExcluded[i] = true;
  1853. }
  1854. });
  1855. }
  1856. let shouldIndentNextCharacter = options.indentStart !== false;
  1857. const replacer = (match) => {
  1858. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  1859. shouldIndentNextCharacter = true;
  1860. return match;
  1861. };
  1862. this.intro = this.intro.replace(pattern, replacer);
  1863. let charIndex = 0;
  1864. let chunk = this.firstChunk;
  1865. while (chunk) {
  1866. const end = chunk.end;
  1867. if (chunk.edited) {
  1868. if (!isExcluded[charIndex]) {
  1869. chunk.content = chunk.content.replace(pattern, replacer);
  1870. if (chunk.content.length) {
  1871. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  1872. }
  1873. }
  1874. } else {
  1875. charIndex = chunk.start;
  1876. while (charIndex < end) {
  1877. if (!isExcluded[charIndex]) {
  1878. const char = this.original[charIndex];
  1879. if (char === '\n') {
  1880. shouldIndentNextCharacter = true;
  1881. } else if (char !== '\r' && shouldIndentNextCharacter) {
  1882. shouldIndentNextCharacter = false;
  1883. if (charIndex === chunk.start) {
  1884. chunk.prependRight(indentStr);
  1885. } else {
  1886. this._splitChunk(chunk, charIndex);
  1887. chunk = chunk.next;
  1888. chunk.prependRight(indentStr);
  1889. }
  1890. }
  1891. }
  1892. charIndex += 1;
  1893. }
  1894. }
  1895. charIndex = chunk.end;
  1896. chunk = chunk.next;
  1897. }
  1898. this.outro = this.outro.replace(pattern, replacer);
  1899. return this;
  1900. }
  1901. insert() {
  1902. throw new Error(
  1903. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  1904. );
  1905. }
  1906. insertLeft(index, content) {
  1907. if (!warned.insertLeft) {
  1908. console.warn(
  1909. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  1910. ); // eslint-disable-line no-console
  1911. warned.insertLeft = true;
  1912. }
  1913. return this.appendLeft(index, content);
  1914. }
  1915. insertRight(index, content) {
  1916. if (!warned.insertRight) {
  1917. console.warn(
  1918. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  1919. ); // eslint-disable-line no-console
  1920. warned.insertRight = true;
  1921. }
  1922. return this.prependRight(index, content);
  1923. }
  1924. move(start, end, index) {
  1925. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  1926. this._split(start);
  1927. this._split(end);
  1928. this._split(index);
  1929. const first = this.byStart[start];
  1930. const last = this.byEnd[end];
  1931. const oldLeft = first.previous;
  1932. const oldRight = last.next;
  1933. const newRight = this.byStart[index];
  1934. if (!newRight && last === this.lastChunk) return this;
  1935. const newLeft = newRight ? newRight.previous : this.lastChunk;
  1936. if (oldLeft) oldLeft.next = oldRight;
  1937. if (oldRight) oldRight.previous = oldLeft;
  1938. if (newLeft) newLeft.next = first;
  1939. if (newRight) newRight.previous = last;
  1940. if (!first.previous) this.firstChunk = last.next;
  1941. if (!last.next) {
  1942. this.lastChunk = first.previous;
  1943. this.lastChunk.next = null;
  1944. }
  1945. first.previous = newLeft;
  1946. last.next = newRight || null;
  1947. if (!newLeft) this.firstChunk = first;
  1948. if (!newRight) this.lastChunk = last;
  1949. return this;
  1950. }
  1951. overwrite(start, end, content, options) {
  1952. options = options || {};
  1953. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  1954. }
  1955. update(start, end, content, options) {
  1956. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  1957. while (start < 0) start += this.original.length;
  1958. while (end < 0) end += this.original.length;
  1959. if (end > this.original.length) throw new Error('end is out of bounds');
  1960. if (start === end)
  1961. throw new Error(
  1962. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  1963. );
  1964. this._split(start);
  1965. this._split(end);
  1966. if (options === true) {
  1967. if (!warned.storeName) {
  1968. console.warn(
  1969. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  1970. ); // eslint-disable-line no-console
  1971. warned.storeName = true;
  1972. }
  1973. options = { storeName: true };
  1974. }
  1975. const storeName = options !== undefined ? options.storeName : false;
  1976. const overwrite = options !== undefined ? options.overwrite : false;
  1977. if (storeName) {
  1978. const original = this.original.slice(start, end);
  1979. Object.defineProperty(this.storedNames, original, {
  1980. writable: true,
  1981. value: true,
  1982. enumerable: true,
  1983. });
  1984. }
  1985. const first = this.byStart[start];
  1986. const last = this.byEnd[end];
  1987. if (first) {
  1988. let chunk = first;
  1989. while (chunk !== last) {
  1990. if (chunk.next !== this.byStart[chunk.end]) {
  1991. throw new Error('Cannot overwrite across a split point');
  1992. }
  1993. chunk = chunk.next;
  1994. chunk.edit('', false);
  1995. }
  1996. first.edit(content, storeName, !overwrite);
  1997. } else {
  1998. // must be inserting at the end
  1999. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  2000. // TODO last chunk in the array may not be the last chunk, if it's moved...
  2001. last.next = newChunk;
  2002. newChunk.previous = last;
  2003. }
  2004. return this;
  2005. }
  2006. prepend(content) {
  2007. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  2008. this.intro = content + this.intro;
  2009. return this;
  2010. }
  2011. prependLeft(index, content) {
  2012. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2013. this._split(index);
  2014. const chunk = this.byEnd[index];
  2015. if (chunk) {
  2016. chunk.prependLeft(content);
  2017. } else {
  2018. this.intro = content + this.intro;
  2019. }
  2020. return this;
  2021. }
  2022. prependRight(index, content) {
  2023. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2024. this._split(index);
  2025. const chunk = this.byStart[index];
  2026. if (chunk) {
  2027. chunk.prependRight(content);
  2028. } else {
  2029. this.outro = content + this.outro;
  2030. }
  2031. return this;
  2032. }
  2033. remove(start, end) {
  2034. while (start < 0) start += this.original.length;
  2035. while (end < 0) end += this.original.length;
  2036. if (start === end) return this;
  2037. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  2038. if (start > end) throw new Error('end must be greater than start');
  2039. this._split(start);
  2040. this._split(end);
  2041. let chunk = this.byStart[start];
  2042. while (chunk) {
  2043. chunk.intro = '';
  2044. chunk.outro = '';
  2045. chunk.edit('');
  2046. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  2047. }
  2048. return this;
  2049. }
  2050. lastChar() {
  2051. if (this.outro.length) return this.outro[this.outro.length - 1];
  2052. let chunk = this.lastChunk;
  2053. do {
  2054. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  2055. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  2056. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  2057. } while ((chunk = chunk.previous));
  2058. if (this.intro.length) return this.intro[this.intro.length - 1];
  2059. return '';
  2060. }
  2061. lastLine() {
  2062. let lineIndex = this.outro.lastIndexOf(n);
  2063. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  2064. let lineStr = this.outro;
  2065. let chunk = this.lastChunk;
  2066. do {
  2067. if (chunk.outro.length > 0) {
  2068. lineIndex = chunk.outro.lastIndexOf(n);
  2069. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  2070. lineStr = chunk.outro + lineStr;
  2071. }
  2072. if (chunk.content.length > 0) {
  2073. lineIndex = chunk.content.lastIndexOf(n);
  2074. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  2075. lineStr = chunk.content + lineStr;
  2076. }
  2077. if (chunk.intro.length > 0) {
  2078. lineIndex = chunk.intro.lastIndexOf(n);
  2079. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  2080. lineStr = chunk.intro + lineStr;
  2081. }
  2082. } while ((chunk = chunk.previous));
  2083. lineIndex = this.intro.lastIndexOf(n);
  2084. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  2085. return this.intro + lineStr;
  2086. }
  2087. slice(start = 0, end = this.original.length) {
  2088. while (start < 0) start += this.original.length;
  2089. while (end < 0) end += this.original.length;
  2090. let result = '';
  2091. // find start chunk
  2092. let chunk = this.firstChunk;
  2093. while (chunk && (chunk.start > start || chunk.end <= start)) {
  2094. // found end chunk before start
  2095. if (chunk.start < end && chunk.end >= end) {
  2096. return result;
  2097. }
  2098. chunk = chunk.next;
  2099. }
  2100. if (chunk && chunk.edited && chunk.start !== start)
  2101. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  2102. const startChunk = chunk;
  2103. while (chunk) {
  2104. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  2105. result += chunk.intro;
  2106. }
  2107. const containsEnd = chunk.start < end && chunk.end >= end;
  2108. if (containsEnd && chunk.edited && chunk.end !== end)
  2109. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  2110. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  2111. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  2112. result += chunk.content.slice(sliceStart, sliceEnd);
  2113. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  2114. result += chunk.outro;
  2115. }
  2116. if (containsEnd) {
  2117. break;
  2118. }
  2119. chunk = chunk.next;
  2120. }
  2121. return result;
  2122. }
  2123. // TODO deprecate this? not really very useful
  2124. snip(start, end) {
  2125. const clone = this.clone();
  2126. clone.remove(0, start);
  2127. clone.remove(end, clone.original.length);
  2128. return clone;
  2129. }
  2130. _split(index) {
  2131. if (this.byStart[index] || this.byEnd[index]) return;
  2132. let chunk = this.lastSearchedChunk;
  2133. const searchForward = index > chunk.end;
  2134. while (chunk) {
  2135. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  2136. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  2137. }
  2138. }
  2139. _splitChunk(chunk, index) {
  2140. if (chunk.edited && chunk.content.length) {
  2141. // zero-length edited chunks are a special case (overlapping replacements)
  2142. const loc = getLocator(this.original)(index);
  2143. throw new Error(
  2144. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
  2145. );
  2146. }
  2147. const newChunk = chunk.split(index);
  2148. this.byEnd[index] = chunk;
  2149. this.byStart[index] = newChunk;
  2150. this.byEnd[newChunk.end] = newChunk;
  2151. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  2152. this.lastSearchedChunk = chunk;
  2153. return true;
  2154. }
  2155. toString() {
  2156. let str = this.intro;
  2157. let chunk = this.firstChunk;
  2158. while (chunk) {
  2159. str += chunk.toString();
  2160. chunk = chunk.next;
  2161. }
  2162. return str + this.outro;
  2163. }
  2164. isEmpty() {
  2165. let chunk = this.firstChunk;
  2166. do {
  2167. if (
  2168. (chunk.intro.length && chunk.intro.trim()) ||
  2169. (chunk.content.length && chunk.content.trim()) ||
  2170. (chunk.outro.length && chunk.outro.trim())
  2171. )
  2172. return false;
  2173. } while ((chunk = chunk.next));
  2174. return true;
  2175. }
  2176. length() {
  2177. let chunk = this.firstChunk;
  2178. let length = 0;
  2179. do {
  2180. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  2181. } while ((chunk = chunk.next));
  2182. return length;
  2183. }
  2184. trimLines() {
  2185. return this.trim('[\\r\\n]');
  2186. }
  2187. trim(charType) {
  2188. return this.trimStart(charType).trimEnd(charType);
  2189. }
  2190. trimEndAborted(charType) {
  2191. const rx = new RegExp((charType || '\\s') + '+$');
  2192. this.outro = this.outro.replace(rx, '');
  2193. if (this.outro.length) return true;
  2194. let chunk = this.lastChunk;
  2195. do {
  2196. const end = chunk.end;
  2197. const aborted = chunk.trimEnd(rx);
  2198. // if chunk was trimmed, we have a new lastChunk
  2199. if (chunk.end !== end) {
  2200. if (this.lastChunk === chunk) {
  2201. this.lastChunk = chunk.next;
  2202. }
  2203. this.byEnd[chunk.end] = chunk;
  2204. this.byStart[chunk.next.start] = chunk.next;
  2205. this.byEnd[chunk.next.end] = chunk.next;
  2206. }
  2207. if (aborted) return true;
  2208. chunk = chunk.previous;
  2209. } while (chunk);
  2210. return false;
  2211. }
  2212. trimEnd(charType) {
  2213. this.trimEndAborted(charType);
  2214. return this;
  2215. }
  2216. trimStartAborted(charType) {
  2217. const rx = new RegExp('^' + (charType || '\\s') + '+');
  2218. this.intro = this.intro.replace(rx, '');
  2219. if (this.intro.length) return true;
  2220. let chunk = this.firstChunk;
  2221. do {
  2222. const end = chunk.end;
  2223. const aborted = chunk.trimStart(rx);
  2224. if (chunk.end !== end) {
  2225. // special case...
  2226. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  2227. this.byEnd[chunk.end] = chunk;
  2228. this.byStart[chunk.next.start] = chunk.next;
  2229. this.byEnd[chunk.next.end] = chunk.next;
  2230. }
  2231. if (aborted) return true;
  2232. chunk = chunk.next;
  2233. } while (chunk);
  2234. return false;
  2235. }
  2236. trimStart(charType) {
  2237. this.trimStartAborted(charType);
  2238. return this;
  2239. }
  2240. hasChanged() {
  2241. return this.original !== this.toString();
  2242. }
  2243. _replaceRegexp(searchValue, replacement) {
  2244. function getReplacement(match, str) {
  2245. if (typeof replacement === 'string') {
  2246. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  2247. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  2248. if (i === '$') return '$';
  2249. if (i === '&') return match[0];
  2250. const num = +i;
  2251. if (num < match.length) return match[+i];
  2252. return `$${i}`;
  2253. });
  2254. } else {
  2255. return replacement(...match, match.index, str, match.groups);
  2256. }
  2257. }
  2258. function matchAll(re, str) {
  2259. let match;
  2260. const matches = [];
  2261. while ((match = re.exec(str))) {
  2262. matches.push(match);
  2263. }
  2264. return matches;
  2265. }
  2266. if (searchValue.global) {
  2267. const matches = matchAll(searchValue, this.original);
  2268. matches.forEach((match) => {
  2269. if (match.index != null)
  2270. this.overwrite(
  2271. match.index,
  2272. match.index + match[0].length,
  2273. getReplacement(match, this.original)
  2274. );
  2275. });
  2276. } else {
  2277. const match = this.original.match(searchValue);
  2278. if (match && match.index != null)
  2279. this.overwrite(
  2280. match.index,
  2281. match.index + match[0].length,
  2282. getReplacement(match, this.original)
  2283. );
  2284. }
  2285. return this;
  2286. }
  2287. _replaceString(string, replacement) {
  2288. const { original } = this;
  2289. const index = original.indexOf(string);
  2290. if (index !== -1) {
  2291. this.overwrite(index, index + string.length, replacement);
  2292. }
  2293. return this;
  2294. }
  2295. replace(searchValue, replacement) {
  2296. if (typeof searchValue === 'string') {
  2297. return this._replaceString(searchValue, replacement);
  2298. }
  2299. return this._replaceRegexp(searchValue, replacement);
  2300. }
  2301. _replaceAllString(string, replacement) {
  2302. const { original } = this;
  2303. const stringLength = string.length;
  2304. for (
  2305. let index = original.indexOf(string);
  2306. index !== -1;
  2307. index = original.indexOf(string, index + stringLength)
  2308. ) {
  2309. this.overwrite(index, index + stringLength, replacement);
  2310. }
  2311. return this;
  2312. }
  2313. replaceAll(searchValue, replacement) {
  2314. if (typeof searchValue === 'string') {
  2315. return this._replaceAllString(searchValue, replacement);
  2316. }
  2317. if (!searchValue.global) {
  2318. throw new TypeError(
  2319. 'MagicString.prototype.replaceAll called with a non-global RegExp argument'
  2320. );
  2321. }
  2322. return this._replaceRegexp(searchValue, replacement);
  2323. }
  2324. }
  2325. const hasOwnProp = Object.prototype.hasOwnProperty;
  2326. let Bundle$1 = class Bundle {
  2327. constructor(options = {}) {
  2328. this.intro = options.intro || '';
  2329. this.separator = options.separator !== undefined ? options.separator : '\n';
  2330. this.sources = [];
  2331. this.uniqueSources = [];
  2332. this.uniqueSourceIndexByFilename = {};
  2333. }
  2334. addSource(source) {
  2335. if (source instanceof MagicString) {
  2336. return this.addSource({
  2337. content: source,
  2338. filename: source.filename,
  2339. separator: this.separator,
  2340. });
  2341. }
  2342. if (!isObject$1(source) || !source.content) {
  2343. throw new Error(
  2344. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'
  2345. );
  2346. }
  2347. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  2348. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  2349. });
  2350. if (source.separator === undefined) {
  2351. // TODO there's a bunch of this sort of thing, needs cleaning up
  2352. source.separator = this.separator;
  2353. }
  2354. if (source.filename) {
  2355. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  2356. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  2357. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  2358. } else {
  2359. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  2360. if (source.content.original !== uniqueSource.content) {
  2361. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  2362. }
  2363. }
  2364. }
  2365. this.sources.push(source);
  2366. return this;
  2367. }
  2368. append(str, options) {
  2369. this.addSource({
  2370. content: new MagicString(str),
  2371. separator: (options && options.separator) || '',
  2372. });
  2373. return this;
  2374. }
  2375. clone() {
  2376. const bundle = new Bundle({
  2377. intro: this.intro,
  2378. separator: this.separator,
  2379. });
  2380. this.sources.forEach((source) => {
  2381. bundle.addSource({
  2382. filename: source.filename,
  2383. content: source.content.clone(),
  2384. separator: source.separator,
  2385. });
  2386. });
  2387. return bundle;
  2388. }
  2389. generateDecodedMap(options = {}) {
  2390. const names = [];
  2391. let x_google_ignoreList = undefined;
  2392. this.sources.forEach((source) => {
  2393. Object.keys(source.content.storedNames).forEach((name) => {
  2394. if (!~names.indexOf(name)) names.push(name);
  2395. });
  2396. });
  2397. const mappings = new Mappings(options.hires);
  2398. if (this.intro) {
  2399. mappings.advance(this.intro);
  2400. }
  2401. this.sources.forEach((source, i) => {
  2402. if (i > 0) {
  2403. mappings.advance(this.separator);
  2404. }
  2405. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  2406. const magicString = source.content;
  2407. const locate = getLocator(magicString.original);
  2408. if (magicString.intro) {
  2409. mappings.advance(magicString.intro);
  2410. }
  2411. magicString.firstChunk.eachNext((chunk) => {
  2412. const loc = locate(chunk.start);
  2413. if (chunk.intro.length) mappings.advance(chunk.intro);
  2414. if (source.filename) {
  2415. if (chunk.edited) {
  2416. mappings.addEdit(
  2417. sourceIndex,
  2418. chunk.content,
  2419. loc,
  2420. chunk.storeName ? names.indexOf(chunk.original) : -1
  2421. );
  2422. } else {
  2423. mappings.addUneditedChunk(
  2424. sourceIndex,
  2425. chunk,
  2426. magicString.original,
  2427. loc,
  2428. magicString.sourcemapLocations
  2429. );
  2430. }
  2431. } else {
  2432. mappings.advance(chunk.content);
  2433. }
  2434. if (chunk.outro.length) mappings.advance(chunk.outro);
  2435. });
  2436. if (magicString.outro) {
  2437. mappings.advance(magicString.outro);
  2438. }
  2439. if (source.ignoreList && sourceIndex !== -1) {
  2440. if (x_google_ignoreList === undefined) {
  2441. x_google_ignoreList = [];
  2442. }
  2443. x_google_ignoreList.push(sourceIndex);
  2444. }
  2445. });
  2446. return {
  2447. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  2448. sources: this.uniqueSources.map((source) => {
  2449. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  2450. }),
  2451. sourcesContent: this.uniqueSources.map((source) => {
  2452. return options.includeContent ? source.content : null;
  2453. }),
  2454. names,
  2455. mappings: mappings.raw,
  2456. x_google_ignoreList,
  2457. };
  2458. }
  2459. generateMap(options) {
  2460. return new SourceMap(this.generateDecodedMap(options));
  2461. }
  2462. getIndentString() {
  2463. const indentStringCounts = {};
  2464. this.sources.forEach((source) => {
  2465. const indentStr = source.content._getRawIndentString();
  2466. if (indentStr === null) return;
  2467. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  2468. indentStringCounts[indentStr] += 1;
  2469. });
  2470. return (
  2471. Object.keys(indentStringCounts).sort((a, b) => {
  2472. return indentStringCounts[a] - indentStringCounts[b];
  2473. })[0] || '\t'
  2474. );
  2475. }
  2476. indent(indentStr) {
  2477. if (!arguments.length) {
  2478. indentStr = this.getIndentString();
  2479. }
  2480. if (indentStr === '') return this; // noop
  2481. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  2482. this.sources.forEach((source, i) => {
  2483. const separator = source.separator !== undefined ? source.separator : this.separator;
  2484. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  2485. source.content.indent(indentStr, {
  2486. exclude: source.indentExclusionRanges,
  2487. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  2488. });
  2489. trailingNewline = source.content.lastChar() === '\n';
  2490. });
  2491. if (this.intro) {
  2492. this.intro =
  2493. indentStr +
  2494. this.intro.replace(/^[^\n]/gm, (match, index) => {
  2495. return index > 0 ? indentStr + match : match;
  2496. });
  2497. }
  2498. return this;
  2499. }
  2500. prepend(str) {
  2501. this.intro = str + this.intro;
  2502. return this;
  2503. }
  2504. toString() {
  2505. const body = this.sources
  2506. .map((source, i) => {
  2507. const separator = source.separator !== undefined ? source.separator : this.separator;
  2508. const str = (i > 0 ? separator : '') + source.content.toString();
  2509. return str;
  2510. })
  2511. .join('');
  2512. return this.intro + body;
  2513. }
  2514. isEmpty() {
  2515. if (this.intro.length && this.intro.trim()) return false;
  2516. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  2517. return true;
  2518. }
  2519. length() {
  2520. return this.sources.reduce(
  2521. (length, source) => length + source.content.length(),
  2522. this.intro.length
  2523. );
  2524. }
  2525. trimLines() {
  2526. return this.trim('[\\r\\n]');
  2527. }
  2528. trim(charType) {
  2529. return this.trimStart(charType).trimEnd(charType);
  2530. }
  2531. trimStart(charType) {
  2532. const rx = new RegExp('^' + (charType || '\\s') + '+');
  2533. this.intro = this.intro.replace(rx, '');
  2534. if (!this.intro) {
  2535. let source;
  2536. let i = 0;
  2537. do {
  2538. source = this.sources[i++];
  2539. if (!source) {
  2540. break;
  2541. }
  2542. } while (!source.content.trimStartAborted(charType));
  2543. }
  2544. return this;
  2545. }
  2546. trimEnd(charType) {
  2547. const rx = new RegExp((charType || '\\s') + '+$');
  2548. let source;
  2549. let i = this.sources.length - 1;
  2550. do {
  2551. source = this.sources[i--];
  2552. if (!source) {
  2553. this.intro = this.intro.replace(rx, '');
  2554. break;
  2555. }
  2556. } while (!source.content.trimEndAborted(charType));
  2557. return this;
  2558. }
  2559. };
  2560. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  2561. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  2562. const backSlashRegEx = /\\/g;
  2563. function escapeId(id) {
  2564. if (!needsEscapeRegEx.test(id))
  2565. return id;
  2566. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  2567. }
  2568. class ExternalChunk {
  2569. constructor(module, options, inputBase) {
  2570. this.options = options;
  2571. this.inputBase = inputBase;
  2572. this.defaultVariableName = '';
  2573. this.namespaceVariableName = '';
  2574. this.variableName = '';
  2575. this.fileName = null;
  2576. this.importAssertions = null;
  2577. this.id = module.id;
  2578. this.moduleInfo = module.info;
  2579. this.renormalizeRenderPath = module.renormalizeRenderPath;
  2580. this.suggestedVariableName = module.suggestedVariableName;
  2581. }
  2582. getFileName() {
  2583. if (this.fileName) {
  2584. return this.fileName;
  2585. }
  2586. const { paths } = this.options;
  2587. return (this.fileName =
  2588. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  2589. (this.renormalizeRenderPath ? normalize(node_path.relative(this.inputBase, this.id)) : this.id));
  2590. }
  2591. getImportAssertions(snippets) {
  2592. return (this.importAssertions || (this.importAssertions = formatAssertions(this.options.format === 'es' &&
  2593. this.options.externalImportAssertions &&
  2594. this.moduleInfo.assertions, snippets)));
  2595. }
  2596. getImportPath(importer) {
  2597. return escapeId(this.renormalizeRenderPath
  2598. ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  2599. : this.getFileName());
  2600. }
  2601. }
  2602. function formatAssertions(assertions, { getObject }) {
  2603. if (!assertions) {
  2604. return null;
  2605. }
  2606. const assertionEntries = Object.entries(assertions).map(([key, value]) => [key, `'${value}'`]);
  2607. if (assertionEntries.length > 0) {
  2608. return getObject(assertionEntries, { lineBreakIndent: null });
  2609. }
  2610. return null;
  2611. }
  2612. function getOrCreate(map, key, init) {
  2613. const existing = map.get(key);
  2614. if (existing !== undefined) {
  2615. return existing;
  2616. }
  2617. const value = init();
  2618. map.set(key, value);
  2619. return value;
  2620. }
  2621. function getNewSet() {
  2622. return new Set();
  2623. }
  2624. function getNewArray() {
  2625. return [];
  2626. }
  2627. const UnknownKey = Symbol('Unknown Key');
  2628. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  2629. const UnknownInteger = Symbol('Unknown Integer');
  2630. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  2631. const EMPTY_PATH = [];
  2632. const UNKNOWN_PATH = [UnknownKey];
  2633. // For deoptimizations, this means we are modifying an unknown property but did
  2634. // not lose track of the object or are creating a setter/getter;
  2635. // For assignment effects it means we do not check for setter/getter effects
  2636. // but only if something is mutated that is included, which is relevant for
  2637. // Object.defineProperty
  2638. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  2639. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  2640. const EntitiesKey = Symbol('Entities');
  2641. class PathTracker {
  2642. constructor() {
  2643. this.entityPaths = Object.create(null, {
  2644. [EntitiesKey]: { value: new Set() }
  2645. });
  2646. }
  2647. trackEntityAtPathAndGetIfTracked(path, entity) {
  2648. const trackedEntities = this.getEntities(path);
  2649. if (trackedEntities.has(entity))
  2650. return true;
  2651. trackedEntities.add(entity);
  2652. return false;
  2653. }
  2654. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  2655. const trackedEntities = this.getEntities(path);
  2656. if (trackedEntities.has(entity))
  2657. return returnIfTracked;
  2658. trackedEntities.add(entity);
  2659. const result = onUntracked();
  2660. trackedEntities.delete(entity);
  2661. return result;
  2662. }
  2663. getEntities(path) {
  2664. let currentPaths = this.entityPaths;
  2665. for (const pathSegment of path) {
  2666. currentPaths = currentPaths[pathSegment] =
  2667. currentPaths[pathSegment] ||
  2668. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  2669. }
  2670. return currentPaths[EntitiesKey];
  2671. }
  2672. }
  2673. const SHARED_RECURSION_TRACKER = new PathTracker();
  2674. class DiscriminatedPathTracker {
  2675. constructor() {
  2676. this.entityPaths = Object.create(null, {
  2677. [EntitiesKey]: { value: new Map() }
  2678. });
  2679. }
  2680. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  2681. let currentPaths = this.entityPaths;
  2682. for (const pathSegment of path) {
  2683. currentPaths = currentPaths[pathSegment] =
  2684. currentPaths[pathSegment] ||
  2685. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  2686. }
  2687. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  2688. if (trackedEntities.has(entity))
  2689. return true;
  2690. trackedEntities.add(entity);
  2691. return false;
  2692. }
  2693. }
  2694. const UnknownValue = Symbol('Unknown Value');
  2695. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  2696. class ExpressionEntity {
  2697. constructor() {
  2698. this.included = false;
  2699. }
  2700. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  2701. deoptimizeInteraction(interaction);
  2702. }
  2703. deoptimizePath(_path) { }
  2704. /**
  2705. * If possible it returns a stringifyable literal value for this node that
  2706. * can be used for inlining or comparing values. Otherwise, it should return
  2707. * UnknownValue.
  2708. */
  2709. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  2710. return UnknownValue;
  2711. }
  2712. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  2713. return UNKNOWN_RETURN_EXPRESSION;
  2714. }
  2715. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  2716. return true;
  2717. }
  2718. include(_context, _includeChildrenRecursively, _options) {
  2719. this.included = true;
  2720. }
  2721. includeCallArguments(context, parameters) {
  2722. for (const argument of parameters) {
  2723. argument.include(context, false);
  2724. }
  2725. }
  2726. shouldBeIncluded(_context) {
  2727. return true;
  2728. }
  2729. }
  2730. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  2731. })();
  2732. const UNKNOWN_RETURN_EXPRESSION = [
  2733. UNKNOWN_EXPRESSION,
  2734. false
  2735. ];
  2736. const deoptimizeInteraction = (interaction) => {
  2737. for (const argument of interaction.args) {
  2738. argument?.deoptimizePath(UNKNOWN_PATH);
  2739. }
  2740. };
  2741. const INTERACTION_ACCESSED = 0;
  2742. const INTERACTION_ASSIGNED = 1;
  2743. const INTERACTION_CALLED = 2;
  2744. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  2745. args: [null],
  2746. type: INTERACTION_ACCESSED
  2747. };
  2748. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  2749. args: [null, UNKNOWN_EXPRESSION],
  2750. type: INTERACTION_ASSIGNED
  2751. };
  2752. // While this is technically a call without arguments, we can compare against
  2753. // this reference in places where precise values or this argument would make a
  2754. // difference
  2755. const NODE_INTERACTION_UNKNOWN_CALL = {
  2756. args: [null],
  2757. type: INTERACTION_CALLED,
  2758. withNew: false
  2759. };
  2760. class Variable extends ExpressionEntity {
  2761. constructor(name) {
  2762. super();
  2763. this.name = name;
  2764. this.alwaysRendered = false;
  2765. this.forbiddenNames = null;
  2766. this.initReached = false;
  2767. this.isId = false;
  2768. this.isReassigned = false;
  2769. this.kind = null;
  2770. this.renderBaseName = null;
  2771. this.renderName = null;
  2772. }
  2773. /**
  2774. * Binds identifiers that reference this variable to this variable.
  2775. * Necessary to be able to change variable names.
  2776. */
  2777. addReference(_identifier) { }
  2778. /**
  2779. * Prevent this variable from being renamed to this name to avoid name
  2780. * collisions
  2781. */
  2782. forbidName(name) {
  2783. (this.forbiddenNames || (this.forbiddenNames = new Set())).add(name);
  2784. }
  2785. getBaseVariableName() {
  2786. return this.renderBaseName || this.renderName || this.name;
  2787. }
  2788. getName(getPropertyAccess, useOriginalName) {
  2789. if (useOriginalName?.(this)) {
  2790. return this.name;
  2791. }
  2792. const name = this.renderName || this.name;
  2793. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  2794. }
  2795. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  2796. return type !== INTERACTION_ACCESSED || path.length > 0;
  2797. }
  2798. /**
  2799. * Marks this variable as being part of the bundle, which is usually the case when one of
  2800. * its identifiers becomes part of the bundle. Returns true if it has not been included
  2801. * previously.
  2802. * Once a variable is included, it should take care all its declarations are included.
  2803. */
  2804. include() {
  2805. this.included = true;
  2806. }
  2807. markCalledFromTryStatement() { }
  2808. setRenderNames(baseName, name) {
  2809. this.renderBaseName = baseName;
  2810. this.renderName = name;
  2811. }
  2812. }
  2813. class ExternalVariable extends Variable {
  2814. constructor(module, name) {
  2815. super(name);
  2816. this.referenced = false;
  2817. this.module = module;
  2818. this.isNamespace = name === '*';
  2819. }
  2820. addReference(identifier) {
  2821. this.referenced = true;
  2822. if (this.name === 'default' || this.name === '*') {
  2823. this.module.suggestName(identifier.name);
  2824. }
  2825. }
  2826. hasEffectsOnInteractionAtPath(path, { type }) {
  2827. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  2828. }
  2829. include() {
  2830. if (!this.included) {
  2831. this.included = true;
  2832. this.module.used = true;
  2833. }
  2834. }
  2835. }
  2836. const RESERVED_NAMES = new Set([
  2837. 'await',
  2838. 'break',
  2839. 'case',
  2840. 'catch',
  2841. 'class',
  2842. 'const',
  2843. 'continue',
  2844. 'debugger',
  2845. 'default',
  2846. 'delete',
  2847. 'do',
  2848. 'else',
  2849. 'enum',
  2850. 'eval',
  2851. 'export',
  2852. 'extends',
  2853. 'false',
  2854. 'finally',
  2855. 'for',
  2856. 'function',
  2857. 'if',
  2858. 'implements',
  2859. 'import',
  2860. 'in',
  2861. 'instanceof',
  2862. 'interface',
  2863. 'let',
  2864. 'NaN',
  2865. 'new',
  2866. 'null',
  2867. 'package',
  2868. 'private',
  2869. 'protected',
  2870. 'public',
  2871. 'return',
  2872. 'static',
  2873. 'super',
  2874. 'switch',
  2875. 'this',
  2876. 'throw',
  2877. 'true',
  2878. 'try',
  2879. 'typeof',
  2880. 'undefined',
  2881. 'var',
  2882. 'void',
  2883. 'while',
  2884. 'with',
  2885. 'yield'
  2886. ]);
  2887. const RESERVED_NAMES$1 = RESERVED_NAMES;
  2888. const illegalCharacters = /[^\w$]/g;
  2889. const startsWithDigit = (value) => /\d/.test(value[0]);
  2890. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES$1.has(value) || value === 'arguments';
  2891. function isLegal(value) {
  2892. if (needsEscape(value)) {
  2893. return false;
  2894. }
  2895. return !illegalCharacters.test(value);
  2896. }
  2897. function makeLegal(value) {
  2898. value = value
  2899. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  2900. .replace(illegalCharacters, '_');
  2901. if (needsEscape(value))
  2902. value = `_${value}`;
  2903. return value || '_';
  2904. }
  2905. class ExternalModule {
  2906. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, assertions) {
  2907. this.options = options;
  2908. this.id = id;
  2909. this.renormalizeRenderPath = renormalizeRenderPath;
  2910. this.dynamicImporters = [];
  2911. this.execIndex = Infinity;
  2912. this.exportedVariables = new Map();
  2913. this.importers = [];
  2914. this.reexported = false;
  2915. this.used = false;
  2916. this.declarations = new Map();
  2917. this.mostCommonSuggestion = 0;
  2918. this.nameSuggestions = new Map();
  2919. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  2920. const { importers, dynamicImporters } = this;
  2921. const info = (this.info = {
  2922. assertions,
  2923. ast: null,
  2924. code: null,
  2925. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2926. dynamicallyImportedIds: EMPTY_ARRAY,
  2927. get dynamicImporters() {
  2928. return dynamicImporters.sort();
  2929. },
  2930. exportedBindings: null,
  2931. exports: null,
  2932. hasDefaultExport: null,
  2933. get hasModuleSideEffects() {
  2934. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options);
  2935. return info.moduleSideEffects;
  2936. },
  2937. id,
  2938. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2939. implicitlyLoadedBefore: EMPTY_ARRAY,
  2940. importedIdResolutions: EMPTY_ARRAY,
  2941. importedIds: EMPTY_ARRAY,
  2942. get importers() {
  2943. return importers.sort();
  2944. },
  2945. isEntry: false,
  2946. isExternal: true,
  2947. isIncluded: null,
  2948. meta,
  2949. moduleSideEffects,
  2950. syntheticNamedExports: false
  2951. });
  2952. // Hide the deprecated key so that it only warns when accessed explicitly
  2953. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  2954. enumerable: false
  2955. });
  2956. }
  2957. getVariableForExportName(name) {
  2958. const declaration = this.declarations.get(name);
  2959. if (declaration)
  2960. return [declaration];
  2961. const externalVariable = new ExternalVariable(this, name);
  2962. this.declarations.set(name, externalVariable);
  2963. this.exportedVariables.set(externalVariable, name);
  2964. return [externalVariable];
  2965. }
  2966. suggestName(name) {
  2967. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  2968. this.nameSuggestions.set(name, value);
  2969. if (value > this.mostCommonSuggestion) {
  2970. this.mostCommonSuggestion = value;
  2971. this.suggestedVariableName = name;
  2972. }
  2973. }
  2974. warnUnusedImports() {
  2975. const unused = [...this.declarations]
  2976. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2977. .map(([name]) => name);
  2978. if (unused.length === 0)
  2979. return;
  2980. const importersSet = new Set();
  2981. for (const name of unused) {
  2982. for (const importer of this.declarations.get(name).module.importers) {
  2983. importersSet.add(importer);
  2984. }
  2985. }
  2986. const importersArray = [...importersSet];
  2987. this.options.onwarn(errorUnusedExternalImports(this.id, unused, importersArray));
  2988. }
  2989. }
  2990. function getDefaultExportFromCjs (x) {
  2991. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2992. }
  2993. function getAugmentedNamespace(n) {
  2994. if (n.__esModule) return n;
  2995. var f = n.default;
  2996. if (typeof f == "function") {
  2997. var a = function a () {
  2998. if (this instanceof a) {
  2999. var args = [null];
  3000. args.push.apply(args, arguments);
  3001. var Ctor = Function.bind.apply(f, args);
  3002. return new Ctor();
  3003. }
  3004. return f.apply(this, arguments);
  3005. };
  3006. a.prototype = f.prototype;
  3007. } else a = {};
  3008. Object.defineProperty(a, '__esModule', {value: true});
  3009. Object.keys(n).forEach(function (k) {
  3010. var d = Object.getOwnPropertyDescriptor(n, k);
  3011. Object.defineProperty(a, k, d.get ? d : {
  3012. enumerable: true,
  3013. get: function () {
  3014. return n[k];
  3015. }
  3016. });
  3017. });
  3018. return a;
  3019. }
  3020. var utils$3 = {};
  3021. const path$1 = require$$0$1;
  3022. const WIN_SLASH = '\\\\/';
  3023. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  3024. /**
  3025. * Posix glob regex
  3026. */
  3027. const DOT_LITERAL = '\\.';
  3028. const PLUS_LITERAL = '\\+';
  3029. const QMARK_LITERAL = '\\?';
  3030. const SLASH_LITERAL = '\\/';
  3031. const ONE_CHAR = '(?=.)';
  3032. const QMARK = '[^/]';
  3033. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  3034. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  3035. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  3036. const NO_DOT = `(?!${DOT_LITERAL})`;
  3037. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  3038. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  3039. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  3040. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  3041. const STAR = `${QMARK}*?`;
  3042. const POSIX_CHARS = {
  3043. DOT_LITERAL,
  3044. PLUS_LITERAL,
  3045. QMARK_LITERAL,
  3046. SLASH_LITERAL,
  3047. ONE_CHAR,
  3048. QMARK,
  3049. END_ANCHOR,
  3050. DOTS_SLASH,
  3051. NO_DOT,
  3052. NO_DOTS,
  3053. NO_DOT_SLASH,
  3054. NO_DOTS_SLASH,
  3055. QMARK_NO_DOT,
  3056. STAR,
  3057. START_ANCHOR
  3058. };
  3059. /**
  3060. * Windows glob regex
  3061. */
  3062. const WINDOWS_CHARS = {
  3063. ...POSIX_CHARS,
  3064. SLASH_LITERAL: `[${WIN_SLASH}]`,
  3065. QMARK: WIN_NO_SLASH,
  3066. STAR: `${WIN_NO_SLASH}*?`,
  3067. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  3068. NO_DOT: `(?!${DOT_LITERAL})`,
  3069. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  3070. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  3071. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  3072. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  3073. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  3074. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  3075. };
  3076. /**
  3077. * POSIX Bracket Regex
  3078. */
  3079. const POSIX_REGEX_SOURCE$1 = {
  3080. alnum: 'a-zA-Z0-9',
  3081. alpha: 'a-zA-Z',
  3082. ascii: '\\x00-\\x7F',
  3083. blank: ' \\t',
  3084. cntrl: '\\x00-\\x1F\\x7F',
  3085. digit: '0-9',
  3086. graph: '\\x21-\\x7E',
  3087. lower: 'a-z',
  3088. print: '\\x20-\\x7E ',
  3089. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  3090. space: ' \\t\\r\\n\\v\\f',
  3091. upper: 'A-Z',
  3092. word: 'A-Za-z0-9_',
  3093. xdigit: 'A-Fa-f0-9'
  3094. };
  3095. var constants$2 = {
  3096. MAX_LENGTH: 1024 * 64,
  3097. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  3098. // regular expressions
  3099. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  3100. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  3101. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  3102. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  3103. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  3104. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  3105. // Replace globs with equivalent patterns to reduce parsing time.
  3106. REPLACEMENTS: {
  3107. '***': '*',
  3108. '**/**': '**',
  3109. '**/**/**': '**'
  3110. },
  3111. // Digits
  3112. CHAR_0: 48, /* 0 */
  3113. CHAR_9: 57, /* 9 */
  3114. // Alphabet chars.
  3115. CHAR_UPPERCASE_A: 65, /* A */
  3116. CHAR_LOWERCASE_A: 97, /* a */
  3117. CHAR_UPPERCASE_Z: 90, /* Z */
  3118. CHAR_LOWERCASE_Z: 122, /* z */
  3119. CHAR_LEFT_PARENTHESES: 40, /* ( */
  3120. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  3121. CHAR_ASTERISK: 42, /* * */
  3122. // Non-alphabetic chars.
  3123. CHAR_AMPERSAND: 38, /* & */
  3124. CHAR_AT: 64, /* @ */
  3125. CHAR_BACKWARD_SLASH: 92, /* \ */
  3126. CHAR_CARRIAGE_RETURN: 13, /* \r */
  3127. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  3128. CHAR_COLON: 58, /* : */
  3129. CHAR_COMMA: 44, /* , */
  3130. CHAR_DOT: 46, /* . */
  3131. CHAR_DOUBLE_QUOTE: 34, /* " */
  3132. CHAR_EQUAL: 61, /* = */
  3133. CHAR_EXCLAMATION_MARK: 33, /* ! */
  3134. CHAR_FORM_FEED: 12, /* \f */
  3135. CHAR_FORWARD_SLASH: 47, /* / */
  3136. CHAR_GRAVE_ACCENT: 96, /* ` */
  3137. CHAR_HASH: 35, /* # */
  3138. CHAR_HYPHEN_MINUS: 45, /* - */
  3139. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  3140. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  3141. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  3142. CHAR_LINE_FEED: 10, /* \n */
  3143. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  3144. CHAR_PERCENT: 37, /* % */
  3145. CHAR_PLUS: 43, /* + */
  3146. CHAR_QUESTION_MARK: 63, /* ? */
  3147. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  3148. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  3149. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  3150. CHAR_SEMICOLON: 59, /* ; */
  3151. CHAR_SINGLE_QUOTE: 39, /* ' */
  3152. CHAR_SPACE: 32, /* */
  3153. CHAR_TAB: 9, /* \t */
  3154. CHAR_UNDERSCORE: 95, /* _ */
  3155. CHAR_VERTICAL_LINE: 124, /* | */
  3156. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  3157. SEP: path$1.sep,
  3158. /**
  3159. * Create EXTGLOB_CHARS
  3160. */
  3161. extglobChars(chars) {
  3162. return {
  3163. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  3164. '?': { type: 'qmark', open: '(?:', close: ')?' },
  3165. '+': { type: 'plus', open: '(?:', close: ')+' },
  3166. '*': { type: 'star', open: '(?:', close: ')*' },
  3167. '@': { type: 'at', open: '(?:', close: ')' }
  3168. };
  3169. },
  3170. /**
  3171. * Create GLOB_CHARS
  3172. */
  3173. globChars(win32) {
  3174. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  3175. }
  3176. };
  3177. (function (exports) {
  3178. const path = require$$0$1;
  3179. const win32 = process.platform === 'win32';
  3180. const {
  3181. REGEX_BACKSLASH,
  3182. REGEX_REMOVE_BACKSLASH,
  3183. REGEX_SPECIAL_CHARS,
  3184. REGEX_SPECIAL_CHARS_GLOBAL
  3185. } = constants$2;
  3186. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  3187. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  3188. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  3189. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  3190. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  3191. exports.removeBackslashes = str => {
  3192. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  3193. return match === '\\' ? '' : match;
  3194. });
  3195. };
  3196. exports.supportsLookbehinds = () => {
  3197. const segs = process.version.slice(1).split('.').map(Number);
  3198. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  3199. return true;
  3200. }
  3201. return false;
  3202. };
  3203. exports.isWindows = options => {
  3204. if (options && typeof options.windows === 'boolean') {
  3205. return options.windows;
  3206. }
  3207. return win32 === true || path.sep === '\\';
  3208. };
  3209. exports.escapeLast = (input, char, lastIdx) => {
  3210. const idx = input.lastIndexOf(char, lastIdx);
  3211. if (idx === -1) return input;
  3212. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  3213. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  3214. };
  3215. exports.removePrefix = (input, state = {}) => {
  3216. let output = input;
  3217. if (output.startsWith('./')) {
  3218. output = output.slice(2);
  3219. state.prefix = './';
  3220. }
  3221. return output;
  3222. };
  3223. exports.wrapOutput = (input, state = {}, options = {}) => {
  3224. const prepend = options.contains ? '' : '^';
  3225. const append = options.contains ? '' : '$';
  3226. let output = `${prepend}(?:${input})${append}`;
  3227. if (state.negated === true) {
  3228. output = `(?:^(?!${output}).*$)`;
  3229. }
  3230. return output;
  3231. };
  3232. } (utils$3));
  3233. const utils$2 = utils$3;
  3234. const {
  3235. CHAR_ASTERISK, /* * */
  3236. CHAR_AT, /* @ */
  3237. CHAR_BACKWARD_SLASH, /* \ */
  3238. CHAR_COMMA, /* , */
  3239. CHAR_DOT, /* . */
  3240. CHAR_EXCLAMATION_MARK, /* ! */
  3241. CHAR_FORWARD_SLASH, /* / */
  3242. CHAR_LEFT_CURLY_BRACE, /* { */
  3243. CHAR_LEFT_PARENTHESES, /* ( */
  3244. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  3245. CHAR_PLUS, /* + */
  3246. CHAR_QUESTION_MARK, /* ? */
  3247. CHAR_RIGHT_CURLY_BRACE, /* } */
  3248. CHAR_RIGHT_PARENTHESES, /* ) */
  3249. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  3250. } = constants$2;
  3251. const isPathSeparator = code => {
  3252. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  3253. };
  3254. const depth = token => {
  3255. if (token.isPrefix !== true) {
  3256. token.depth = token.isGlobstar ? Infinity : 1;
  3257. }
  3258. };
  3259. /**
  3260. * Quickly scans a glob pattern and returns an object with a handful of
  3261. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  3262. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  3263. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  3264. *
  3265. * ```js
  3266. * const pm = require('picomatch');
  3267. * console.log(pm.scan('foo/bar/*.js'));
  3268. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  3269. * ```
  3270. * @param {String} `str`
  3271. * @param {Object} `options`
  3272. * @return {Object} Returns an object with tokens and regex source string.
  3273. * @api public
  3274. */
  3275. const scan$1 = (input, options) => {
  3276. const opts = options || {};
  3277. const length = input.length - 1;
  3278. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  3279. const slashes = [];
  3280. const tokens = [];
  3281. const parts = [];
  3282. let str = input;
  3283. let index = -1;
  3284. let start = 0;
  3285. let lastIndex = 0;
  3286. let isBrace = false;
  3287. let isBracket = false;
  3288. let isGlob = false;
  3289. let isExtglob = false;
  3290. let isGlobstar = false;
  3291. let braceEscaped = false;
  3292. let backslashes = false;
  3293. let negated = false;
  3294. let negatedExtglob = false;
  3295. let finished = false;
  3296. let braces = 0;
  3297. let prev;
  3298. let code;
  3299. let token = { value: '', depth: 0, isGlob: false };
  3300. const eos = () => index >= length;
  3301. const peek = () => str.charCodeAt(index + 1);
  3302. const advance = () => {
  3303. prev = code;
  3304. return str.charCodeAt(++index);
  3305. };
  3306. while (index < length) {
  3307. code = advance();
  3308. let next;
  3309. if (code === CHAR_BACKWARD_SLASH) {
  3310. backslashes = token.backslashes = true;
  3311. code = advance();
  3312. if (code === CHAR_LEFT_CURLY_BRACE) {
  3313. braceEscaped = true;
  3314. }
  3315. continue;
  3316. }
  3317. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  3318. braces++;
  3319. while (eos() !== true && (code = advance())) {
  3320. if (code === CHAR_BACKWARD_SLASH) {
  3321. backslashes = token.backslashes = true;
  3322. advance();
  3323. continue;
  3324. }
  3325. if (code === CHAR_LEFT_CURLY_BRACE) {
  3326. braces++;
  3327. continue;
  3328. }
  3329. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  3330. isBrace = token.isBrace = true;
  3331. isGlob = token.isGlob = true;
  3332. finished = true;
  3333. if (scanToEnd === true) {
  3334. continue;
  3335. }
  3336. break;
  3337. }
  3338. if (braceEscaped !== true && code === CHAR_COMMA) {
  3339. isBrace = token.isBrace = true;
  3340. isGlob = token.isGlob = true;
  3341. finished = true;
  3342. if (scanToEnd === true) {
  3343. continue;
  3344. }
  3345. break;
  3346. }
  3347. if (code === CHAR_RIGHT_CURLY_BRACE) {
  3348. braces--;
  3349. if (braces === 0) {
  3350. braceEscaped = false;
  3351. isBrace = token.isBrace = true;
  3352. finished = true;
  3353. break;
  3354. }
  3355. }
  3356. }
  3357. if (scanToEnd === true) {
  3358. continue;
  3359. }
  3360. break;
  3361. }
  3362. if (code === CHAR_FORWARD_SLASH) {
  3363. slashes.push(index);
  3364. tokens.push(token);
  3365. token = { value: '', depth: 0, isGlob: false };
  3366. if (finished === true) continue;
  3367. if (prev === CHAR_DOT && index === (start + 1)) {
  3368. start += 2;
  3369. continue;
  3370. }
  3371. lastIndex = index + 1;
  3372. continue;
  3373. }
  3374. if (opts.noext !== true) {
  3375. const isExtglobChar = code === CHAR_PLUS
  3376. || code === CHAR_AT
  3377. || code === CHAR_ASTERISK
  3378. || code === CHAR_QUESTION_MARK
  3379. || code === CHAR_EXCLAMATION_MARK;
  3380. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  3381. isGlob = token.isGlob = true;
  3382. isExtglob = token.isExtglob = true;
  3383. finished = true;
  3384. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  3385. negatedExtglob = true;
  3386. }
  3387. if (scanToEnd === true) {
  3388. while (eos() !== true && (code = advance())) {
  3389. if (code === CHAR_BACKWARD_SLASH) {
  3390. backslashes = token.backslashes = true;
  3391. code = advance();
  3392. continue;
  3393. }
  3394. if (code === CHAR_RIGHT_PARENTHESES) {
  3395. isGlob = token.isGlob = true;
  3396. finished = true;
  3397. break;
  3398. }
  3399. }
  3400. continue;
  3401. }
  3402. break;
  3403. }
  3404. }
  3405. if (code === CHAR_ASTERISK) {
  3406. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  3407. isGlob = token.isGlob = true;
  3408. finished = true;
  3409. if (scanToEnd === true) {
  3410. continue;
  3411. }
  3412. break;
  3413. }
  3414. if (code === CHAR_QUESTION_MARK) {
  3415. isGlob = token.isGlob = true;
  3416. finished = true;
  3417. if (scanToEnd === true) {
  3418. continue;
  3419. }
  3420. break;
  3421. }
  3422. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  3423. while (eos() !== true && (next = advance())) {
  3424. if (next === CHAR_BACKWARD_SLASH) {
  3425. backslashes = token.backslashes = true;
  3426. advance();
  3427. continue;
  3428. }
  3429. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  3430. isBracket = token.isBracket = true;
  3431. isGlob = token.isGlob = true;
  3432. finished = true;
  3433. break;
  3434. }
  3435. }
  3436. if (scanToEnd === true) {
  3437. continue;
  3438. }
  3439. break;
  3440. }
  3441. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  3442. negated = token.negated = true;
  3443. start++;
  3444. continue;
  3445. }
  3446. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  3447. isGlob = token.isGlob = true;
  3448. if (scanToEnd === true) {
  3449. while (eos() !== true && (code = advance())) {
  3450. if (code === CHAR_LEFT_PARENTHESES) {
  3451. backslashes = token.backslashes = true;
  3452. code = advance();
  3453. continue;
  3454. }
  3455. if (code === CHAR_RIGHT_PARENTHESES) {
  3456. finished = true;
  3457. break;
  3458. }
  3459. }
  3460. continue;
  3461. }
  3462. break;
  3463. }
  3464. if (isGlob === true) {
  3465. finished = true;
  3466. if (scanToEnd === true) {
  3467. continue;
  3468. }
  3469. break;
  3470. }
  3471. }
  3472. if (opts.noext === true) {
  3473. isExtglob = false;
  3474. isGlob = false;
  3475. }
  3476. let base = str;
  3477. let prefix = '';
  3478. let glob = '';
  3479. if (start > 0) {
  3480. prefix = str.slice(0, start);
  3481. str = str.slice(start);
  3482. lastIndex -= start;
  3483. }
  3484. if (base && isGlob === true && lastIndex > 0) {
  3485. base = str.slice(0, lastIndex);
  3486. glob = str.slice(lastIndex);
  3487. } else if (isGlob === true) {
  3488. base = '';
  3489. glob = str;
  3490. } else {
  3491. base = str;
  3492. }
  3493. if (base && base !== '' && base !== '/' && base !== str) {
  3494. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  3495. base = base.slice(0, -1);
  3496. }
  3497. }
  3498. if (opts.unescape === true) {
  3499. if (glob) glob = utils$2.removeBackslashes(glob);
  3500. if (base && backslashes === true) {
  3501. base = utils$2.removeBackslashes(base);
  3502. }
  3503. }
  3504. const state = {
  3505. prefix,
  3506. input,
  3507. start,
  3508. base,
  3509. glob,
  3510. isBrace,
  3511. isBracket,
  3512. isGlob,
  3513. isExtglob,
  3514. isGlobstar,
  3515. negated,
  3516. negatedExtglob
  3517. };
  3518. if (opts.tokens === true) {
  3519. state.maxDepth = 0;
  3520. if (!isPathSeparator(code)) {
  3521. tokens.push(token);
  3522. }
  3523. state.tokens = tokens;
  3524. }
  3525. if (opts.parts === true || opts.tokens === true) {
  3526. let prevIndex;
  3527. for (let idx = 0; idx < slashes.length; idx++) {
  3528. const n = prevIndex ? prevIndex + 1 : start;
  3529. const i = slashes[idx];
  3530. const value = input.slice(n, i);
  3531. if (opts.tokens) {
  3532. if (idx === 0 && start !== 0) {
  3533. tokens[idx].isPrefix = true;
  3534. tokens[idx].value = prefix;
  3535. } else {
  3536. tokens[idx].value = value;
  3537. }
  3538. depth(tokens[idx]);
  3539. state.maxDepth += tokens[idx].depth;
  3540. }
  3541. if (idx !== 0 || value !== '') {
  3542. parts.push(value);
  3543. }
  3544. prevIndex = i;
  3545. }
  3546. if (prevIndex && prevIndex + 1 < input.length) {
  3547. const value = input.slice(prevIndex + 1);
  3548. parts.push(value);
  3549. if (opts.tokens) {
  3550. tokens[tokens.length - 1].value = value;
  3551. depth(tokens[tokens.length - 1]);
  3552. state.maxDepth += tokens[tokens.length - 1].depth;
  3553. }
  3554. }
  3555. state.slashes = slashes;
  3556. state.parts = parts;
  3557. }
  3558. return state;
  3559. };
  3560. var scan_1 = scan$1;
  3561. const constants$1 = constants$2;
  3562. const utils$1 = utils$3;
  3563. /**
  3564. * Constants
  3565. */
  3566. const {
  3567. MAX_LENGTH,
  3568. POSIX_REGEX_SOURCE,
  3569. REGEX_NON_SPECIAL_CHARS,
  3570. REGEX_SPECIAL_CHARS_BACKREF,
  3571. REPLACEMENTS
  3572. } = constants$1;
  3573. /**
  3574. * Helpers
  3575. */
  3576. const expandRange = (args, options) => {
  3577. if (typeof options.expandRange === 'function') {
  3578. return options.expandRange(...args, options);
  3579. }
  3580. args.sort();
  3581. const value = `[${args.join('-')}]`;
  3582. return value;
  3583. };
  3584. /**
  3585. * Create the message for a syntax error
  3586. */
  3587. const syntaxError = (type, char) => {
  3588. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  3589. };
  3590. /**
  3591. * Parse the given input string.
  3592. * @param {String} input
  3593. * @param {Object} options
  3594. * @return {Object}
  3595. */
  3596. const parse$2 = (input, options) => {
  3597. if (typeof input !== 'string') {
  3598. throw new TypeError('Expected a string');
  3599. }
  3600. input = REPLACEMENTS[input] || input;
  3601. const opts = { ...options };
  3602. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3603. let len = input.length;
  3604. if (len > max) {
  3605. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3606. }
  3607. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  3608. const tokens = [bos];
  3609. const capture = opts.capture ? '' : '?:';
  3610. const win32 = utils$1.isWindows(options);
  3611. // create constants based on platform, for windows or posix
  3612. const PLATFORM_CHARS = constants$1.globChars(win32);
  3613. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  3614. const {
  3615. DOT_LITERAL,
  3616. PLUS_LITERAL,
  3617. SLASH_LITERAL,
  3618. ONE_CHAR,
  3619. DOTS_SLASH,
  3620. NO_DOT,
  3621. NO_DOT_SLASH,
  3622. NO_DOTS_SLASH,
  3623. QMARK,
  3624. QMARK_NO_DOT,
  3625. STAR,
  3626. START_ANCHOR
  3627. } = PLATFORM_CHARS;
  3628. const globstar = opts => {
  3629. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3630. };
  3631. const nodot = opts.dot ? '' : NO_DOT;
  3632. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  3633. let star = opts.bash === true ? globstar(opts) : STAR;
  3634. if (opts.capture) {
  3635. star = `(${star})`;
  3636. }
  3637. // minimatch options support
  3638. if (typeof opts.noext === 'boolean') {
  3639. opts.noextglob = opts.noext;
  3640. }
  3641. const state = {
  3642. input,
  3643. index: -1,
  3644. start: 0,
  3645. dot: opts.dot === true,
  3646. consumed: '',
  3647. output: '',
  3648. prefix: '',
  3649. backtrack: false,
  3650. negated: false,
  3651. brackets: 0,
  3652. braces: 0,
  3653. parens: 0,
  3654. quotes: 0,
  3655. globstar: false,
  3656. tokens
  3657. };
  3658. input = utils$1.removePrefix(input, state);
  3659. len = input.length;
  3660. const extglobs = [];
  3661. const braces = [];
  3662. const stack = [];
  3663. let prev = bos;
  3664. let value;
  3665. /**
  3666. * Tokenizing helpers
  3667. */
  3668. const eos = () => state.index === len - 1;
  3669. const peek = state.peek = (n = 1) => input[state.index + n];
  3670. const advance = state.advance = () => input[++state.index] || '';
  3671. const remaining = () => input.slice(state.index + 1);
  3672. const consume = (value = '', num = 0) => {
  3673. state.consumed += value;
  3674. state.index += num;
  3675. };
  3676. const append = token => {
  3677. state.output += token.output != null ? token.output : token.value;
  3678. consume(token.value);
  3679. };
  3680. const negate = () => {
  3681. let count = 1;
  3682. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  3683. advance();
  3684. state.start++;
  3685. count++;
  3686. }
  3687. if (count % 2 === 0) {
  3688. return false;
  3689. }
  3690. state.negated = true;
  3691. state.start++;
  3692. return true;
  3693. };
  3694. const increment = type => {
  3695. state[type]++;
  3696. stack.push(type);
  3697. };
  3698. const decrement = type => {
  3699. state[type]--;
  3700. stack.pop();
  3701. };
  3702. /**
  3703. * Push tokens onto the tokens array. This helper speeds up
  3704. * tokenizing by 1) helping us avoid backtracking as much as possible,
  3705. * and 2) helping us avoid creating extra tokens when consecutive
  3706. * characters are plain text. This improves performance and simplifies
  3707. * lookbehinds.
  3708. */
  3709. const push = tok => {
  3710. if (prev.type === 'globstar') {
  3711. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  3712. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  3713. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  3714. state.output = state.output.slice(0, -prev.output.length);
  3715. prev.type = 'star';
  3716. prev.value = '*';
  3717. prev.output = star;
  3718. state.output += prev.output;
  3719. }
  3720. }
  3721. if (extglobs.length && tok.type !== 'paren') {
  3722. extglobs[extglobs.length - 1].inner += tok.value;
  3723. }
  3724. if (tok.value || tok.output) append(tok);
  3725. if (prev && prev.type === 'text' && tok.type === 'text') {
  3726. prev.value += tok.value;
  3727. prev.output = (prev.output || '') + tok.value;
  3728. return;
  3729. }
  3730. tok.prev = prev;
  3731. tokens.push(tok);
  3732. prev = tok;
  3733. };
  3734. const extglobOpen = (type, value) => {
  3735. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  3736. token.prev = prev;
  3737. token.parens = state.parens;
  3738. token.output = state.output;
  3739. const output = (opts.capture ? '(' : '') + token.open;
  3740. increment('parens');
  3741. push({ type, value, output: state.output ? '' : ONE_CHAR });
  3742. push({ type: 'paren', extglob: true, value: advance(), output });
  3743. extglobs.push(token);
  3744. };
  3745. const extglobClose = token => {
  3746. let output = token.close + (opts.capture ? ')' : '');
  3747. let rest;
  3748. if (token.type === 'negate') {
  3749. let extglobStar = star;
  3750. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  3751. extglobStar = globstar(opts);
  3752. }
  3753. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  3754. output = token.close = `)$))${extglobStar}`;
  3755. }
  3756. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  3757. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  3758. // In this case, we need to parse the string and use it in the output of the original pattern.
  3759. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  3760. //
  3761. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  3762. const expression = parse$2(rest, { ...options, fastpaths: false }).output;
  3763. output = token.close = `)${expression})${extglobStar})`;
  3764. }
  3765. if (token.prev.type === 'bos') {
  3766. state.negatedExtglob = true;
  3767. }
  3768. }
  3769. push({ type: 'paren', extglob: true, value, output });
  3770. decrement('parens');
  3771. };
  3772. /**
  3773. * Fast paths
  3774. */
  3775. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  3776. let backslashes = false;
  3777. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  3778. if (first === '\\') {
  3779. backslashes = true;
  3780. return m;
  3781. }
  3782. if (first === '?') {
  3783. if (esc) {
  3784. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  3785. }
  3786. if (index === 0) {
  3787. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  3788. }
  3789. return QMARK.repeat(chars.length);
  3790. }
  3791. if (first === '.') {
  3792. return DOT_LITERAL.repeat(chars.length);
  3793. }
  3794. if (first === '*') {
  3795. if (esc) {
  3796. return esc + first + (rest ? star : '');
  3797. }
  3798. return star;
  3799. }
  3800. return esc ? m : `\\${m}`;
  3801. });
  3802. if (backslashes === true) {
  3803. if (opts.unescape === true) {
  3804. output = output.replace(/\\/g, '');
  3805. } else {
  3806. output = output.replace(/\\+/g, m => {
  3807. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  3808. });
  3809. }
  3810. }
  3811. if (output === input && opts.contains === true) {
  3812. state.output = input;
  3813. return state;
  3814. }
  3815. state.output = utils$1.wrapOutput(output, state, options);
  3816. return state;
  3817. }
  3818. /**
  3819. * Tokenize input until we reach end-of-string
  3820. */
  3821. while (!eos()) {
  3822. value = advance();
  3823. if (value === '\u0000') {
  3824. continue;
  3825. }
  3826. /**
  3827. * Escaped characters
  3828. */
  3829. if (value === '\\') {
  3830. const next = peek();
  3831. if (next === '/' && opts.bash !== true) {
  3832. continue;
  3833. }
  3834. if (next === '.' || next === ';') {
  3835. continue;
  3836. }
  3837. if (!next) {
  3838. value += '\\';
  3839. push({ type: 'text', value });
  3840. continue;
  3841. }
  3842. // collapse slashes to reduce potential for exploits
  3843. const match = /^\\+/.exec(remaining());
  3844. let slashes = 0;
  3845. if (match && match[0].length > 2) {
  3846. slashes = match[0].length;
  3847. state.index += slashes;
  3848. if (slashes % 2 !== 0) {
  3849. value += '\\';
  3850. }
  3851. }
  3852. if (opts.unescape === true) {
  3853. value = advance();
  3854. } else {
  3855. value += advance();
  3856. }
  3857. if (state.brackets === 0) {
  3858. push({ type: 'text', value });
  3859. continue;
  3860. }
  3861. }
  3862. /**
  3863. * If we're inside a regex character class, continue
  3864. * until we reach the closing bracket.
  3865. */
  3866. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  3867. if (opts.posix !== false && value === ':') {
  3868. const inner = prev.value.slice(1);
  3869. if (inner.includes('[')) {
  3870. prev.posix = true;
  3871. if (inner.includes(':')) {
  3872. const idx = prev.value.lastIndexOf('[');
  3873. const pre = prev.value.slice(0, idx);
  3874. const rest = prev.value.slice(idx + 2);
  3875. const posix = POSIX_REGEX_SOURCE[rest];
  3876. if (posix) {
  3877. prev.value = pre + posix;
  3878. state.backtrack = true;
  3879. advance();
  3880. if (!bos.output && tokens.indexOf(prev) === 1) {
  3881. bos.output = ONE_CHAR;
  3882. }
  3883. continue;
  3884. }
  3885. }
  3886. }
  3887. }
  3888. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  3889. value = `\\${value}`;
  3890. }
  3891. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  3892. value = `\\${value}`;
  3893. }
  3894. if (opts.posix === true && value === '!' && prev.value === '[') {
  3895. value = '^';
  3896. }
  3897. prev.value += value;
  3898. append({ value });
  3899. continue;
  3900. }
  3901. /**
  3902. * If we're inside a quoted string, continue
  3903. * until we reach the closing double quote.
  3904. */
  3905. if (state.quotes === 1 && value !== '"') {
  3906. value = utils$1.escapeRegex(value);
  3907. prev.value += value;
  3908. append({ value });
  3909. continue;
  3910. }
  3911. /**
  3912. * Double quotes
  3913. */
  3914. if (value === '"') {
  3915. state.quotes = state.quotes === 1 ? 0 : 1;
  3916. if (opts.keepQuotes === true) {
  3917. push({ type: 'text', value });
  3918. }
  3919. continue;
  3920. }
  3921. /**
  3922. * Parentheses
  3923. */
  3924. if (value === '(') {
  3925. increment('parens');
  3926. push({ type: 'paren', value });
  3927. continue;
  3928. }
  3929. if (value === ')') {
  3930. if (state.parens === 0 && opts.strictBrackets === true) {
  3931. throw new SyntaxError(syntaxError('opening', '('));
  3932. }
  3933. const extglob = extglobs[extglobs.length - 1];
  3934. if (extglob && state.parens === extglob.parens + 1) {
  3935. extglobClose(extglobs.pop());
  3936. continue;
  3937. }
  3938. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  3939. decrement('parens');
  3940. continue;
  3941. }
  3942. /**
  3943. * Square brackets
  3944. */
  3945. if (value === '[') {
  3946. if (opts.nobracket === true || !remaining().includes(']')) {
  3947. if (opts.nobracket !== true && opts.strictBrackets === true) {
  3948. throw new SyntaxError(syntaxError('closing', ']'));
  3949. }
  3950. value = `\\${value}`;
  3951. } else {
  3952. increment('brackets');
  3953. }
  3954. push({ type: 'bracket', value });
  3955. continue;
  3956. }
  3957. if (value === ']') {
  3958. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  3959. push({ type: 'text', value, output: `\\${value}` });
  3960. continue;
  3961. }
  3962. if (state.brackets === 0) {
  3963. if (opts.strictBrackets === true) {
  3964. throw new SyntaxError(syntaxError('opening', '['));
  3965. }
  3966. push({ type: 'text', value, output: `\\${value}` });
  3967. continue;
  3968. }
  3969. decrement('brackets');
  3970. const prevValue = prev.value.slice(1);
  3971. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  3972. value = `/${value}`;
  3973. }
  3974. prev.value += value;
  3975. append({ value });
  3976. // when literal brackets are explicitly disabled
  3977. // assume we should match with a regex character class
  3978. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  3979. continue;
  3980. }
  3981. const escaped = utils$1.escapeRegex(prev.value);
  3982. state.output = state.output.slice(0, -prev.value.length);
  3983. // when literal brackets are explicitly enabled
  3984. // assume we should escape the brackets to match literal characters
  3985. if (opts.literalBrackets === true) {
  3986. state.output += escaped;
  3987. prev.value = escaped;
  3988. continue;
  3989. }
  3990. // when the user specifies nothing, try to match both
  3991. prev.value = `(${capture}${escaped}|${prev.value})`;
  3992. state.output += prev.value;
  3993. continue;
  3994. }
  3995. /**
  3996. * Braces
  3997. */
  3998. if (value === '{' && opts.nobrace !== true) {
  3999. increment('braces');
  4000. const open = {
  4001. type: 'brace',
  4002. value,
  4003. output: '(',
  4004. outputIndex: state.output.length,
  4005. tokensIndex: state.tokens.length
  4006. };
  4007. braces.push(open);
  4008. push(open);
  4009. continue;
  4010. }
  4011. if (value === '}') {
  4012. const brace = braces[braces.length - 1];
  4013. if (opts.nobrace === true || !brace) {
  4014. push({ type: 'text', value, output: value });
  4015. continue;
  4016. }
  4017. let output = ')';
  4018. if (brace.dots === true) {
  4019. const arr = tokens.slice();
  4020. const range = [];
  4021. for (let i = arr.length - 1; i >= 0; i--) {
  4022. tokens.pop();
  4023. if (arr[i].type === 'brace') {
  4024. break;
  4025. }
  4026. if (arr[i].type !== 'dots') {
  4027. range.unshift(arr[i].value);
  4028. }
  4029. }
  4030. output = expandRange(range, opts);
  4031. state.backtrack = true;
  4032. }
  4033. if (brace.comma !== true && brace.dots !== true) {
  4034. const out = state.output.slice(0, brace.outputIndex);
  4035. const toks = state.tokens.slice(brace.tokensIndex);
  4036. brace.value = brace.output = '\\{';
  4037. value = output = '\\}';
  4038. state.output = out;
  4039. for (const t of toks) {
  4040. state.output += (t.output || t.value);
  4041. }
  4042. }
  4043. push({ type: 'brace', value, output });
  4044. decrement('braces');
  4045. braces.pop();
  4046. continue;
  4047. }
  4048. /**
  4049. * Pipes
  4050. */
  4051. if (value === '|') {
  4052. if (extglobs.length > 0) {
  4053. extglobs[extglobs.length - 1].conditions++;
  4054. }
  4055. push({ type: 'text', value });
  4056. continue;
  4057. }
  4058. /**
  4059. * Commas
  4060. */
  4061. if (value === ',') {
  4062. let output = value;
  4063. const brace = braces[braces.length - 1];
  4064. if (brace && stack[stack.length - 1] === 'braces') {
  4065. brace.comma = true;
  4066. output = '|';
  4067. }
  4068. push({ type: 'comma', value, output });
  4069. continue;
  4070. }
  4071. /**
  4072. * Slashes
  4073. */
  4074. if (value === '/') {
  4075. // if the beginning of the glob is "./", advance the start
  4076. // to the current index, and don't add the "./" characters
  4077. // to the state. This greatly simplifies lookbehinds when
  4078. // checking for BOS characters like "!" and "." (not "./")
  4079. if (prev.type === 'dot' && state.index === state.start + 1) {
  4080. state.start = state.index + 1;
  4081. state.consumed = '';
  4082. state.output = '';
  4083. tokens.pop();
  4084. prev = bos; // reset "prev" to the first token
  4085. continue;
  4086. }
  4087. push({ type: 'slash', value, output: SLASH_LITERAL });
  4088. continue;
  4089. }
  4090. /**
  4091. * Dots
  4092. */
  4093. if (value === '.') {
  4094. if (state.braces > 0 && prev.type === 'dot') {
  4095. if (prev.value === '.') prev.output = DOT_LITERAL;
  4096. const brace = braces[braces.length - 1];
  4097. prev.type = 'dots';
  4098. prev.output += value;
  4099. prev.value += value;
  4100. brace.dots = true;
  4101. continue;
  4102. }
  4103. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  4104. push({ type: 'text', value, output: DOT_LITERAL });
  4105. continue;
  4106. }
  4107. push({ type: 'dot', value, output: DOT_LITERAL });
  4108. continue;
  4109. }
  4110. /**
  4111. * Question marks
  4112. */
  4113. if (value === '?') {
  4114. const isGroup = prev && prev.value === '(';
  4115. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  4116. extglobOpen('qmark', value);
  4117. continue;
  4118. }
  4119. if (prev && prev.type === 'paren') {
  4120. const next = peek();
  4121. let output = value;
  4122. if (next === '<' && !utils$1.supportsLookbehinds()) {
  4123. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  4124. }
  4125. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  4126. output = `\\${value}`;
  4127. }
  4128. push({ type: 'text', value, output });
  4129. continue;
  4130. }
  4131. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  4132. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  4133. continue;
  4134. }
  4135. push({ type: 'qmark', value, output: QMARK });
  4136. continue;
  4137. }
  4138. /**
  4139. * Exclamation
  4140. */
  4141. if (value === '!') {
  4142. if (opts.noextglob !== true && peek() === '(') {
  4143. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  4144. extglobOpen('negate', value);
  4145. continue;
  4146. }
  4147. }
  4148. if (opts.nonegate !== true && state.index === 0) {
  4149. negate();
  4150. continue;
  4151. }
  4152. }
  4153. /**
  4154. * Plus
  4155. */
  4156. if (value === '+') {
  4157. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  4158. extglobOpen('plus', value);
  4159. continue;
  4160. }
  4161. if ((prev && prev.value === '(') || opts.regex === false) {
  4162. push({ type: 'plus', value, output: PLUS_LITERAL });
  4163. continue;
  4164. }
  4165. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  4166. push({ type: 'plus', value });
  4167. continue;
  4168. }
  4169. push({ type: 'plus', value: PLUS_LITERAL });
  4170. continue;
  4171. }
  4172. /**
  4173. * Plain text
  4174. */
  4175. if (value === '@') {
  4176. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  4177. push({ type: 'at', extglob: true, value, output: '' });
  4178. continue;
  4179. }
  4180. push({ type: 'text', value });
  4181. continue;
  4182. }
  4183. /**
  4184. * Plain text
  4185. */
  4186. if (value !== '*') {
  4187. if (value === '$' || value === '^') {
  4188. value = `\\${value}`;
  4189. }
  4190. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  4191. if (match) {
  4192. value += match[0];
  4193. state.index += match[0].length;
  4194. }
  4195. push({ type: 'text', value });
  4196. continue;
  4197. }
  4198. /**
  4199. * Stars
  4200. */
  4201. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  4202. prev.type = 'star';
  4203. prev.star = true;
  4204. prev.value += value;
  4205. prev.output = star;
  4206. state.backtrack = true;
  4207. state.globstar = true;
  4208. consume(value);
  4209. continue;
  4210. }
  4211. let rest = remaining();
  4212. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  4213. extglobOpen('star', value);
  4214. continue;
  4215. }
  4216. if (prev.type === 'star') {
  4217. if (opts.noglobstar === true) {
  4218. consume(value);
  4219. continue;
  4220. }
  4221. const prior = prev.prev;
  4222. const before = prior.prev;
  4223. const isStart = prior.type === 'slash' || prior.type === 'bos';
  4224. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  4225. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  4226. push({ type: 'star', value, output: '' });
  4227. continue;
  4228. }
  4229. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  4230. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  4231. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  4232. push({ type: 'star', value, output: '' });
  4233. continue;
  4234. }
  4235. // strip consecutive `/**/`
  4236. while (rest.slice(0, 3) === '/**') {
  4237. const after = input[state.index + 4];
  4238. if (after && after !== '/') {
  4239. break;
  4240. }
  4241. rest = rest.slice(3);
  4242. consume('/**', 3);
  4243. }
  4244. if (prior.type === 'bos' && eos()) {
  4245. prev.type = 'globstar';
  4246. prev.value += value;
  4247. prev.output = globstar(opts);
  4248. state.output = prev.output;
  4249. state.globstar = true;
  4250. consume(value);
  4251. continue;
  4252. }
  4253. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  4254. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  4255. prior.output = `(?:${prior.output}`;
  4256. prev.type = 'globstar';
  4257. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  4258. prev.value += value;
  4259. state.globstar = true;
  4260. state.output += prior.output + prev.output;
  4261. consume(value);
  4262. continue;
  4263. }
  4264. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  4265. const end = rest[1] !== void 0 ? '|$' : '';
  4266. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  4267. prior.output = `(?:${prior.output}`;
  4268. prev.type = 'globstar';
  4269. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  4270. prev.value += value;
  4271. state.output += prior.output + prev.output;
  4272. state.globstar = true;
  4273. consume(value + advance());
  4274. push({ type: 'slash', value: '/', output: '' });
  4275. continue;
  4276. }
  4277. if (prior.type === 'bos' && rest[0] === '/') {
  4278. prev.type = 'globstar';
  4279. prev.value += value;
  4280. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  4281. state.output = prev.output;
  4282. state.globstar = true;
  4283. consume(value + advance());
  4284. push({ type: 'slash', value: '/', output: '' });
  4285. continue;
  4286. }
  4287. // remove single star from output
  4288. state.output = state.output.slice(0, -prev.output.length);
  4289. // reset previous token to globstar
  4290. prev.type = 'globstar';
  4291. prev.output = globstar(opts);
  4292. prev.value += value;
  4293. // reset output with globstar
  4294. state.output += prev.output;
  4295. state.globstar = true;
  4296. consume(value);
  4297. continue;
  4298. }
  4299. const token = { type: 'star', value, output: star };
  4300. if (opts.bash === true) {
  4301. token.output = '.*?';
  4302. if (prev.type === 'bos' || prev.type === 'slash') {
  4303. token.output = nodot + token.output;
  4304. }
  4305. push(token);
  4306. continue;
  4307. }
  4308. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  4309. token.output = value;
  4310. push(token);
  4311. continue;
  4312. }
  4313. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  4314. if (prev.type === 'dot') {
  4315. state.output += NO_DOT_SLASH;
  4316. prev.output += NO_DOT_SLASH;
  4317. } else if (opts.dot === true) {
  4318. state.output += NO_DOTS_SLASH;
  4319. prev.output += NO_DOTS_SLASH;
  4320. } else {
  4321. state.output += nodot;
  4322. prev.output += nodot;
  4323. }
  4324. if (peek() !== '*') {
  4325. state.output += ONE_CHAR;
  4326. prev.output += ONE_CHAR;
  4327. }
  4328. }
  4329. push(token);
  4330. }
  4331. while (state.brackets > 0) {
  4332. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  4333. state.output = utils$1.escapeLast(state.output, '[');
  4334. decrement('brackets');
  4335. }
  4336. while (state.parens > 0) {
  4337. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  4338. state.output = utils$1.escapeLast(state.output, '(');
  4339. decrement('parens');
  4340. }
  4341. while (state.braces > 0) {
  4342. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  4343. state.output = utils$1.escapeLast(state.output, '{');
  4344. decrement('braces');
  4345. }
  4346. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  4347. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  4348. }
  4349. // rebuild the output if we had to backtrack at any point
  4350. if (state.backtrack === true) {
  4351. state.output = '';
  4352. for (const token of state.tokens) {
  4353. state.output += token.output != null ? token.output : token.value;
  4354. if (token.suffix) {
  4355. state.output += token.suffix;
  4356. }
  4357. }
  4358. }
  4359. return state;
  4360. };
  4361. /**
  4362. * Fast paths for creating regular expressions for common glob patterns.
  4363. * This can significantly speed up processing and has very little downside
  4364. * impact when none of the fast paths match.
  4365. */
  4366. parse$2.fastpaths = (input, options) => {
  4367. const opts = { ...options };
  4368. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  4369. const len = input.length;
  4370. if (len > max) {
  4371. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  4372. }
  4373. input = REPLACEMENTS[input] || input;
  4374. const win32 = utils$1.isWindows(options);
  4375. // create constants based on platform, for windows or posix
  4376. const {
  4377. DOT_LITERAL,
  4378. SLASH_LITERAL,
  4379. ONE_CHAR,
  4380. DOTS_SLASH,
  4381. NO_DOT,
  4382. NO_DOTS,
  4383. NO_DOTS_SLASH,
  4384. STAR,
  4385. START_ANCHOR
  4386. } = constants$1.globChars(win32);
  4387. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  4388. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  4389. const capture = opts.capture ? '' : '?:';
  4390. const state = { negated: false, prefix: '' };
  4391. let star = opts.bash === true ? '.*?' : STAR;
  4392. if (opts.capture) {
  4393. star = `(${star})`;
  4394. }
  4395. const globstar = opts => {
  4396. if (opts.noglobstar === true) return star;
  4397. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  4398. };
  4399. const create = str => {
  4400. switch (str) {
  4401. case '*':
  4402. return `${nodot}${ONE_CHAR}${star}`;
  4403. case '.*':
  4404. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  4405. case '*.*':
  4406. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  4407. case '*/*':
  4408. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  4409. case '**':
  4410. return nodot + globstar(opts);
  4411. case '**/*':
  4412. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  4413. case '**/*.*':
  4414. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  4415. case '**/.*':
  4416. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  4417. default: {
  4418. const match = /^(.*?)\.(\w+)$/.exec(str);
  4419. if (!match) return;
  4420. const source = create(match[1]);
  4421. if (!source) return;
  4422. return source + DOT_LITERAL + match[2];
  4423. }
  4424. }
  4425. };
  4426. const output = utils$1.removePrefix(input, state);
  4427. let source = create(output);
  4428. if (source && opts.strictSlashes !== true) {
  4429. source += `${SLASH_LITERAL}?`;
  4430. }
  4431. return source;
  4432. };
  4433. var parse_1 = parse$2;
  4434. const path = require$$0$1;
  4435. const scan = scan_1;
  4436. const parse$1 = parse_1;
  4437. const utils = utils$3;
  4438. const constants = constants$2;
  4439. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  4440. /**
  4441. * Creates a matcher function from one or more glob patterns. The
  4442. * returned function takes a string to match as its first argument,
  4443. * and returns true if the string is a match. The returned matcher
  4444. * function also takes a boolean as the second argument that, when true,
  4445. * returns an object with additional information.
  4446. *
  4447. * ```js
  4448. * const picomatch = require('picomatch');
  4449. * // picomatch(glob[, options]);
  4450. *
  4451. * const isMatch = picomatch('*.!(*a)');
  4452. * console.log(isMatch('a.a')); //=> false
  4453. * console.log(isMatch('a.b')); //=> true
  4454. * ```
  4455. * @name picomatch
  4456. * @param {String|Array} `globs` One or more glob patterns.
  4457. * @param {Object=} `options`
  4458. * @return {Function=} Returns a matcher function.
  4459. * @api public
  4460. */
  4461. const picomatch$1 = (glob, options, returnState = false) => {
  4462. if (Array.isArray(glob)) {
  4463. const fns = glob.map(input => picomatch$1(input, options, returnState));
  4464. const arrayMatcher = str => {
  4465. for (const isMatch of fns) {
  4466. const state = isMatch(str);
  4467. if (state) return state;
  4468. }
  4469. return false;
  4470. };
  4471. return arrayMatcher;
  4472. }
  4473. const isState = isObject(glob) && glob.tokens && glob.input;
  4474. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  4475. throw new TypeError('Expected pattern to be a non-empty string');
  4476. }
  4477. const opts = options || {};
  4478. const posix = utils.isWindows(options);
  4479. const regex = isState
  4480. ? picomatch$1.compileRe(glob, options)
  4481. : picomatch$1.makeRe(glob, options, false, true);
  4482. const state = regex.state;
  4483. delete regex.state;
  4484. let isIgnored = () => false;
  4485. if (opts.ignore) {
  4486. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  4487. isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
  4488. }
  4489. const matcher = (input, returnObject = false) => {
  4490. const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix });
  4491. const result = { glob, state, regex, posix, input, output, match, isMatch };
  4492. if (typeof opts.onResult === 'function') {
  4493. opts.onResult(result);
  4494. }
  4495. if (isMatch === false) {
  4496. result.isMatch = false;
  4497. return returnObject ? result : false;
  4498. }
  4499. if (isIgnored(input)) {
  4500. if (typeof opts.onIgnore === 'function') {
  4501. opts.onIgnore(result);
  4502. }
  4503. result.isMatch = false;
  4504. return returnObject ? result : false;
  4505. }
  4506. if (typeof opts.onMatch === 'function') {
  4507. opts.onMatch(result);
  4508. }
  4509. return returnObject ? result : true;
  4510. };
  4511. if (returnState) {
  4512. matcher.state = state;
  4513. }
  4514. return matcher;
  4515. };
  4516. /**
  4517. * Test `input` with the given `regex`. This is used by the main
  4518. * `picomatch()` function to test the input string.
  4519. *
  4520. * ```js
  4521. * const picomatch = require('picomatch');
  4522. * // picomatch.test(input, regex[, options]);
  4523. *
  4524. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  4525. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  4526. * ```
  4527. * @param {String} `input` String to test.
  4528. * @param {RegExp} `regex`
  4529. * @return {Object} Returns an object with matching info.
  4530. * @api public
  4531. */
  4532. picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
  4533. if (typeof input !== 'string') {
  4534. throw new TypeError('Expected input to be a string');
  4535. }
  4536. if (input === '') {
  4537. return { isMatch: false, output: '' };
  4538. }
  4539. const opts = options || {};
  4540. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  4541. let match = input === glob;
  4542. let output = (match && format) ? format(input) : input;
  4543. if (match === false) {
  4544. output = format ? format(input) : input;
  4545. match = output === glob;
  4546. }
  4547. if (match === false || opts.capture === true) {
  4548. if (opts.matchBase === true || opts.basename === true) {
  4549. match = picomatch$1.matchBase(input, regex, options, posix);
  4550. } else {
  4551. match = regex.exec(output);
  4552. }
  4553. }
  4554. return { isMatch: Boolean(match), match, output };
  4555. };
  4556. /**
  4557. * Match the basename of a filepath.
  4558. *
  4559. * ```js
  4560. * const picomatch = require('picomatch');
  4561. * // picomatch.matchBase(input, glob[, options]);
  4562. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  4563. * ```
  4564. * @param {String} `input` String to test.
  4565. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  4566. * @return {Boolean}
  4567. * @api public
  4568. */
  4569. picomatch$1.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  4570. const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options);
  4571. return regex.test(path.basename(input));
  4572. };
  4573. /**
  4574. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  4575. *
  4576. * ```js
  4577. * const picomatch = require('picomatch');
  4578. * // picomatch.isMatch(string, patterns[, options]);
  4579. *
  4580. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  4581. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  4582. * ```
  4583. * @param {String|Array} str The string to test.
  4584. * @param {String|Array} patterns One or more glob patterns to use for matching.
  4585. * @param {Object} [options] See available [options](#options).
  4586. * @return {Boolean} Returns true if any patterns match `str`
  4587. * @api public
  4588. */
  4589. picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  4590. /**
  4591. * Parse a glob pattern to create the source string for a regular
  4592. * expression.
  4593. *
  4594. * ```js
  4595. * const picomatch = require('picomatch');
  4596. * const result = picomatch.parse(pattern[, options]);
  4597. * ```
  4598. * @param {String} `pattern`
  4599. * @param {Object} `options`
  4600. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  4601. * @api public
  4602. */
  4603. picomatch$1.parse = (pattern, options) => {
  4604. if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options));
  4605. return parse$1(pattern, { ...options, fastpaths: false });
  4606. };
  4607. /**
  4608. * Scan a glob pattern to separate the pattern into segments.
  4609. *
  4610. * ```js
  4611. * const picomatch = require('picomatch');
  4612. * // picomatch.scan(input[, options]);
  4613. *
  4614. * const result = picomatch.scan('!./foo/*.js');
  4615. * console.log(result);
  4616. * { prefix: '!./',
  4617. * input: '!./foo/*.js',
  4618. * start: 3,
  4619. * base: 'foo',
  4620. * glob: '*.js',
  4621. * isBrace: false,
  4622. * isBracket: false,
  4623. * isGlob: true,
  4624. * isExtglob: false,
  4625. * isGlobstar: false,
  4626. * negated: true }
  4627. * ```
  4628. * @param {String} `input` Glob pattern to scan.
  4629. * @param {Object} `options`
  4630. * @return {Object} Returns an object with
  4631. * @api public
  4632. */
  4633. picomatch$1.scan = (input, options) => scan(input, options);
  4634. /**
  4635. * Compile a regular expression from the `state` object returned by the
  4636. * [parse()](#parse) method.
  4637. *
  4638. * @param {Object} `state`
  4639. * @param {Object} `options`
  4640. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  4641. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  4642. * @return {RegExp}
  4643. * @api public
  4644. */
  4645. picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
  4646. if (returnOutput === true) {
  4647. return state.output;
  4648. }
  4649. const opts = options || {};
  4650. const prepend = opts.contains ? '' : '^';
  4651. const append = opts.contains ? '' : '$';
  4652. let source = `${prepend}(?:${state.output})${append}`;
  4653. if (state && state.negated === true) {
  4654. source = `^(?!${source}).*$`;
  4655. }
  4656. const regex = picomatch$1.toRegex(source, options);
  4657. if (returnState === true) {
  4658. regex.state = state;
  4659. }
  4660. return regex;
  4661. };
  4662. /**
  4663. * Create a regular expression from a parsed glob pattern.
  4664. *
  4665. * ```js
  4666. * const picomatch = require('picomatch');
  4667. * const state = picomatch.parse('*.js');
  4668. * // picomatch.compileRe(state[, options]);
  4669. *
  4670. * console.log(picomatch.compileRe(state));
  4671. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  4672. * ```
  4673. * @param {String} `state` The object returned from the `.parse` method.
  4674. * @param {Object} `options`
  4675. * @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.
  4676. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  4677. * @return {RegExp} Returns a regex created from the given pattern.
  4678. * @api public
  4679. */
  4680. picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  4681. if (!input || typeof input !== 'string') {
  4682. throw new TypeError('Expected a non-empty string');
  4683. }
  4684. let parsed = { negated: false, fastpaths: true };
  4685. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  4686. parsed.output = parse$1.fastpaths(input, options);
  4687. }
  4688. if (!parsed.output) {
  4689. parsed = parse$1(input, options);
  4690. }
  4691. return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
  4692. };
  4693. /**
  4694. * Create a regular expression from the given regex source string.
  4695. *
  4696. * ```js
  4697. * const picomatch = require('picomatch');
  4698. * // picomatch.toRegex(source[, options]);
  4699. *
  4700. * const { output } = picomatch.parse('*.js');
  4701. * console.log(picomatch.toRegex(output));
  4702. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  4703. * ```
  4704. * @param {String} `source` Regular expression source string.
  4705. * @param {Object} `options`
  4706. * @return {RegExp}
  4707. * @api public
  4708. */
  4709. picomatch$1.toRegex = (source, options) => {
  4710. try {
  4711. const opts = options || {};
  4712. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  4713. } catch (err) {
  4714. if (options && options.debug === true) throw err;
  4715. return /$^/;
  4716. }
  4717. };
  4718. /**
  4719. * Picomatch constants.
  4720. * @return {Object}
  4721. */
  4722. picomatch$1.constants = constants;
  4723. /**
  4724. * Expose "picomatch"
  4725. */
  4726. var picomatch_1 = picomatch$1;
  4727. var picomatch = picomatch_1;
  4728. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch);
  4729. const extractors = {
  4730. ArrayPattern(names, param) {
  4731. for (const element of param.elements) {
  4732. if (element)
  4733. extractors[element.type](names, element);
  4734. }
  4735. },
  4736. AssignmentPattern(names, param) {
  4737. extractors[param.left.type](names, param.left);
  4738. },
  4739. Identifier(names, param) {
  4740. names.push(param.name);
  4741. },
  4742. MemberExpression() { },
  4743. ObjectPattern(names, param) {
  4744. for (const prop of param.properties) {
  4745. // @ts-ignore Typescript reports that this is not a valid type
  4746. if (prop.type === 'RestElement') {
  4747. extractors.RestElement(names, prop);
  4748. }
  4749. else {
  4750. extractors[prop.value.type](names, prop.value);
  4751. }
  4752. }
  4753. },
  4754. RestElement(names, param) {
  4755. extractors[param.argument.type](names, param.argument);
  4756. }
  4757. };
  4758. const extractAssignedNames = function extractAssignedNames(param) {
  4759. const names = [];
  4760. extractors[param.type](names, param);
  4761. return names;
  4762. };
  4763. // Helper since Typescript can't detect readonly arrays with Array.isArray
  4764. function isArray$1(arg) {
  4765. return Array.isArray(arg);
  4766. }
  4767. function ensureArray(thing) {
  4768. if (isArray$1(thing))
  4769. return thing;
  4770. if (thing == null)
  4771. return [];
  4772. return [thing];
  4773. }
  4774. const normalizePath = function normalizePath(filename) {
  4775. return filename.split(require$$0$1.win32.sep).join(require$$0$1.posix.sep);
  4776. };
  4777. function getMatcherString(id, resolutionBase) {
  4778. if (resolutionBase === false || require$$0$1.isAbsolute(id) || id.startsWith('*')) {
  4779. return normalizePath(id);
  4780. }
  4781. // resolve('') is valid and will default to process.cwd()
  4782. const basePath = normalizePath(require$$0$1.resolve(resolutionBase || ''))
  4783. // escape all possible (posix + win) path characters that might interfere with regex
  4784. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  4785. // Note that we use posix.join because:
  4786. // 1. the basePath has been normalized to use /
  4787. // 2. the incoming glob (id) matcher, also uses /
  4788. // otherwise Node will force backslash (\) on windows
  4789. return require$$0$1.posix.join(basePath, normalizePath(id));
  4790. }
  4791. const createFilter = function createFilter(include, exclude, options) {
  4792. const resolutionBase = options && options.resolve;
  4793. const getMatcher = (id) => id instanceof RegExp
  4794. ? id
  4795. : {
  4796. test: (what) => {
  4797. // this refactor is a tad overly verbose but makes for easy debugging
  4798. const pattern = getMatcherString(id, resolutionBase);
  4799. const fn = pm(pattern, { dot: true });
  4800. const result = fn(what);
  4801. return result;
  4802. }
  4803. };
  4804. const includeMatchers = ensureArray(include).map(getMatcher);
  4805. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  4806. return function result(id) {
  4807. if (typeof id !== 'string')
  4808. return false;
  4809. if (/\0/.test(id))
  4810. return false;
  4811. const pathId = normalizePath(id);
  4812. for (let i = 0; i < excludeMatchers.length; ++i) {
  4813. const matcher = excludeMatchers[i];
  4814. if (matcher.test(pathId))
  4815. return false;
  4816. }
  4817. for (let i = 0; i < includeMatchers.length; ++i) {
  4818. const matcher = includeMatchers[i];
  4819. if (matcher.test(pathId))
  4820. return true;
  4821. }
  4822. return !includeMatchers.length;
  4823. };
  4824. };
  4825. 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';
  4826. 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';
  4827. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins}`.split(' '));
  4828. forbiddenIdentifiers.add('');
  4829. function createInclusionContext() {
  4830. return {
  4831. brokenFlow: false,
  4832. hasBreak: false,
  4833. hasContinue: false,
  4834. includedCallArguments: new Set(),
  4835. includedLabels: new Set()
  4836. };
  4837. }
  4838. function createHasEffectsContext() {
  4839. return {
  4840. accessed: new PathTracker(),
  4841. assigned: new PathTracker(),
  4842. brokenFlow: false,
  4843. called: new DiscriminatedPathTracker(),
  4844. hasBreak: false,
  4845. hasContinue: false,
  4846. ignore: {
  4847. breaks: false,
  4848. continues: false,
  4849. labels: new Set(),
  4850. returnYield: false,
  4851. this: false
  4852. },
  4853. includedLabels: new Set(),
  4854. instantiated: new DiscriminatedPathTracker(),
  4855. replacedVariableInits: new Map()
  4856. };
  4857. }
  4858. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  4859. return Object.create(inheritedDescriptions, memberDescriptions);
  4860. }
  4861. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  4862. getLiteralValueAtPath() {
  4863. return undefined;
  4864. }
  4865. })();
  4866. const returnsUnknown = {
  4867. value: {
  4868. hasEffectsWhenCalled: null,
  4869. returns: UNKNOWN_EXPRESSION
  4870. }
  4871. };
  4872. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  4873. getReturnExpressionWhenCalledAtPath(path) {
  4874. if (path.length === 1) {
  4875. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  4876. }
  4877. return UNKNOWN_RETURN_EXPRESSION;
  4878. }
  4879. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4880. if (interaction.type === INTERACTION_ACCESSED) {
  4881. return path.length > 1;
  4882. }
  4883. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4884. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  4885. }
  4886. return true;
  4887. }
  4888. })();
  4889. const returnsBoolean = {
  4890. value: {
  4891. hasEffectsWhenCalled: null,
  4892. returns: UNKNOWN_LITERAL_BOOLEAN
  4893. }
  4894. };
  4895. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  4896. getReturnExpressionWhenCalledAtPath(path) {
  4897. if (path.length === 1) {
  4898. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  4899. }
  4900. return UNKNOWN_RETURN_EXPRESSION;
  4901. }
  4902. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4903. if (interaction.type === INTERACTION_ACCESSED) {
  4904. return path.length > 1;
  4905. }
  4906. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4907. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  4908. }
  4909. return true;
  4910. }
  4911. })();
  4912. const returnsNumber = {
  4913. value: {
  4914. hasEffectsWhenCalled: null,
  4915. returns: UNKNOWN_LITERAL_NUMBER
  4916. }
  4917. };
  4918. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  4919. getReturnExpressionWhenCalledAtPath(path) {
  4920. if (path.length === 1) {
  4921. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  4922. }
  4923. return UNKNOWN_RETURN_EXPRESSION;
  4924. }
  4925. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4926. if (interaction.type === INTERACTION_ACCESSED) {
  4927. return path.length > 1;
  4928. }
  4929. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4930. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  4931. }
  4932. return true;
  4933. }
  4934. })();
  4935. const returnsString = {
  4936. value: {
  4937. hasEffectsWhenCalled: null,
  4938. returns: UNKNOWN_LITERAL_STRING
  4939. }
  4940. };
  4941. const stringReplace = {
  4942. value: {
  4943. hasEffectsWhenCalled({ args }, context) {
  4944. const argument1 = args[2];
  4945. return (args.length < 3 ||
  4946. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  4947. deoptimizeCache() { }
  4948. }) === 'symbol' &&
  4949. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  4950. },
  4951. returns: UNKNOWN_LITERAL_STRING
  4952. }
  4953. };
  4954. const objectMembers = assembleMemberDescriptions({
  4955. hasOwnProperty: returnsBoolean,
  4956. isPrototypeOf: returnsBoolean,
  4957. propertyIsEnumerable: returnsBoolean,
  4958. toLocaleString: returnsString,
  4959. toString: returnsString,
  4960. valueOf: returnsUnknown
  4961. });
  4962. const literalBooleanMembers = assembleMemberDescriptions({
  4963. valueOf: returnsBoolean
  4964. }, objectMembers);
  4965. const literalNumberMembers = assembleMemberDescriptions({
  4966. toExponential: returnsString,
  4967. toFixed: returnsString,
  4968. toLocaleString: returnsString,
  4969. toPrecision: returnsString,
  4970. valueOf: returnsNumber
  4971. }, objectMembers);
  4972. /**
  4973. * RegExp are stateful when they have the global or sticky flags set.
  4974. * But if we actually don't use them, the side effect does not matter.
  4975. * the check logic in `hasEffectsOnInteractionAtPath`.
  4976. */
  4977. const literalRegExpMembers = assembleMemberDescriptions({
  4978. exec: returnsUnknown,
  4979. test: returnsBoolean
  4980. }, objectMembers);
  4981. const literalStringMembers = assembleMemberDescriptions({
  4982. anchor: returnsString,
  4983. at: returnsUnknown,
  4984. big: returnsString,
  4985. blink: returnsString,
  4986. bold: returnsString,
  4987. charAt: returnsString,
  4988. charCodeAt: returnsNumber,
  4989. codePointAt: returnsUnknown,
  4990. concat: returnsString,
  4991. endsWith: returnsBoolean,
  4992. fixed: returnsString,
  4993. fontcolor: returnsString,
  4994. fontsize: returnsString,
  4995. includes: returnsBoolean,
  4996. indexOf: returnsNumber,
  4997. italics: returnsString,
  4998. lastIndexOf: returnsNumber,
  4999. link: returnsString,
  5000. localeCompare: returnsNumber,
  5001. match: returnsUnknown,
  5002. matchAll: returnsUnknown,
  5003. normalize: returnsString,
  5004. padEnd: returnsString,
  5005. padStart: returnsString,
  5006. repeat: returnsString,
  5007. replace: stringReplace,
  5008. replaceAll: stringReplace,
  5009. search: returnsNumber,
  5010. slice: returnsString,
  5011. small: returnsString,
  5012. split: returnsUnknown,
  5013. startsWith: returnsBoolean,
  5014. strike: returnsString,
  5015. sub: returnsString,
  5016. substr: returnsString,
  5017. substring: returnsString,
  5018. sup: returnsString,
  5019. toLocaleLowerCase: returnsString,
  5020. toLocaleUpperCase: returnsString,
  5021. toLowerCase: returnsString,
  5022. toString: returnsString,
  5023. toUpperCase: returnsString,
  5024. trim: returnsString,
  5025. trimEnd: returnsString,
  5026. trimLeft: returnsString,
  5027. trimRight: returnsString,
  5028. trimStart: returnsString,
  5029. valueOf: returnsString
  5030. }, objectMembers);
  5031. function getLiteralMembersForValue(value) {
  5032. if (value instanceof RegExp) {
  5033. return literalRegExpMembers;
  5034. }
  5035. switch (typeof value) {
  5036. case 'boolean': {
  5037. return literalBooleanMembers;
  5038. }
  5039. case 'number': {
  5040. return literalNumberMembers;
  5041. }
  5042. case 'string': {
  5043. return literalStringMembers;
  5044. }
  5045. }
  5046. return Object.create(null);
  5047. }
  5048. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  5049. if (typeof memberName !== 'string' || !members[memberName]) {
  5050. return true;
  5051. }
  5052. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  5053. }
  5054. function getMemberReturnExpressionWhenCalled(members, memberName) {
  5055. if (typeof memberName !== 'string' || !members[memberName])
  5056. return UNKNOWN_RETURN_EXPRESSION;
  5057. return [members[memberName].returns, false];
  5058. }
  5059. // AST walker module for Mozilla Parser API compatible trees
  5060. function skipThrough(node, st, c) { c(node, st); }
  5061. function ignore(_node, _st, _c) {}
  5062. // Node walkers.
  5063. var base$1 = {};
  5064. base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {
  5065. for (var i = 0, list = node.body; i < list.length; i += 1)
  5066. {
  5067. var stmt = list[i];
  5068. c(stmt, st, "Statement");
  5069. }
  5070. };
  5071. base$1.Statement = skipThrough;
  5072. base$1.EmptyStatement = ignore;
  5073. base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
  5074. function (node, st, c) { return c(node.expression, st, "Expression"); };
  5075. base$1.IfStatement = function (node, st, c) {
  5076. c(node.test, st, "Expression");
  5077. c(node.consequent, st, "Statement");
  5078. if (node.alternate) { c(node.alternate, st, "Statement"); }
  5079. };
  5080. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  5081. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  5082. base$1.WithStatement = function (node, st, c) {
  5083. c(node.object, st, "Expression");
  5084. c(node.body, st, "Statement");
  5085. };
  5086. base$1.SwitchStatement = function (node, st, c) {
  5087. c(node.discriminant, st, "Expression");
  5088. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  5089. var cs = list$1[i$1];
  5090. if (cs.test) { c(cs.test, st, "Expression"); }
  5091. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  5092. {
  5093. var cons = list[i];
  5094. c(cons, st, "Statement");
  5095. }
  5096. }
  5097. };
  5098. base$1.SwitchCase = function (node, st, c) {
  5099. if (node.test) { c(node.test, st, "Expression"); }
  5100. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  5101. {
  5102. var cons = list[i];
  5103. c(cons, st, "Statement");
  5104. }
  5105. };
  5106. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  5107. if (node.argument) { c(node.argument, st, "Expression"); }
  5108. };
  5109. base$1.ThrowStatement = base$1.SpreadElement =
  5110. function (node, st, c) { return c(node.argument, st, "Expression"); };
  5111. base$1.TryStatement = function (node, st, c) {
  5112. c(node.block, st, "Statement");
  5113. if (node.handler) { c(node.handler, st); }
  5114. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  5115. };
  5116. base$1.CatchClause = function (node, st, c) {
  5117. if (node.param) { c(node.param, st, "Pattern"); }
  5118. c(node.body, st, "Statement");
  5119. };
  5120. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  5121. c(node.test, st, "Expression");
  5122. c(node.body, st, "Statement");
  5123. };
  5124. base$1.ForStatement = function (node, st, c) {
  5125. if (node.init) { c(node.init, st, "ForInit"); }
  5126. if (node.test) { c(node.test, st, "Expression"); }
  5127. if (node.update) { c(node.update, st, "Expression"); }
  5128. c(node.body, st, "Statement");
  5129. };
  5130. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  5131. c(node.left, st, "ForInit");
  5132. c(node.right, st, "Expression");
  5133. c(node.body, st, "Statement");
  5134. };
  5135. base$1.ForInit = function (node, st, c) {
  5136. if (node.type === "VariableDeclaration") { c(node, st); }
  5137. else { c(node, st, "Expression"); }
  5138. };
  5139. base$1.DebuggerStatement = ignore;
  5140. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  5141. base$1.VariableDeclaration = function (node, st, c) {
  5142. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  5143. {
  5144. var decl = list[i];
  5145. c(decl, st);
  5146. }
  5147. };
  5148. base$1.VariableDeclarator = function (node, st, c) {
  5149. c(node.id, st, "Pattern");
  5150. if (node.init) { c(node.init, st, "Expression"); }
  5151. };
  5152. base$1.Function = function (node, st, c) {
  5153. if (node.id) { c(node.id, st, "Pattern"); }
  5154. for (var i = 0, list = node.params; i < list.length; i += 1)
  5155. {
  5156. var param = list[i];
  5157. c(param, st, "Pattern");
  5158. }
  5159. c(node.body, st, node.expression ? "Expression" : "Statement");
  5160. };
  5161. base$1.Pattern = function (node, st, c) {
  5162. if (node.type === "Identifier")
  5163. { c(node, st, "VariablePattern"); }
  5164. else if (node.type === "MemberExpression")
  5165. { c(node, st, "MemberPattern"); }
  5166. else
  5167. { c(node, st); }
  5168. };
  5169. base$1.VariablePattern = ignore;
  5170. base$1.MemberPattern = skipThrough;
  5171. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  5172. base$1.ArrayPattern = function (node, st, c) {
  5173. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  5174. var elt = list[i];
  5175. if (elt) { c(elt, st, "Pattern"); }
  5176. }
  5177. };
  5178. base$1.ObjectPattern = function (node, st, c) {
  5179. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  5180. var prop = list[i];
  5181. if (prop.type === "Property") {
  5182. if (prop.computed) { c(prop.key, st, "Expression"); }
  5183. c(prop.value, st, "Pattern");
  5184. } else if (prop.type === "RestElement") {
  5185. c(prop.argument, st, "Pattern");
  5186. }
  5187. }
  5188. };
  5189. base$1.Expression = skipThrough;
  5190. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  5191. base$1.ArrayExpression = function (node, st, c) {
  5192. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  5193. var elt = list[i];
  5194. if (elt) { c(elt, st, "Expression"); }
  5195. }
  5196. };
  5197. base$1.ObjectExpression = function (node, st, c) {
  5198. for (var i = 0, list = node.properties; i < list.length; i += 1)
  5199. {
  5200. var prop = list[i];
  5201. c(prop, st);
  5202. }
  5203. };
  5204. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  5205. base$1.SequenceExpression = function (node, st, c) {
  5206. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  5207. {
  5208. var expr = list[i];
  5209. c(expr, st, "Expression");
  5210. }
  5211. };
  5212. base$1.TemplateLiteral = function (node, st, c) {
  5213. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  5214. {
  5215. var quasi = list[i];
  5216. c(quasi, st);
  5217. }
  5218. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  5219. {
  5220. var expr = list$1[i$1];
  5221. c(expr, st, "Expression");
  5222. }
  5223. };
  5224. base$1.TemplateElement = ignore;
  5225. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  5226. c(node.argument, st, "Expression");
  5227. };
  5228. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  5229. c(node.left, st, "Expression");
  5230. c(node.right, st, "Expression");
  5231. };
  5232. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  5233. c(node.left, st, "Pattern");
  5234. c(node.right, st, "Expression");
  5235. };
  5236. base$1.ConditionalExpression = function (node, st, c) {
  5237. c(node.test, st, "Expression");
  5238. c(node.consequent, st, "Expression");
  5239. c(node.alternate, st, "Expression");
  5240. };
  5241. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  5242. c(node.callee, st, "Expression");
  5243. if (node.arguments)
  5244. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  5245. {
  5246. var arg = list[i];
  5247. c(arg, st, "Expression");
  5248. } }
  5249. };
  5250. base$1.MemberExpression = function (node, st, c) {
  5251. c(node.object, st, "Expression");
  5252. if (node.computed) { c(node.property, st, "Expression"); }
  5253. };
  5254. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  5255. if (node.declaration)
  5256. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  5257. if (node.source) { c(node.source, st, "Expression"); }
  5258. };
  5259. base$1.ExportAllDeclaration = function (node, st, c) {
  5260. if (node.exported)
  5261. { c(node.exported, st); }
  5262. c(node.source, st, "Expression");
  5263. };
  5264. base$1.ImportDeclaration = function (node, st, c) {
  5265. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  5266. {
  5267. var spec = list[i];
  5268. c(spec, st);
  5269. }
  5270. c(node.source, st, "Expression");
  5271. };
  5272. base$1.ImportExpression = function (node, st, c) {
  5273. c(node.source, st, "Expression");
  5274. };
  5275. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
  5276. base$1.TaggedTemplateExpression = function (node, st, c) {
  5277. c(node.tag, st, "Expression");
  5278. c(node.quasi, st, "Expression");
  5279. };
  5280. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  5281. base$1.Class = function (node, st, c) {
  5282. if (node.id) { c(node.id, st, "Pattern"); }
  5283. if (node.superClass) { c(node.superClass, st, "Expression"); }
  5284. c(node.body, st);
  5285. };
  5286. base$1.ClassBody = function (node, st, c) {
  5287. for (var i = 0, list = node.body; i < list.length; i += 1)
  5288. {
  5289. var elt = list[i];
  5290. c(elt, st);
  5291. }
  5292. };
  5293. base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
  5294. if (node.computed) { c(node.key, st, "Expression"); }
  5295. if (node.value) { c(node.value, st, "Expression"); }
  5296. };
  5297. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  5298. const BinaryExpression$1 = 'BinaryExpression';
  5299. const BlockStatement$1 = 'BlockStatement';
  5300. const CallExpression$1 = 'CallExpression';
  5301. const ChainExpression$1 = 'ChainExpression';
  5302. const ConditionalExpression$1 = 'ConditionalExpression';
  5303. const ExpressionStatement$1 = 'ExpressionStatement';
  5304. const Identifier$1 = 'Identifier';
  5305. const LogicalExpression$1 = 'LogicalExpression';
  5306. const NewExpression$1 = 'NewExpression';
  5307. const Program$1 = 'Program';
  5308. const Property$1 = 'Property';
  5309. const ReturnStatement$1 = 'ReturnStatement';
  5310. const SequenceExpression$1 = 'SequenceExpression';
  5311. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  5312. // this for an actual sourceMappingURL
  5313. let SOURCEMAPPING_URL = 'sourceMa';
  5314. SOURCEMAPPING_URL += 'ppingURL';
  5315. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  5316. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
  5317. const ANNOTATION_KEY = '_rollupAnnotations';
  5318. const INVALID_COMMENT_KEY = '_rollupRemoved';
  5319. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  5320. const { annotations, code } = state;
  5321. // eslint-disable-next-line unicorn/consistent-destructuring
  5322. let comment = annotations[state.annotationIndex];
  5323. while (comment && node.start >= comment.end) {
  5324. markPureNode(node, comment, code);
  5325. comment = annotations[++state.annotationIndex];
  5326. }
  5327. if (comment && comment.end <= node.end) {
  5328. base$1[type](node, state, handlePureAnnotationsOfNode);
  5329. // eslint-disable-next-line unicorn/consistent-destructuring
  5330. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  5331. ++state.annotationIndex;
  5332. annotateNode(node, comment, false);
  5333. }
  5334. }
  5335. }
  5336. const neitherWithespaceNorBrackets = /[^\s(]/g;
  5337. const noWhitespace = /\S/g;
  5338. function markPureNode(node, comment, code) {
  5339. const annotatedNodes = [];
  5340. let invalidAnnotation;
  5341. const codeInBetween = code.slice(comment.end, node.start);
  5342. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  5343. const parentStart = node.start;
  5344. while (true) {
  5345. annotatedNodes.push(node);
  5346. switch (node.type) {
  5347. case ExpressionStatement$1:
  5348. case ChainExpression$1: {
  5349. node = node.expression;
  5350. continue;
  5351. }
  5352. case SequenceExpression$1: {
  5353. // if there are parentheses, the annotation would apply to the entire expression
  5354. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  5355. node = node.expressions[0];
  5356. continue;
  5357. }
  5358. invalidAnnotation = true;
  5359. break;
  5360. }
  5361. case ConditionalExpression$1: {
  5362. // if there are parentheses, the annotation would apply to the entire expression
  5363. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  5364. node = node.test;
  5365. continue;
  5366. }
  5367. invalidAnnotation = true;
  5368. break;
  5369. }
  5370. case LogicalExpression$1:
  5371. case BinaryExpression$1: {
  5372. // if there are parentheses, the annotation would apply to the entire expression
  5373. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  5374. node = node.left;
  5375. continue;
  5376. }
  5377. invalidAnnotation = true;
  5378. break;
  5379. }
  5380. case CallExpression$1:
  5381. case NewExpression$1: {
  5382. break;
  5383. }
  5384. default: {
  5385. invalidAnnotation = true;
  5386. }
  5387. }
  5388. break;
  5389. }
  5390. }
  5391. else {
  5392. invalidAnnotation = true;
  5393. }
  5394. if (invalidAnnotation) {
  5395. annotateNode(node, comment, false);
  5396. }
  5397. else {
  5398. for (const node of annotatedNodes) {
  5399. annotateNode(node, comment, true);
  5400. }
  5401. }
  5402. }
  5403. function doesNotMatchOutsideComment(code, forbiddenChars) {
  5404. let nextMatch;
  5405. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  5406. if (nextMatch[0] === '/') {
  5407. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  5408. if (charCodeAfterSlash === 42 /*"*"*/) {
  5409. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  5410. continue;
  5411. }
  5412. else if (charCodeAfterSlash === 47 /*"/"*/) {
  5413. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  5414. continue;
  5415. }
  5416. }
  5417. forbiddenChars.lastIndex = 0;
  5418. return false;
  5419. }
  5420. return true;
  5421. }
  5422. const pureCommentRegex = /[#@]__PURE__/;
  5423. function addAnnotations(comments, esTreeAst, code) {
  5424. const annotations = [];
  5425. const sourceMappingComments = [];
  5426. for (const comment of comments) {
  5427. if (pureCommentRegex.test(comment.value)) {
  5428. annotations.push(comment);
  5429. }
  5430. else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  5431. sourceMappingComments.push(comment);
  5432. }
  5433. }
  5434. for (const comment of sourceMappingComments) {
  5435. annotateNode(esTreeAst, comment, false);
  5436. }
  5437. handlePureAnnotationsOfNode(esTreeAst, {
  5438. annotationIndex: 0,
  5439. annotations,
  5440. code
  5441. });
  5442. }
  5443. function annotateNode(node, comment, valid) {
  5444. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  5445. const property = node[key];
  5446. if (property) {
  5447. property.push(comment);
  5448. }
  5449. else {
  5450. node[key] = [comment];
  5451. }
  5452. }
  5453. const keys = {
  5454. // TODO this should be removed once ImportExpression follows official ESTree
  5455. // specs with "null" as default
  5456. ImportExpression: ['arguments'],
  5457. Literal: [],
  5458. Program: ['body']
  5459. };
  5460. function getAndCreateKeys(esTreeNode) {
  5461. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  5462. return keys[esTreeNode.type];
  5463. }
  5464. const INCLUDE_PARAMETERS = 'variables';
  5465. class NodeBase extends ExpressionEntity {
  5466. constructor(esTreeNode, parent, parentScope, keepEsTreeNode = false) {
  5467. super();
  5468. /**
  5469. * Nodes can apply custom deoptimizations once they become part of the
  5470. * executed code. To do this, they must initialize this as false, implement
  5471. * applyDeoptimizations and call this from include and hasEffects if they have
  5472. * custom handlers
  5473. */
  5474. this.deoptimized = false;
  5475. // Nodes can opt-in to keep the AST if needed during the build pipeline.
  5476. // Avoid true when possible as large AST takes up memory.
  5477. this.esTreeNode = keepEsTreeNode ? esTreeNode : null;
  5478. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  5479. this.parent = parent;
  5480. this.context = parent.context;
  5481. this.createScope(parentScope);
  5482. this.parseNode(esTreeNode);
  5483. this.initialise();
  5484. this.context.magicString.addSourcemapLocation(this.start);
  5485. this.context.magicString.addSourcemapLocation(this.end);
  5486. }
  5487. addExportedVariables(_variables, _exportNamesByVariable) { }
  5488. /**
  5489. * Override this to bind assignments to variables and do any initialisations
  5490. * that require the scopes to be populated with variables.
  5491. */
  5492. bind() {
  5493. for (const key of this.keys) {
  5494. const value = this[key];
  5495. if (Array.isArray(value)) {
  5496. for (const child of value) {
  5497. child?.bind();
  5498. }
  5499. }
  5500. else if (value) {
  5501. value.bind();
  5502. }
  5503. }
  5504. }
  5505. /**
  5506. * Override if this node should receive a different scope than the parent
  5507. * scope.
  5508. */
  5509. createScope(parentScope) {
  5510. this.scope = parentScope;
  5511. }
  5512. hasEffects(context) {
  5513. if (!this.deoptimized)
  5514. this.applyDeoptimizations();
  5515. for (const key of this.keys) {
  5516. const value = this[key];
  5517. if (value === null)
  5518. continue;
  5519. if (Array.isArray(value)) {
  5520. for (const child of value) {
  5521. if (child?.hasEffects(context))
  5522. return true;
  5523. }
  5524. }
  5525. else if (value.hasEffects(context))
  5526. return true;
  5527. }
  5528. return false;
  5529. }
  5530. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  5531. return (this.hasEffects(context) ||
  5532. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  5533. }
  5534. include(context, includeChildrenRecursively, _options) {
  5535. if (!this.deoptimized)
  5536. this.applyDeoptimizations();
  5537. this.included = true;
  5538. for (const key of this.keys) {
  5539. const value = this[key];
  5540. if (value === null)
  5541. continue;
  5542. if (Array.isArray(value)) {
  5543. for (const child of value) {
  5544. child?.include(context, includeChildrenRecursively);
  5545. }
  5546. }
  5547. else {
  5548. value.include(context, includeChildrenRecursively);
  5549. }
  5550. }
  5551. }
  5552. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  5553. this.include(context, includeChildrenRecursively);
  5554. }
  5555. /**
  5556. * Override to perform special initialisation steps after the scope is
  5557. * initialised
  5558. */
  5559. initialise() { }
  5560. insertSemicolon(code) {
  5561. if (code.original[this.end - 1] !== ';') {
  5562. code.appendLeft(this.end, ';');
  5563. }
  5564. }
  5565. parseNode(esTreeNode, keepEsTreeNodeKeys) {
  5566. for (const [key, value] of Object.entries(esTreeNode)) {
  5567. // That way, we can override this function to add custom initialisation and then call super.parseNode
  5568. if (this.hasOwnProperty(key))
  5569. continue;
  5570. if (key.charCodeAt(0) === 95 /* _ */) {
  5571. if (key === ANNOTATION_KEY) {
  5572. this.annotations = value;
  5573. }
  5574. else if (key === INVALID_COMMENT_KEY) {
  5575. for (const { start, end } of value)
  5576. this.context.magicString.remove(start, end);
  5577. }
  5578. }
  5579. else if (typeof value !== 'object' || value === null) {
  5580. this[key] = value;
  5581. }
  5582. else if (Array.isArray(value)) {
  5583. this[key] = [];
  5584. for (const child of value) {
  5585. this[key].push(child === null
  5586. ? null
  5587. : new (this.context.getNodeConstructor(child.type))(child, this, this.scope, keepEsTreeNodeKeys?.includes(key)));
  5588. }
  5589. }
  5590. else {
  5591. this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope, keepEsTreeNodeKeys?.includes(key));
  5592. }
  5593. }
  5594. }
  5595. render(code, options) {
  5596. for (const key of this.keys) {
  5597. const value = this[key];
  5598. if (value === null)
  5599. continue;
  5600. if (Array.isArray(value)) {
  5601. for (const child of value) {
  5602. child?.render(code, options);
  5603. }
  5604. }
  5605. else {
  5606. value.render(code, options);
  5607. }
  5608. }
  5609. }
  5610. setAssignedValue(value) {
  5611. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  5612. }
  5613. shouldBeIncluded(context) {
  5614. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  5615. }
  5616. /**
  5617. * Just deoptimize everything by default so that when e.g. we do not track
  5618. * something properly, it is deoptimized.
  5619. * @protected
  5620. */
  5621. applyDeoptimizations() {
  5622. this.deoptimized = true;
  5623. for (const key of this.keys) {
  5624. const value = this[key];
  5625. if (value === null)
  5626. continue;
  5627. if (Array.isArray(value)) {
  5628. for (const child of value) {
  5629. child?.deoptimizePath(UNKNOWN_PATH);
  5630. }
  5631. }
  5632. else {
  5633. value.deoptimizePath(UNKNOWN_PATH);
  5634. }
  5635. }
  5636. this.context.requestTreeshakingPass();
  5637. }
  5638. }
  5639. class SpreadElement extends NodeBase {
  5640. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5641. if (path.length > 0) {
  5642. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  5643. }
  5644. }
  5645. hasEffects(context) {
  5646. if (!this.deoptimized)
  5647. this.applyDeoptimizations();
  5648. const { propertyReadSideEffects } = this.context.options
  5649. .treeshake;
  5650. return (this.argument.hasEffects(context) ||
  5651. (propertyReadSideEffects &&
  5652. (propertyReadSideEffects === 'always' ||
  5653. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  5654. }
  5655. applyDeoptimizations() {
  5656. this.deoptimized = true;
  5657. // Only properties of properties of the argument could become subject to reassignment
  5658. // This will also reassign the return values of iterators
  5659. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  5660. this.context.requestTreeshakingPass();
  5661. }
  5662. }
  5663. class Method extends ExpressionEntity {
  5664. constructor(description) {
  5665. super();
  5666. this.description = description;
  5667. }
  5668. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  5669. if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  5670. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  5671. }
  5672. }
  5673. getReturnExpressionWhenCalledAtPath(path, { args }) {
  5674. if (path.length > 0) {
  5675. return UNKNOWN_RETURN_EXPRESSION;
  5676. }
  5677. return [
  5678. this.description.returnsPrimitive ||
  5679. (this.description.returns === 'self'
  5680. ? args[0] || UNKNOWN_EXPRESSION
  5681. : this.description.returns()),
  5682. false
  5683. ];
  5684. }
  5685. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5686. const { type } = interaction;
  5687. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  5688. return true;
  5689. }
  5690. if (type === INTERACTION_CALLED) {
  5691. const { args } = interaction;
  5692. if (this.description.mutatesSelfAsArray === true &&
  5693. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  5694. return true;
  5695. }
  5696. if (this.description.callsArgs) {
  5697. for (const argumentIndex of this.description.callsArgs) {
  5698. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  5699. return true;
  5700. }
  5701. }
  5702. }
  5703. }
  5704. return false;
  5705. }
  5706. }
  5707. const METHOD_RETURNS_BOOLEAN = [
  5708. new Method({
  5709. callsArgs: null,
  5710. mutatesSelfAsArray: false,
  5711. returns: null,
  5712. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  5713. })
  5714. ];
  5715. const METHOD_RETURNS_STRING = [
  5716. new Method({
  5717. callsArgs: null,
  5718. mutatesSelfAsArray: false,
  5719. returns: null,
  5720. returnsPrimitive: UNKNOWN_LITERAL_STRING
  5721. })
  5722. ];
  5723. const METHOD_RETURNS_NUMBER = [
  5724. new Method({
  5725. callsArgs: null,
  5726. mutatesSelfAsArray: false,
  5727. returns: null,
  5728. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5729. })
  5730. ];
  5731. const METHOD_RETURNS_UNKNOWN = [
  5732. new Method({
  5733. callsArgs: null,
  5734. mutatesSelfAsArray: false,
  5735. returns: null,
  5736. returnsPrimitive: UNKNOWN_EXPRESSION
  5737. })
  5738. ];
  5739. const INTEGER_REG_EXP = /^\d+$/;
  5740. class ObjectEntity extends ExpressionEntity {
  5741. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  5742. // and we assume there are no setters or getters
  5743. constructor(properties, prototypeExpression, immutable = false) {
  5744. super();
  5745. this.prototypeExpression = prototypeExpression;
  5746. this.immutable = immutable;
  5747. this.additionalExpressionsToBeDeoptimized = new Set();
  5748. this.allProperties = [];
  5749. this.deoptimizedPaths = Object.create(null);
  5750. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  5751. this.gettersByKey = Object.create(null);
  5752. this.hasLostTrack = false;
  5753. this.hasUnknownDeoptimizedInteger = false;
  5754. this.hasUnknownDeoptimizedProperty = false;
  5755. this.propertiesAndGettersByKey = Object.create(null);
  5756. this.propertiesAndSettersByKey = Object.create(null);
  5757. this.settersByKey = Object.create(null);
  5758. this.unknownIntegerProps = [];
  5759. this.unmatchableGetters = [];
  5760. this.unmatchablePropertiesAndGetters = [];
  5761. this.unmatchableSetters = [];
  5762. if (Array.isArray(properties)) {
  5763. this.buildPropertyMaps(properties);
  5764. }
  5765. else {
  5766. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  5767. for (const propertiesForKey of Object.values(properties)) {
  5768. this.allProperties.push(...propertiesForKey);
  5769. }
  5770. }
  5771. }
  5772. deoptimizeAllProperties(noAccessors) {
  5773. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  5774. if (noAccessors) {
  5775. this.hasUnknownDeoptimizedProperty = true;
  5776. }
  5777. else {
  5778. this.hasLostTrack = true;
  5779. }
  5780. if (isDeoptimized) {
  5781. return;
  5782. }
  5783. for (const properties of [
  5784. ...Object.values(this.propertiesAndGettersByKey),
  5785. ...Object.values(this.settersByKey)
  5786. ]) {
  5787. for (const property of properties) {
  5788. property.deoptimizePath(UNKNOWN_PATH);
  5789. }
  5790. }
  5791. // While the prototype itself cannot be mutated, each property can
  5792. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  5793. this.deoptimizeCachedEntities();
  5794. }
  5795. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5796. const [key, ...subPath] = path;
  5797. const { args, type } = interaction;
  5798. if (this.hasLostTrack ||
  5799. // single paths that are deoptimized will not become getters or setters
  5800. ((type === INTERACTION_CALLED || path.length > 1) &&
  5801. (this.hasUnknownDeoptimizedProperty ||
  5802. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  5803. deoptimizeInteraction(interaction);
  5804. return;
  5805. }
  5806. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  5807. ? [
  5808. this.propertiesAndGettersByKey,
  5809. this.propertiesAndGettersByKey,
  5810. this.unmatchablePropertiesAndGetters
  5811. ]
  5812. : type === INTERACTION_ACCESSED
  5813. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5814. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5815. if (typeof key === 'string') {
  5816. if (propertiesForExactMatchByKey[key]) {
  5817. const properties = relevantPropertiesByKey[key];
  5818. if (properties) {
  5819. for (const property of properties) {
  5820. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  5821. }
  5822. }
  5823. if (!this.immutable) {
  5824. for (const argument of args) {
  5825. if (argument) {
  5826. this.additionalExpressionsToBeDeoptimized.add(argument);
  5827. }
  5828. }
  5829. }
  5830. return;
  5831. }
  5832. for (const property of relevantUnmatchableProperties) {
  5833. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  5834. }
  5835. if (INTEGER_REG_EXP.test(key)) {
  5836. for (const property of this.unknownIntegerProps) {
  5837. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  5838. }
  5839. }
  5840. }
  5841. else {
  5842. for (const properties of [
  5843. ...Object.values(relevantPropertiesByKey),
  5844. relevantUnmatchableProperties
  5845. ]) {
  5846. for (const property of properties) {
  5847. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  5848. }
  5849. }
  5850. for (const property of this.unknownIntegerProps) {
  5851. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  5852. }
  5853. }
  5854. if (!this.immutable) {
  5855. for (const argument of args) {
  5856. if (argument) {
  5857. this.additionalExpressionsToBeDeoptimized.add(argument);
  5858. }
  5859. }
  5860. }
  5861. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5862. }
  5863. deoptimizeIntegerProperties() {
  5864. if (this.hasLostTrack ||
  5865. this.hasUnknownDeoptimizedProperty ||
  5866. this.hasUnknownDeoptimizedInteger) {
  5867. return;
  5868. }
  5869. this.hasUnknownDeoptimizedInteger = true;
  5870. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  5871. if (INTEGER_REG_EXP.test(key)) {
  5872. for (const property of propertiesAndGetters) {
  5873. property.deoptimizePath(UNKNOWN_PATH);
  5874. }
  5875. }
  5876. }
  5877. this.deoptimizeCachedIntegerEntities();
  5878. }
  5879. // Assumption: If only a specific path is deoptimized, no accessors are created
  5880. deoptimizePath(path) {
  5881. if (this.hasLostTrack || this.immutable) {
  5882. return;
  5883. }
  5884. const key = path[0];
  5885. if (path.length === 1) {
  5886. if (typeof key !== 'string') {
  5887. if (key === UnknownInteger) {
  5888. return this.deoptimizeIntegerProperties();
  5889. }
  5890. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  5891. }
  5892. if (!this.deoptimizedPaths[key]) {
  5893. this.deoptimizedPaths[key] = true;
  5894. // we only deoptimizeCache exact matches as in all other cases,
  5895. // we do not return a literal value or return expression
  5896. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  5897. if (expressionsToBeDeoptimized) {
  5898. for (const expression of expressionsToBeDeoptimized) {
  5899. expression.deoptimizeCache();
  5900. }
  5901. }
  5902. }
  5903. }
  5904. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  5905. for (const property of typeof key === 'string'
  5906. ? [
  5907. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  5908. ...(this.settersByKey[key] || this.unmatchableSetters)
  5909. ]
  5910. : this.allProperties) {
  5911. property.deoptimizePath(subPath);
  5912. }
  5913. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  5914. }
  5915. getLiteralValueAtPath(path, recursionTracker, origin) {
  5916. if (path.length === 0) {
  5917. return UnknownTruthyValue;
  5918. }
  5919. const key = path[0];
  5920. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  5921. if (expressionAtPath) {
  5922. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  5923. }
  5924. if (this.prototypeExpression) {
  5925. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  5926. }
  5927. if (path.length === 1) {
  5928. return undefined;
  5929. }
  5930. return UnknownValue;
  5931. }
  5932. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5933. if (path.length === 0) {
  5934. return UNKNOWN_RETURN_EXPRESSION;
  5935. }
  5936. const [key, ...subPath] = path;
  5937. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  5938. if (expressionAtPath) {
  5939. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  5940. }
  5941. if (this.prototypeExpression) {
  5942. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5943. }
  5944. return UNKNOWN_RETURN_EXPRESSION;
  5945. }
  5946. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5947. const [key, ...subPath] = path;
  5948. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  5949. const expressionAtPath = this.getMemberExpression(key);
  5950. if (expressionAtPath) {
  5951. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  5952. }
  5953. if (this.prototypeExpression) {
  5954. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5955. }
  5956. return true;
  5957. }
  5958. if (key === UnknownNonAccessorKey)
  5959. return false;
  5960. if (this.hasLostTrack)
  5961. return true;
  5962. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  5963. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5964. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5965. if (typeof key === 'string') {
  5966. if (propertiesAndAccessorsByKey[key]) {
  5967. const accessors = accessorsByKey[key];
  5968. if (accessors) {
  5969. for (const accessor of accessors) {
  5970. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5971. return true;
  5972. }
  5973. }
  5974. return false;
  5975. }
  5976. for (const accessor of unmatchableAccessors) {
  5977. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  5978. return true;
  5979. }
  5980. }
  5981. }
  5982. else {
  5983. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  5984. for (const accessor of accessors) {
  5985. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5986. return true;
  5987. }
  5988. }
  5989. }
  5990. if (this.prototypeExpression) {
  5991. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5992. }
  5993. return false;
  5994. }
  5995. buildPropertyMaps(properties) {
  5996. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  5997. const unmatchablePropertiesAndSetters = [];
  5998. for (let index = properties.length - 1; index >= 0; index--) {
  5999. const { key, kind, property } = properties[index];
  6000. allProperties.push(property);
  6001. if (typeof key === 'string') {
  6002. if (kind === 'set') {
  6003. if (!propertiesAndSettersByKey[key]) {
  6004. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  6005. settersByKey[key] = [property, ...unmatchableSetters];
  6006. }
  6007. }
  6008. else if (kind === 'get') {
  6009. if (!propertiesAndGettersByKey[key]) {
  6010. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  6011. gettersByKey[key] = [property, ...unmatchableGetters];
  6012. }
  6013. }
  6014. else {
  6015. if (!propertiesAndSettersByKey[key]) {
  6016. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  6017. }
  6018. if (!propertiesAndGettersByKey[key]) {
  6019. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  6020. }
  6021. }
  6022. }
  6023. else {
  6024. if (key === UnknownInteger) {
  6025. unknownIntegerProps.push(property);
  6026. continue;
  6027. }
  6028. if (kind === 'set')
  6029. unmatchableSetters.push(property);
  6030. if (kind === 'get')
  6031. unmatchableGetters.push(property);
  6032. if (kind !== 'get')
  6033. unmatchablePropertiesAndSetters.push(property);
  6034. if (kind !== 'set')
  6035. unmatchablePropertiesAndGetters.push(property);
  6036. }
  6037. }
  6038. }
  6039. deoptimizeCachedEntities() {
  6040. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  6041. for (const expression of expressionsToBeDeoptimized) {
  6042. expression.deoptimizeCache();
  6043. }
  6044. }
  6045. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  6046. expression.deoptimizePath(UNKNOWN_PATH);
  6047. }
  6048. }
  6049. deoptimizeCachedIntegerEntities() {
  6050. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  6051. if (INTEGER_REG_EXP.test(key)) {
  6052. for (const expression of expressionsToBeDeoptimized) {
  6053. expression.deoptimizeCache();
  6054. }
  6055. }
  6056. }
  6057. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  6058. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  6059. }
  6060. }
  6061. getMemberExpression(key) {
  6062. if (this.hasLostTrack ||
  6063. this.hasUnknownDeoptimizedProperty ||
  6064. typeof key !== 'string' ||
  6065. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  6066. this.deoptimizedPaths[key]) {
  6067. return UNKNOWN_EXPRESSION;
  6068. }
  6069. const properties = this.propertiesAndGettersByKey[key];
  6070. if (properties?.length === 1) {
  6071. return properties[0];
  6072. }
  6073. if (properties ||
  6074. this.unmatchablePropertiesAndGetters.length > 0 ||
  6075. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  6076. return UNKNOWN_EXPRESSION;
  6077. }
  6078. return null;
  6079. }
  6080. getMemberExpressionAndTrackDeopt(key, origin) {
  6081. if (typeof key !== 'string') {
  6082. return UNKNOWN_EXPRESSION;
  6083. }
  6084. const expression = this.getMemberExpression(key);
  6085. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  6086. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  6087. this.expressionsToBeDeoptimizedByKey[key] || []);
  6088. expressionsToBeDeoptimized.push(origin);
  6089. }
  6090. return expression;
  6091. }
  6092. }
  6093. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  6094. // This makes sure unknown properties are not handled as "undefined" but as
  6095. // "unknown" but without access side effects. An exception is done for numeric
  6096. // properties as we do not expect new builtin properties to be numbers, this
  6097. // will improve tree-shaking for out-of-bounds array properties
  6098. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  6099. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  6100. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  6101. deoptimizeInteraction(interaction);
  6102. }
  6103. }
  6104. getLiteralValueAtPath(path) {
  6105. // We ignore number properties as we do not expect new properties to be
  6106. // numbers and also want to keep handling out-of-bound array elements as
  6107. // "undefined"
  6108. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  6109. }
  6110. hasEffectsOnInteractionAtPath(path, { type }) {
  6111. return path.length > 1 || type === INTERACTION_CALLED;
  6112. }
  6113. })();
  6114. const OBJECT_PROTOTYPE = new ObjectEntity({
  6115. __proto__: null,
  6116. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  6117. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  6118. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  6119. toLocaleString: METHOD_RETURNS_STRING,
  6120. toString: METHOD_RETURNS_STRING,
  6121. valueOf: METHOD_RETURNS_UNKNOWN
  6122. }, OBJECT_PROTOTYPE_FALLBACK, true);
  6123. const NEW_ARRAY_PROPERTIES = [
  6124. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  6125. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  6126. ];
  6127. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  6128. new Method({
  6129. callsArgs: [0],
  6130. mutatesSelfAsArray: 'deopt-only',
  6131. returns: null,
  6132. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  6133. })
  6134. ];
  6135. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  6136. new Method({
  6137. callsArgs: [0],
  6138. mutatesSelfAsArray: 'deopt-only',
  6139. returns: null,
  6140. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6141. })
  6142. ];
  6143. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  6144. new Method({
  6145. callsArgs: null,
  6146. mutatesSelfAsArray: true,
  6147. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6148. returnsPrimitive: null
  6149. })
  6150. ];
  6151. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  6152. new Method({
  6153. callsArgs: null,
  6154. mutatesSelfAsArray: 'deopt-only',
  6155. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6156. returnsPrimitive: null
  6157. })
  6158. ];
  6159. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  6160. new Method({
  6161. callsArgs: [0],
  6162. mutatesSelfAsArray: 'deopt-only',
  6163. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6164. returnsPrimitive: null
  6165. })
  6166. ];
  6167. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  6168. new Method({
  6169. callsArgs: null,
  6170. mutatesSelfAsArray: true,
  6171. returns: null,
  6172. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6173. })
  6174. ];
  6175. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  6176. new Method({
  6177. callsArgs: null,
  6178. mutatesSelfAsArray: true,
  6179. returns: null,
  6180. returnsPrimitive: UNKNOWN_EXPRESSION
  6181. })
  6182. ];
  6183. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  6184. new Method({
  6185. callsArgs: null,
  6186. mutatesSelfAsArray: 'deopt-only',
  6187. returns: null,
  6188. returnsPrimitive: UNKNOWN_EXPRESSION
  6189. })
  6190. ];
  6191. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  6192. new Method({
  6193. callsArgs: [0],
  6194. mutatesSelfAsArray: 'deopt-only',
  6195. returns: null,
  6196. returnsPrimitive: UNKNOWN_EXPRESSION
  6197. })
  6198. ];
  6199. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  6200. new Method({
  6201. callsArgs: null,
  6202. mutatesSelfAsArray: true,
  6203. returns: 'self',
  6204. returnsPrimitive: null
  6205. })
  6206. ];
  6207. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  6208. new Method({
  6209. callsArgs: [0],
  6210. mutatesSelfAsArray: true,
  6211. returns: 'self',
  6212. returnsPrimitive: null
  6213. })
  6214. ];
  6215. const ARRAY_PROTOTYPE = new ObjectEntity({
  6216. __proto__: null,
  6217. // We assume that accessors have effects as we do not track the accessed value afterwards
  6218. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  6219. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6220. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  6221. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6222. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  6223. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  6224. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6225. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6226. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  6227. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6228. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  6229. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6230. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6231. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6232. includes: METHOD_RETURNS_BOOLEAN,
  6233. indexOf: METHOD_RETURNS_NUMBER,
  6234. join: METHOD_RETURNS_STRING,
  6235. keys: METHOD_RETURNS_UNKNOWN,
  6236. lastIndexOf: METHOD_RETURNS_NUMBER,
  6237. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6238. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  6239. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  6240. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6241. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6242. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  6243. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  6244. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6245. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  6246. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  6247. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  6248. toLocaleString: METHOD_RETURNS_STRING,
  6249. toString: METHOD_RETURNS_STRING,
  6250. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  6251. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  6252. }, OBJECT_PROTOTYPE, true);
  6253. class ArrayExpression extends NodeBase {
  6254. constructor() {
  6255. super(...arguments);
  6256. this.objectEntity = null;
  6257. }
  6258. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6259. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6260. }
  6261. deoptimizePath(path) {
  6262. this.getObjectEntity().deoptimizePath(path);
  6263. }
  6264. getLiteralValueAtPath(path, recursionTracker, origin) {
  6265. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  6266. }
  6267. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6268. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6269. }
  6270. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6271. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  6272. }
  6273. applyDeoptimizations() {
  6274. this.deoptimized = true;
  6275. let hasSpread = false;
  6276. for (let index = 0; index < this.elements.length; index++) {
  6277. const element = this.elements[index];
  6278. if (element && (hasSpread || element instanceof SpreadElement)) {
  6279. hasSpread = true;
  6280. element.deoptimizePath(UNKNOWN_PATH);
  6281. }
  6282. }
  6283. this.context.requestTreeshakingPass();
  6284. }
  6285. getObjectEntity() {
  6286. if (this.objectEntity !== null) {
  6287. return this.objectEntity;
  6288. }
  6289. const properties = [
  6290. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  6291. ];
  6292. let hasSpread = false;
  6293. for (let index = 0; index < this.elements.length; index++) {
  6294. const element = this.elements[index];
  6295. if (hasSpread || element instanceof SpreadElement) {
  6296. if (element) {
  6297. hasSpread = true;
  6298. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  6299. }
  6300. }
  6301. else if (element) {
  6302. properties.push({ key: String(index), kind: 'init', property: element });
  6303. }
  6304. else {
  6305. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  6306. }
  6307. }
  6308. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  6309. }
  6310. }
  6311. class ArrayPattern extends NodeBase {
  6312. addExportedVariables(variables, exportNamesByVariable) {
  6313. for (const element of this.elements) {
  6314. element?.addExportedVariables(variables, exportNamesByVariable);
  6315. }
  6316. }
  6317. declare(kind) {
  6318. const variables = [];
  6319. for (const element of this.elements) {
  6320. if (element !== null) {
  6321. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  6322. }
  6323. }
  6324. return variables;
  6325. }
  6326. // Patterns can only be deoptimized at the empty path at the moment
  6327. deoptimizePath() {
  6328. for (const element of this.elements) {
  6329. element?.deoptimizePath(EMPTY_PATH);
  6330. }
  6331. }
  6332. // Patterns are only checked at the emtpy path at the moment
  6333. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  6334. for (const element of this.elements) {
  6335. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  6336. return true;
  6337. }
  6338. return false;
  6339. }
  6340. markDeclarationReached() {
  6341. for (const element of this.elements) {
  6342. element?.markDeclarationReached();
  6343. }
  6344. }
  6345. }
  6346. class LocalVariable extends Variable {
  6347. constructor(name, declarator, init, context) {
  6348. super(name);
  6349. this.init = init;
  6350. this.calledFromTryStatement = false;
  6351. this.additionalInitializers = null;
  6352. this.expressionsToBeDeoptimized = [];
  6353. this.declarations = declarator ? [declarator] : [];
  6354. this.deoptimizationTracker = context.deoptimizationTracker;
  6355. this.module = context.module;
  6356. }
  6357. addDeclaration(identifier, init) {
  6358. this.declarations.push(identifier);
  6359. this.markInitializersForDeoptimization().push(init);
  6360. }
  6361. consolidateInitializers() {
  6362. if (this.additionalInitializers) {
  6363. for (const initializer of this.additionalInitializers) {
  6364. initializer.deoptimizePath(UNKNOWN_PATH);
  6365. }
  6366. this.additionalInitializers = null;
  6367. }
  6368. }
  6369. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6370. if (this.isReassigned) {
  6371. deoptimizeInteraction(interaction);
  6372. return;
  6373. }
  6374. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  6375. }
  6376. deoptimizePath(path) {
  6377. if (this.isReassigned ||
  6378. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  6379. return;
  6380. }
  6381. if (path.length === 0) {
  6382. if (!this.isReassigned) {
  6383. this.isReassigned = true;
  6384. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6385. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  6386. for (const expression of expressionsToBeDeoptimized) {
  6387. expression.deoptimizeCache();
  6388. }
  6389. this.init.deoptimizePath(UNKNOWN_PATH);
  6390. }
  6391. }
  6392. else {
  6393. this.init.deoptimizePath(path);
  6394. }
  6395. }
  6396. getLiteralValueAtPath(path, recursionTracker, origin) {
  6397. if (this.isReassigned) {
  6398. return UnknownValue;
  6399. }
  6400. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  6401. this.expressionsToBeDeoptimized.push(origin);
  6402. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  6403. }, UnknownValue);
  6404. }
  6405. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6406. if (this.isReassigned) {
  6407. return UNKNOWN_RETURN_EXPRESSION;
  6408. }
  6409. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  6410. this.expressionsToBeDeoptimized.push(origin);
  6411. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6412. }, UNKNOWN_RETURN_EXPRESSION);
  6413. }
  6414. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6415. switch (interaction.type) {
  6416. case INTERACTION_ACCESSED: {
  6417. if (this.isReassigned)
  6418. return true;
  6419. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  6420. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  6421. }
  6422. case INTERACTION_ASSIGNED: {
  6423. if (this.included)
  6424. return true;
  6425. if (path.length === 0)
  6426. return false;
  6427. if (this.isReassigned)
  6428. return true;
  6429. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  6430. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  6431. }
  6432. case INTERACTION_CALLED: {
  6433. if (this.isReassigned)
  6434. return true;
  6435. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  6436. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  6437. }
  6438. }
  6439. }
  6440. include() {
  6441. if (!this.included) {
  6442. this.included = true;
  6443. for (const declaration of this.declarations) {
  6444. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  6445. if (!declaration.included)
  6446. declaration.include(createInclusionContext(), false);
  6447. let node = declaration.parent;
  6448. while (!node.included) {
  6449. // We do not want to properly include parents in case they are part of a dead branch
  6450. // in which case .include() might pull in more dead code
  6451. node.included = true;
  6452. if (node.type === Program$1)
  6453. break;
  6454. node = node.parent;
  6455. }
  6456. }
  6457. }
  6458. }
  6459. includeCallArguments(context, parameters) {
  6460. if (this.isReassigned || context.includedCallArguments.has(this.init)) {
  6461. for (const argument of parameters) {
  6462. argument.include(context, false);
  6463. }
  6464. }
  6465. else {
  6466. context.includedCallArguments.add(this.init);
  6467. this.init.includeCallArguments(context, parameters);
  6468. context.includedCallArguments.delete(this.init);
  6469. }
  6470. }
  6471. markCalledFromTryStatement() {
  6472. this.calledFromTryStatement = true;
  6473. }
  6474. markInitializersForDeoptimization() {
  6475. if (this.additionalInitializers === null) {
  6476. this.additionalInitializers = [this.init];
  6477. this.init = UNKNOWN_EXPRESSION;
  6478. this.isReassigned = true;
  6479. }
  6480. return this.additionalInitializers;
  6481. }
  6482. mergeDeclarations(variable) {
  6483. const { declarations } = this;
  6484. for (const declaration of variable.declarations) {
  6485. declarations.push(declaration);
  6486. }
  6487. const additionalInitializers = this.markInitializersForDeoptimization();
  6488. additionalInitializers.push(variable.init);
  6489. if (variable.additionalInitializers) {
  6490. for (const initializer of variable.additionalInitializers) {
  6491. additionalInitializers.push(initializer);
  6492. }
  6493. }
  6494. }
  6495. }
  6496. const MAX_TRACKED_INTERACTIONS = 20;
  6497. const NO_INTERACTIONS = EMPTY_ARRAY;
  6498. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  6499. const EMPTY_PATH_TRACKER = new PathTracker();
  6500. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  6501. class ParameterVariable extends LocalVariable {
  6502. constructor(name, declarator, context) {
  6503. super(name, declarator, UNKNOWN_EXPRESSION, context);
  6504. this.deoptimizationInteractions = [];
  6505. this.deoptimizations = new PathTracker();
  6506. this.deoptimizedFields = new Set();
  6507. this.entitiesToBeDeoptimized = new Set();
  6508. }
  6509. addEntityToBeDeoptimized(entity) {
  6510. if (entity === UNKNOWN_EXPRESSION) {
  6511. // As unknown expressions fully deoptimize all interactions, we can clear
  6512. // the interaction cache at this point provided we keep this optimization
  6513. // in mind when adding new interactions
  6514. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  6515. this.entitiesToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  6516. for (const { interaction } of this.deoptimizationInteractions) {
  6517. deoptimizeInteraction(interaction);
  6518. }
  6519. this.deoptimizationInteractions = NO_INTERACTIONS;
  6520. }
  6521. }
  6522. else if (this.deoptimizedFields.has(UnknownKey)) {
  6523. // This means that we already deoptimized all interactions and no longer
  6524. // track them
  6525. entity.deoptimizePath(UNKNOWN_PATH);
  6526. }
  6527. else if (!this.entitiesToBeDeoptimized.has(entity)) {
  6528. this.entitiesToBeDeoptimized.add(entity);
  6529. for (const field of this.deoptimizedFields) {
  6530. entity.deoptimizePath([field]);
  6531. }
  6532. for (const { interaction, path } of this.deoptimizationInteractions) {
  6533. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  6534. }
  6535. }
  6536. }
  6537. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  6538. // For performance reasons, we fully deoptimize all deeper interactions
  6539. if (path.length >= 2 ||
  6540. this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  6541. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  6542. (path.length === 1 &&
  6543. (this.deoptimizedFields.has(UnknownKey) ||
  6544. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0]))))) {
  6545. deoptimizeInteraction(interaction);
  6546. return;
  6547. }
  6548. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  6549. for (const entity of this.entitiesToBeDeoptimized) {
  6550. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  6551. }
  6552. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  6553. this.deoptimizationInteractions.push({
  6554. interaction,
  6555. path
  6556. });
  6557. }
  6558. }
  6559. }
  6560. deoptimizePath(path) {
  6561. if (path.length === 0 || this.deoptimizedFields.has(UnknownKey)) {
  6562. return;
  6563. }
  6564. const key = path[0];
  6565. if (this.deoptimizedFields.has(key)) {
  6566. return;
  6567. }
  6568. this.deoptimizedFields.add(key);
  6569. for (const entity of this.entitiesToBeDeoptimized) {
  6570. // We do not need a recursion tracker here as we already track whether
  6571. // this field is deoptimized
  6572. entity.deoptimizePath(path);
  6573. }
  6574. if (key === UnknownKey) {
  6575. // save some memory
  6576. this.deoptimizationInteractions = NO_INTERACTIONS;
  6577. this.deoptimizations = EMPTY_PATH_TRACKER;
  6578. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  6579. this.entitiesToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  6580. }
  6581. }
  6582. getReturnExpressionWhenCalledAtPath(path) {
  6583. // We deoptimize everything that is called as that will trivially deoptimize
  6584. // the corresponding return expressions as well and avoid badly performing
  6585. // and complicated alternatives
  6586. if (path.length === 0) {
  6587. this.deoptimizePath(UNKNOWN_PATH);
  6588. }
  6589. else if (!this.deoptimizedFields.has(path[0])) {
  6590. this.deoptimizePath([path[0]]);
  6591. }
  6592. return UNKNOWN_RETURN_EXPRESSION;
  6593. }
  6594. }
  6595. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  6596. const base = 64;
  6597. function toBase64(value) {
  6598. let outString = '';
  6599. do {
  6600. const currentDigit = value % base;
  6601. value = (value / base) | 0;
  6602. outString = chars[currentDigit] + outString;
  6603. } while (value !== 0);
  6604. return outString;
  6605. }
  6606. function getSafeName(baseName, usedNames, forbiddenNames) {
  6607. let safeName = baseName;
  6608. let count = 1;
  6609. while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName) || forbiddenNames?.has(safeName)) {
  6610. safeName = `${baseName}$${toBase64(count++)}`;
  6611. }
  6612. usedNames.add(safeName);
  6613. return safeName;
  6614. }
  6615. let Scope$1 = class Scope {
  6616. constructor() {
  6617. this.children = [];
  6618. this.variables = new Map();
  6619. }
  6620. addDeclaration(identifier, context, init, _isHoisted) {
  6621. const name = identifier.name;
  6622. let variable = this.variables.get(name);
  6623. if (variable) {
  6624. variable.addDeclaration(identifier, init);
  6625. }
  6626. else {
  6627. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  6628. this.variables.set(name, variable);
  6629. }
  6630. return variable;
  6631. }
  6632. contains(name) {
  6633. return this.variables.has(name);
  6634. }
  6635. findVariable(_name) {
  6636. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  6637. }
  6638. };
  6639. class ChildScope extends Scope$1 {
  6640. constructor(parent) {
  6641. super();
  6642. this.accessedOutsideVariables = new Map();
  6643. this.parent = parent;
  6644. parent.children.push(this);
  6645. }
  6646. addAccessedDynamicImport(importExpression) {
  6647. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  6648. if (this.parent instanceof ChildScope) {
  6649. this.parent.addAccessedDynamicImport(importExpression);
  6650. }
  6651. }
  6652. addAccessedGlobals(globals, accessedGlobalsByScope) {
  6653. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  6654. for (const name of globals) {
  6655. accessedGlobals.add(name);
  6656. }
  6657. accessedGlobalsByScope.set(this, accessedGlobals);
  6658. if (this.parent instanceof ChildScope) {
  6659. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  6660. }
  6661. }
  6662. addNamespaceMemberAccess(name, variable) {
  6663. this.accessedOutsideVariables.set(name, variable);
  6664. this.parent.addNamespaceMemberAccess(name, variable);
  6665. }
  6666. addReturnExpression(expression) {
  6667. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  6668. }
  6669. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  6670. for (const variable of this.accessedOutsideVariables.values()) {
  6671. if (variable.included) {
  6672. usedNames.add(variable.getBaseVariableName());
  6673. if (format === 'system' && exportNamesByVariable.has(variable)) {
  6674. usedNames.add('exports');
  6675. }
  6676. }
  6677. }
  6678. const accessedGlobals = accessedGlobalsByScope.get(this);
  6679. if (accessedGlobals) {
  6680. for (const name of accessedGlobals) {
  6681. usedNames.add(name);
  6682. }
  6683. }
  6684. }
  6685. contains(name) {
  6686. return this.variables.has(name) || this.parent.contains(name);
  6687. }
  6688. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  6689. const usedNames = new Set();
  6690. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  6691. if (this.accessedDynamicImports) {
  6692. for (const importExpression of this.accessedDynamicImports) {
  6693. if (importExpression.inlineNamespace) {
  6694. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  6695. }
  6696. }
  6697. }
  6698. for (const [name, variable] of this.variables) {
  6699. if (variable.included || variable.alwaysRendered) {
  6700. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  6701. }
  6702. }
  6703. for (const scope of this.children) {
  6704. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  6705. }
  6706. }
  6707. findLexicalBoundary() {
  6708. return this.parent.findLexicalBoundary();
  6709. }
  6710. findVariable(name) {
  6711. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  6712. if (knownVariable) {
  6713. return knownVariable;
  6714. }
  6715. const variable = this.parent.findVariable(name);
  6716. this.accessedOutsideVariables.set(name, variable);
  6717. return variable;
  6718. }
  6719. }
  6720. class ParameterScope extends ChildScope {
  6721. constructor(parent, context) {
  6722. super(parent);
  6723. this.parameters = [];
  6724. this.hasRest = false;
  6725. this.context = context;
  6726. this.hoistedBodyVarScope = new ChildScope(this);
  6727. }
  6728. /**
  6729. * Adds a parameter to this scope. Parameters must be added in the correct
  6730. * order, i.e. from left to right.
  6731. */
  6732. addParameterDeclaration(identifier) {
  6733. const { name } = identifier;
  6734. const variable = new ParameterVariable(name, identifier, this.context);
  6735. const localVariable = this.hoistedBodyVarScope.variables.get(name);
  6736. if (localVariable) {
  6737. this.hoistedBodyVarScope.variables.set(name, variable);
  6738. variable.mergeDeclarations(localVariable);
  6739. }
  6740. this.variables.set(name, variable);
  6741. return variable;
  6742. }
  6743. addParameterVariables(parameters, hasRest) {
  6744. this.parameters = parameters;
  6745. for (const parameterList of parameters) {
  6746. for (const parameter of parameterList) {
  6747. parameter.alwaysRendered = true;
  6748. }
  6749. }
  6750. this.hasRest = hasRest;
  6751. }
  6752. includeCallArguments(context, parameters) {
  6753. let calledFromTryStatement = false;
  6754. let argumentIncluded = false;
  6755. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  6756. for (const checkedArgument of parameters) {
  6757. if (checkedArgument instanceof SpreadElement) {
  6758. for (const argument of parameters) {
  6759. argument.include(context, false);
  6760. }
  6761. break;
  6762. }
  6763. }
  6764. for (let index = parameters.length - 1; index >= 0; index--) {
  6765. const parameterVariables = this.parameters[index] || restParameter;
  6766. const argument = parameters[index];
  6767. if (parameterVariables) {
  6768. calledFromTryStatement = false;
  6769. if (parameterVariables.length === 0) {
  6770. // handle empty destructuring
  6771. argumentIncluded = true;
  6772. }
  6773. else {
  6774. for (const variable of parameterVariables) {
  6775. if (variable.included) {
  6776. argumentIncluded = true;
  6777. }
  6778. if (variable.calledFromTryStatement) {
  6779. calledFromTryStatement = true;
  6780. }
  6781. }
  6782. }
  6783. }
  6784. if (!argumentIncluded && argument.shouldBeIncluded(context)) {
  6785. argumentIncluded = true;
  6786. }
  6787. if (argumentIncluded) {
  6788. argument.include(context, calledFromTryStatement);
  6789. }
  6790. }
  6791. }
  6792. }
  6793. class ReturnValueScope extends ParameterScope {
  6794. constructor() {
  6795. super(...arguments);
  6796. this.returnExpression = null;
  6797. this.returnExpressions = [];
  6798. }
  6799. addReturnExpression(expression) {
  6800. this.returnExpressions.push(expression);
  6801. }
  6802. getReturnExpression() {
  6803. if (this.returnExpression === null)
  6804. this.updateReturnExpression();
  6805. return this.returnExpression;
  6806. }
  6807. updateReturnExpression() {
  6808. if (this.returnExpressions.length === 1) {
  6809. this.returnExpression = this.returnExpressions[0];
  6810. }
  6811. else {
  6812. this.returnExpression = UNKNOWN_EXPRESSION;
  6813. for (const expression of this.returnExpressions) {
  6814. expression.deoptimizePath(UNKNOWN_PATH);
  6815. }
  6816. }
  6817. }
  6818. }
  6819. /** @typedef { import('estree').Node} Node */
  6820. /** @typedef {Node | {
  6821. * type: 'PropertyDefinition';
  6822. * computed: boolean;
  6823. * value: Node
  6824. * }} NodeWithPropertyDefinition */
  6825. /**
  6826. *
  6827. * @param {NodeWithPropertyDefinition} node
  6828. * @param {NodeWithPropertyDefinition} parent
  6829. * @returns {boolean}
  6830. */
  6831. function is_reference (node, parent) {
  6832. if (node.type === 'MemberExpression') {
  6833. return !node.computed && is_reference(node.object, node);
  6834. }
  6835. if (node.type === 'Identifier') {
  6836. if (!parent) return true;
  6837. switch (parent.type) {
  6838. // disregard `bar` in `foo.bar`
  6839. case 'MemberExpression': return parent.computed || node === parent.object;
  6840. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  6841. case 'MethodDefinition': return parent.computed;
  6842. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  6843. case 'PropertyDefinition': return parent.computed || node === parent.value;
  6844. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  6845. case 'Property': return parent.computed || node === parent.value;
  6846. // disregard the `bar` in `export { foo as bar }` or
  6847. // the foo in `import { foo as bar }`
  6848. case 'ExportSpecifier':
  6849. case 'ImportSpecifier': return node === parent.local;
  6850. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  6851. case 'LabeledStatement':
  6852. case 'BreakStatement':
  6853. case 'ContinueStatement': return false;
  6854. default: return true;
  6855. }
  6856. }
  6857. return false;
  6858. }
  6859. const PureFunctionKey = Symbol('PureFunction');
  6860. const getPureFunctions = ({ treeshake }) => {
  6861. const pureFunctions = Object.create(null);
  6862. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  6863. let currentFunctions = pureFunctions;
  6864. for (const pathSegment of functionName.split('.')) {
  6865. currentFunctions = currentFunctions[pathSegment] || (currentFunctions[pathSegment] = Object.create(null));
  6866. }
  6867. currentFunctions[PureFunctionKey] = true;
  6868. }
  6869. return pureFunctions;
  6870. };
  6871. const doNothing = () => { };
  6872. /* eslint sort-keys: "off" */
  6873. const ValueProperties = Symbol('Value Properties');
  6874. const getTruthyLiteralValue = () => UnknownTruthyValue;
  6875. const returnFalse = () => false;
  6876. const returnTrue = () => true;
  6877. const PURE = {
  6878. deoptimizeArgumentsOnCall: doNothing,
  6879. getLiteralValue: getTruthyLiteralValue,
  6880. hasEffectsWhenCalled: returnFalse
  6881. };
  6882. const IMPURE = {
  6883. deoptimizeArgumentsOnCall: doNothing,
  6884. getLiteralValue: getTruthyLiteralValue,
  6885. hasEffectsWhenCalled: returnTrue
  6886. };
  6887. const PURE_WITH_ARRAY = {
  6888. deoptimizeArgumentsOnCall: doNothing,
  6889. getLiteralValue: getTruthyLiteralValue,
  6890. hasEffectsWhenCalled({ args }) {
  6891. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  6892. }
  6893. };
  6894. // We use shortened variables to reduce file size here
  6895. /* OBJECT */
  6896. const O = {
  6897. __proto__: null,
  6898. [ValueProperties]: IMPURE
  6899. };
  6900. /* PURE FUNCTION */
  6901. const PF = {
  6902. __proto__: null,
  6903. [ValueProperties]: PURE
  6904. };
  6905. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  6906. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  6907. __proto__: null,
  6908. [ValueProperties]: {
  6909. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  6910. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  6911. },
  6912. getLiteralValue: getTruthyLiteralValue,
  6913. hasEffectsWhenCalled({ args }, context) {
  6914. return (args.length <= 1 ||
  6915. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  6916. }
  6917. }
  6918. };
  6919. /* CONSTRUCTOR */
  6920. const C = {
  6921. __proto__: null,
  6922. [ValueProperties]: IMPURE,
  6923. prototype: O
  6924. };
  6925. /* PURE CONSTRUCTOR */
  6926. const PC = {
  6927. __proto__: null,
  6928. [ValueProperties]: PURE,
  6929. prototype: O
  6930. };
  6931. const PC_WITH_ARRAY = {
  6932. __proto__: null,
  6933. [ValueProperties]: PURE_WITH_ARRAY,
  6934. prototype: O
  6935. };
  6936. const ARRAY_TYPE = {
  6937. __proto__: null,
  6938. [ValueProperties]: PURE,
  6939. from: O,
  6940. of: PF,
  6941. prototype: O
  6942. };
  6943. const INTL_MEMBER = {
  6944. __proto__: null,
  6945. [ValueProperties]: PURE,
  6946. supportedLocalesOf: PC
  6947. };
  6948. const knownGlobals = {
  6949. // Placeholders for global objects to avoid shape mutations
  6950. global: O,
  6951. globalThis: O,
  6952. self: O,
  6953. window: O,
  6954. // Common globals
  6955. __proto__: null,
  6956. [ValueProperties]: IMPURE,
  6957. Array: {
  6958. __proto__: null,
  6959. [ValueProperties]: IMPURE,
  6960. from: O,
  6961. isArray: PF,
  6962. of: PF,
  6963. prototype: O
  6964. },
  6965. ArrayBuffer: {
  6966. __proto__: null,
  6967. [ValueProperties]: PURE,
  6968. isView: PF,
  6969. prototype: O
  6970. },
  6971. Atomics: O,
  6972. BigInt: C,
  6973. BigInt64Array: C,
  6974. BigUint64Array: C,
  6975. Boolean: PC,
  6976. constructor: C,
  6977. DataView: PC,
  6978. Date: {
  6979. __proto__: null,
  6980. [ValueProperties]: PURE,
  6981. now: PF,
  6982. parse: PF,
  6983. prototype: O,
  6984. UTC: PF
  6985. },
  6986. decodeURI: PF,
  6987. decodeURIComponent: PF,
  6988. encodeURI: PF,
  6989. encodeURIComponent: PF,
  6990. Error: PC,
  6991. escape: PF,
  6992. eval: O,
  6993. EvalError: PC,
  6994. Float32Array: ARRAY_TYPE,
  6995. Float64Array: ARRAY_TYPE,
  6996. Function: C,
  6997. hasOwnProperty: O,
  6998. Infinity: O,
  6999. Int16Array: ARRAY_TYPE,
  7000. Int32Array: ARRAY_TYPE,
  7001. Int8Array: ARRAY_TYPE,
  7002. isFinite: PF,
  7003. isNaN: PF,
  7004. isPrototypeOf: O,
  7005. JSON: O,
  7006. Map: PC_WITH_ARRAY,
  7007. Math: {
  7008. __proto__: null,
  7009. [ValueProperties]: IMPURE,
  7010. abs: PF,
  7011. acos: PF,
  7012. acosh: PF,
  7013. asin: PF,
  7014. asinh: PF,
  7015. atan: PF,
  7016. atan2: PF,
  7017. atanh: PF,
  7018. cbrt: PF,
  7019. ceil: PF,
  7020. clz32: PF,
  7021. cos: PF,
  7022. cosh: PF,
  7023. exp: PF,
  7024. expm1: PF,
  7025. floor: PF,
  7026. fround: PF,
  7027. hypot: PF,
  7028. imul: PF,
  7029. log: PF,
  7030. log10: PF,
  7031. log1p: PF,
  7032. log2: PF,
  7033. max: PF,
  7034. min: PF,
  7035. pow: PF,
  7036. random: PF,
  7037. round: PF,
  7038. sign: PF,
  7039. sin: PF,
  7040. sinh: PF,
  7041. sqrt: PF,
  7042. tan: PF,
  7043. tanh: PF,
  7044. trunc: PF
  7045. },
  7046. NaN: O,
  7047. Number: {
  7048. __proto__: null,
  7049. [ValueProperties]: PURE,
  7050. isFinite: PF,
  7051. isInteger: PF,
  7052. isNaN: PF,
  7053. isSafeInteger: PF,
  7054. parseFloat: PF,
  7055. parseInt: PF,
  7056. prototype: O
  7057. },
  7058. Object: {
  7059. __proto__: null,
  7060. [ValueProperties]: PURE,
  7061. create: PF,
  7062. // Technically those can throw in certain situations, but we ignore this as
  7063. // code that relies on this will hopefully wrap this in a try-catch, which
  7064. // deoptimizes everything anyway
  7065. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  7066. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  7067. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  7068. getOwnPropertyDescriptor: PF,
  7069. getOwnPropertyDescriptors: PF,
  7070. getOwnPropertyNames: PF,
  7071. getOwnPropertySymbols: PF,
  7072. getPrototypeOf: PF,
  7073. hasOwn: PF,
  7074. is: PF,
  7075. isExtensible: PF,
  7076. isFrozen: PF,
  7077. isSealed: PF,
  7078. keys: PF,
  7079. fromEntries: O,
  7080. entries: PF,
  7081. prototype: O
  7082. },
  7083. parseFloat: PF,
  7084. parseInt: PF,
  7085. Promise: {
  7086. __proto__: null,
  7087. [ValueProperties]: IMPURE,
  7088. all: O,
  7089. allSettled: O,
  7090. any: O,
  7091. prototype: O,
  7092. race: O,
  7093. reject: O,
  7094. resolve: O
  7095. },
  7096. propertyIsEnumerable: O,
  7097. Proxy: O,
  7098. RangeError: PC,
  7099. ReferenceError: PC,
  7100. Reflect: O,
  7101. RegExp: PC,
  7102. Set: PC_WITH_ARRAY,
  7103. SharedArrayBuffer: C,
  7104. String: {
  7105. __proto__: null,
  7106. [ValueProperties]: PURE,
  7107. fromCharCode: PF,
  7108. fromCodePoint: PF,
  7109. prototype: O,
  7110. raw: PF
  7111. },
  7112. Symbol: {
  7113. __proto__: null,
  7114. [ValueProperties]: PURE,
  7115. for: PF,
  7116. keyFor: PF,
  7117. prototype: O,
  7118. toStringTag: {
  7119. __proto__: null,
  7120. [ValueProperties]: {
  7121. deoptimizeArgumentsOnCall: doNothing,
  7122. getLiteralValue() {
  7123. return SymbolToStringTag;
  7124. },
  7125. hasEffectsWhenCalled: returnTrue
  7126. }
  7127. }
  7128. },
  7129. SyntaxError: PC,
  7130. toLocaleString: O,
  7131. toString: O,
  7132. TypeError: PC,
  7133. Uint16Array: ARRAY_TYPE,
  7134. Uint32Array: ARRAY_TYPE,
  7135. Uint8Array: ARRAY_TYPE,
  7136. Uint8ClampedArray: ARRAY_TYPE,
  7137. // Technically, this is a global, but it needs special handling
  7138. // undefined: ?,
  7139. unescape: PF,
  7140. URIError: PC,
  7141. valueOf: O,
  7142. WeakMap: PC_WITH_ARRAY,
  7143. WeakSet: PC_WITH_ARRAY,
  7144. // Additional globals shared by Node and Browser that are not strictly part of the language
  7145. clearInterval: C,
  7146. clearTimeout: C,
  7147. console: {
  7148. __proto__: null,
  7149. [ValueProperties]: IMPURE,
  7150. assert: C,
  7151. clear: C,
  7152. count: C,
  7153. countReset: C,
  7154. debug: C,
  7155. dir: C,
  7156. dirxml: C,
  7157. error: C,
  7158. exception: C,
  7159. group: C,
  7160. groupCollapsed: C,
  7161. groupEnd: C,
  7162. info: C,
  7163. log: C,
  7164. table: C,
  7165. time: C,
  7166. timeEnd: C,
  7167. timeLog: C,
  7168. trace: C,
  7169. warn: C
  7170. },
  7171. Intl: {
  7172. __proto__: null,
  7173. [ValueProperties]: IMPURE,
  7174. Collator: INTL_MEMBER,
  7175. DateTimeFormat: INTL_MEMBER,
  7176. ListFormat: INTL_MEMBER,
  7177. NumberFormat: INTL_MEMBER,
  7178. PluralRules: INTL_MEMBER,
  7179. RelativeTimeFormat: INTL_MEMBER
  7180. },
  7181. setInterval: C,
  7182. setTimeout: C,
  7183. TextDecoder: C,
  7184. TextEncoder: C,
  7185. URL: C,
  7186. URLSearchParams: C,
  7187. // Browser specific globals
  7188. AbortController: C,
  7189. AbortSignal: C,
  7190. addEventListener: O,
  7191. alert: O,
  7192. AnalyserNode: C,
  7193. Animation: C,
  7194. AnimationEvent: C,
  7195. applicationCache: O,
  7196. ApplicationCache: C,
  7197. ApplicationCacheErrorEvent: C,
  7198. atob: O,
  7199. Attr: C,
  7200. Audio: C,
  7201. AudioBuffer: C,
  7202. AudioBufferSourceNode: C,
  7203. AudioContext: C,
  7204. AudioDestinationNode: C,
  7205. AudioListener: C,
  7206. AudioNode: C,
  7207. AudioParam: C,
  7208. AudioProcessingEvent: C,
  7209. AudioScheduledSourceNode: C,
  7210. AudioWorkletNode: C,
  7211. BarProp: C,
  7212. BaseAudioContext: C,
  7213. BatteryManager: C,
  7214. BeforeUnloadEvent: C,
  7215. BiquadFilterNode: C,
  7216. Blob: C,
  7217. BlobEvent: C,
  7218. blur: O,
  7219. BroadcastChannel: C,
  7220. btoa: O,
  7221. ByteLengthQueuingStrategy: C,
  7222. Cache: C,
  7223. caches: O,
  7224. CacheStorage: C,
  7225. cancelAnimationFrame: O,
  7226. cancelIdleCallback: O,
  7227. CanvasCaptureMediaStreamTrack: C,
  7228. CanvasGradient: C,
  7229. CanvasPattern: C,
  7230. CanvasRenderingContext2D: C,
  7231. ChannelMergerNode: C,
  7232. ChannelSplitterNode: C,
  7233. CharacterData: C,
  7234. clientInformation: O,
  7235. ClipboardEvent: C,
  7236. close: O,
  7237. closed: O,
  7238. CloseEvent: C,
  7239. Comment: C,
  7240. CompositionEvent: C,
  7241. confirm: O,
  7242. ConstantSourceNode: C,
  7243. ConvolverNode: C,
  7244. CountQueuingStrategy: C,
  7245. createImageBitmap: O,
  7246. Credential: C,
  7247. CredentialsContainer: C,
  7248. crypto: O,
  7249. Crypto: C,
  7250. CryptoKey: C,
  7251. CSS: C,
  7252. CSSConditionRule: C,
  7253. CSSFontFaceRule: C,
  7254. CSSGroupingRule: C,
  7255. CSSImportRule: C,
  7256. CSSKeyframeRule: C,
  7257. CSSKeyframesRule: C,
  7258. CSSMediaRule: C,
  7259. CSSNamespaceRule: C,
  7260. CSSPageRule: C,
  7261. CSSRule: C,
  7262. CSSRuleList: C,
  7263. CSSStyleDeclaration: C,
  7264. CSSStyleRule: C,
  7265. CSSStyleSheet: C,
  7266. CSSSupportsRule: C,
  7267. CustomElementRegistry: C,
  7268. customElements: O,
  7269. CustomEvent: C,
  7270. DataTransfer: C,
  7271. DataTransferItem: C,
  7272. DataTransferItemList: C,
  7273. defaultstatus: O,
  7274. defaultStatus: O,
  7275. DelayNode: C,
  7276. DeviceMotionEvent: C,
  7277. DeviceOrientationEvent: C,
  7278. devicePixelRatio: O,
  7279. dispatchEvent: O,
  7280. document: O,
  7281. Document: C,
  7282. DocumentFragment: C,
  7283. DocumentType: C,
  7284. DOMError: C,
  7285. DOMException: C,
  7286. DOMImplementation: C,
  7287. DOMMatrix: C,
  7288. DOMMatrixReadOnly: C,
  7289. DOMParser: C,
  7290. DOMPoint: C,
  7291. DOMPointReadOnly: C,
  7292. DOMQuad: C,
  7293. DOMRect: C,
  7294. DOMRectReadOnly: C,
  7295. DOMStringList: C,
  7296. DOMStringMap: C,
  7297. DOMTokenList: C,
  7298. DragEvent: C,
  7299. DynamicsCompressorNode: C,
  7300. Element: C,
  7301. ErrorEvent: C,
  7302. Event: C,
  7303. EventSource: C,
  7304. EventTarget: C,
  7305. external: O,
  7306. fetch: O,
  7307. File: C,
  7308. FileList: C,
  7309. FileReader: C,
  7310. find: O,
  7311. focus: O,
  7312. FocusEvent: C,
  7313. FontFace: C,
  7314. FontFaceSetLoadEvent: C,
  7315. FormData: C,
  7316. frames: O,
  7317. GainNode: C,
  7318. Gamepad: C,
  7319. GamepadButton: C,
  7320. GamepadEvent: C,
  7321. getComputedStyle: O,
  7322. getSelection: O,
  7323. HashChangeEvent: C,
  7324. Headers: C,
  7325. history: O,
  7326. History: C,
  7327. HTMLAllCollection: C,
  7328. HTMLAnchorElement: C,
  7329. HTMLAreaElement: C,
  7330. HTMLAudioElement: C,
  7331. HTMLBaseElement: C,
  7332. HTMLBodyElement: C,
  7333. HTMLBRElement: C,
  7334. HTMLButtonElement: C,
  7335. HTMLCanvasElement: C,
  7336. HTMLCollection: C,
  7337. HTMLContentElement: C,
  7338. HTMLDataElement: C,
  7339. HTMLDataListElement: C,
  7340. HTMLDetailsElement: C,
  7341. HTMLDialogElement: C,
  7342. HTMLDirectoryElement: C,
  7343. HTMLDivElement: C,
  7344. HTMLDListElement: C,
  7345. HTMLDocument: C,
  7346. HTMLElement: C,
  7347. HTMLEmbedElement: C,
  7348. HTMLFieldSetElement: C,
  7349. HTMLFontElement: C,
  7350. HTMLFormControlsCollection: C,
  7351. HTMLFormElement: C,
  7352. HTMLFrameElement: C,
  7353. HTMLFrameSetElement: C,
  7354. HTMLHeadElement: C,
  7355. HTMLHeadingElement: C,
  7356. HTMLHRElement: C,
  7357. HTMLHtmlElement: C,
  7358. HTMLIFrameElement: C,
  7359. HTMLImageElement: C,
  7360. HTMLInputElement: C,
  7361. HTMLLabelElement: C,
  7362. HTMLLegendElement: C,
  7363. HTMLLIElement: C,
  7364. HTMLLinkElement: C,
  7365. HTMLMapElement: C,
  7366. HTMLMarqueeElement: C,
  7367. HTMLMediaElement: C,
  7368. HTMLMenuElement: C,
  7369. HTMLMetaElement: C,
  7370. HTMLMeterElement: C,
  7371. HTMLModElement: C,
  7372. HTMLObjectElement: C,
  7373. HTMLOListElement: C,
  7374. HTMLOptGroupElement: C,
  7375. HTMLOptionElement: C,
  7376. HTMLOptionsCollection: C,
  7377. HTMLOutputElement: C,
  7378. HTMLParagraphElement: C,
  7379. HTMLParamElement: C,
  7380. HTMLPictureElement: C,
  7381. HTMLPreElement: C,
  7382. HTMLProgressElement: C,
  7383. HTMLQuoteElement: C,
  7384. HTMLScriptElement: C,
  7385. HTMLSelectElement: C,
  7386. HTMLShadowElement: C,
  7387. HTMLSlotElement: C,
  7388. HTMLSourceElement: C,
  7389. HTMLSpanElement: C,
  7390. HTMLStyleElement: C,
  7391. HTMLTableCaptionElement: C,
  7392. HTMLTableCellElement: C,
  7393. HTMLTableColElement: C,
  7394. HTMLTableElement: C,
  7395. HTMLTableRowElement: C,
  7396. HTMLTableSectionElement: C,
  7397. HTMLTemplateElement: C,
  7398. HTMLTextAreaElement: C,
  7399. HTMLTimeElement: C,
  7400. HTMLTitleElement: C,
  7401. HTMLTrackElement: C,
  7402. HTMLUListElement: C,
  7403. HTMLUnknownElement: C,
  7404. HTMLVideoElement: C,
  7405. IDBCursor: C,
  7406. IDBCursorWithValue: C,
  7407. IDBDatabase: C,
  7408. IDBFactory: C,
  7409. IDBIndex: C,
  7410. IDBKeyRange: C,
  7411. IDBObjectStore: C,
  7412. IDBOpenDBRequest: C,
  7413. IDBRequest: C,
  7414. IDBTransaction: C,
  7415. IDBVersionChangeEvent: C,
  7416. IdleDeadline: C,
  7417. IIRFilterNode: C,
  7418. Image: C,
  7419. ImageBitmap: C,
  7420. ImageBitmapRenderingContext: C,
  7421. ImageCapture: C,
  7422. ImageData: C,
  7423. indexedDB: O,
  7424. innerHeight: O,
  7425. innerWidth: O,
  7426. InputEvent: C,
  7427. IntersectionObserver: C,
  7428. IntersectionObserverEntry: C,
  7429. isSecureContext: O,
  7430. KeyboardEvent: C,
  7431. KeyframeEffect: C,
  7432. length: O,
  7433. localStorage: O,
  7434. location: O,
  7435. Location: C,
  7436. locationbar: O,
  7437. matchMedia: O,
  7438. MediaDeviceInfo: C,
  7439. MediaDevices: C,
  7440. MediaElementAudioSourceNode: C,
  7441. MediaEncryptedEvent: C,
  7442. MediaError: C,
  7443. MediaKeyMessageEvent: C,
  7444. MediaKeySession: C,
  7445. MediaKeyStatusMap: C,
  7446. MediaKeySystemAccess: C,
  7447. MediaList: C,
  7448. MediaQueryList: C,
  7449. MediaQueryListEvent: C,
  7450. MediaRecorder: C,
  7451. MediaSettingsRange: C,
  7452. MediaSource: C,
  7453. MediaStream: C,
  7454. MediaStreamAudioDestinationNode: C,
  7455. MediaStreamAudioSourceNode: C,
  7456. MediaStreamEvent: C,
  7457. MediaStreamTrack: C,
  7458. MediaStreamTrackEvent: C,
  7459. menubar: O,
  7460. MessageChannel: C,
  7461. MessageEvent: C,
  7462. MessagePort: C,
  7463. MIDIAccess: C,
  7464. MIDIConnectionEvent: C,
  7465. MIDIInput: C,
  7466. MIDIInputMap: C,
  7467. MIDIMessageEvent: C,
  7468. MIDIOutput: C,
  7469. MIDIOutputMap: C,
  7470. MIDIPort: C,
  7471. MimeType: C,
  7472. MimeTypeArray: C,
  7473. MouseEvent: C,
  7474. moveBy: O,
  7475. moveTo: O,
  7476. MutationEvent: C,
  7477. MutationObserver: C,
  7478. MutationRecord: C,
  7479. name: O,
  7480. NamedNodeMap: C,
  7481. NavigationPreloadManager: C,
  7482. navigator: O,
  7483. Navigator: C,
  7484. NetworkInformation: C,
  7485. Node: C,
  7486. NodeFilter: O,
  7487. NodeIterator: C,
  7488. NodeList: C,
  7489. Notification: C,
  7490. OfflineAudioCompletionEvent: C,
  7491. OfflineAudioContext: C,
  7492. offscreenBuffering: O,
  7493. OffscreenCanvas: C,
  7494. open: O,
  7495. openDatabase: O,
  7496. Option: C,
  7497. origin: O,
  7498. OscillatorNode: C,
  7499. outerHeight: O,
  7500. outerWidth: O,
  7501. PageTransitionEvent: C,
  7502. pageXOffset: O,
  7503. pageYOffset: O,
  7504. PannerNode: C,
  7505. parent: O,
  7506. Path2D: C,
  7507. PaymentAddress: C,
  7508. PaymentRequest: C,
  7509. PaymentRequestUpdateEvent: C,
  7510. PaymentResponse: C,
  7511. performance: O,
  7512. Performance: C,
  7513. PerformanceEntry: C,
  7514. PerformanceLongTaskTiming: C,
  7515. PerformanceMark: C,
  7516. PerformanceMeasure: C,
  7517. PerformanceNavigation: C,
  7518. PerformanceNavigationTiming: C,
  7519. PerformanceObserver: C,
  7520. PerformanceObserverEntryList: C,
  7521. PerformancePaintTiming: C,
  7522. PerformanceResourceTiming: C,
  7523. PerformanceTiming: C,
  7524. PeriodicWave: C,
  7525. Permissions: C,
  7526. PermissionStatus: C,
  7527. personalbar: O,
  7528. PhotoCapabilities: C,
  7529. Plugin: C,
  7530. PluginArray: C,
  7531. PointerEvent: C,
  7532. PopStateEvent: C,
  7533. postMessage: O,
  7534. Presentation: C,
  7535. PresentationAvailability: C,
  7536. PresentationConnection: C,
  7537. PresentationConnectionAvailableEvent: C,
  7538. PresentationConnectionCloseEvent: C,
  7539. PresentationConnectionList: C,
  7540. PresentationReceiver: C,
  7541. PresentationRequest: C,
  7542. print: O,
  7543. ProcessingInstruction: C,
  7544. ProgressEvent: C,
  7545. PromiseRejectionEvent: C,
  7546. prompt: O,
  7547. PushManager: C,
  7548. PushSubscription: C,
  7549. PushSubscriptionOptions: C,
  7550. queueMicrotask: O,
  7551. RadioNodeList: C,
  7552. Range: C,
  7553. ReadableStream: C,
  7554. RemotePlayback: C,
  7555. removeEventListener: O,
  7556. Request: C,
  7557. requestAnimationFrame: O,
  7558. requestIdleCallback: O,
  7559. resizeBy: O,
  7560. ResizeObserver: C,
  7561. ResizeObserverEntry: C,
  7562. resizeTo: O,
  7563. Response: C,
  7564. RTCCertificate: C,
  7565. RTCDataChannel: C,
  7566. RTCDataChannelEvent: C,
  7567. RTCDtlsTransport: C,
  7568. RTCIceCandidate: C,
  7569. RTCIceTransport: C,
  7570. RTCPeerConnection: C,
  7571. RTCPeerConnectionIceEvent: C,
  7572. RTCRtpReceiver: C,
  7573. RTCRtpSender: C,
  7574. RTCSctpTransport: C,
  7575. RTCSessionDescription: C,
  7576. RTCStatsReport: C,
  7577. RTCTrackEvent: C,
  7578. screen: O,
  7579. Screen: C,
  7580. screenLeft: O,
  7581. ScreenOrientation: C,
  7582. screenTop: O,
  7583. screenX: O,
  7584. screenY: O,
  7585. ScriptProcessorNode: C,
  7586. scroll: O,
  7587. scrollbars: O,
  7588. scrollBy: O,
  7589. scrollTo: O,
  7590. scrollX: O,
  7591. scrollY: O,
  7592. SecurityPolicyViolationEvent: C,
  7593. Selection: C,
  7594. ServiceWorker: C,
  7595. ServiceWorkerContainer: C,
  7596. ServiceWorkerRegistration: C,
  7597. sessionStorage: O,
  7598. ShadowRoot: C,
  7599. SharedWorker: C,
  7600. SourceBuffer: C,
  7601. SourceBufferList: C,
  7602. speechSynthesis: O,
  7603. SpeechSynthesisEvent: C,
  7604. SpeechSynthesisUtterance: C,
  7605. StaticRange: C,
  7606. status: O,
  7607. statusbar: O,
  7608. StereoPannerNode: C,
  7609. stop: O,
  7610. Storage: C,
  7611. StorageEvent: C,
  7612. StorageManager: C,
  7613. styleMedia: O,
  7614. StyleSheet: C,
  7615. StyleSheetList: C,
  7616. SubtleCrypto: C,
  7617. SVGAElement: C,
  7618. SVGAngle: C,
  7619. SVGAnimatedAngle: C,
  7620. SVGAnimatedBoolean: C,
  7621. SVGAnimatedEnumeration: C,
  7622. SVGAnimatedInteger: C,
  7623. SVGAnimatedLength: C,
  7624. SVGAnimatedLengthList: C,
  7625. SVGAnimatedNumber: C,
  7626. SVGAnimatedNumberList: C,
  7627. SVGAnimatedPreserveAspectRatio: C,
  7628. SVGAnimatedRect: C,
  7629. SVGAnimatedString: C,
  7630. SVGAnimatedTransformList: C,
  7631. SVGAnimateElement: C,
  7632. SVGAnimateMotionElement: C,
  7633. SVGAnimateTransformElement: C,
  7634. SVGAnimationElement: C,
  7635. SVGCircleElement: C,
  7636. SVGClipPathElement: C,
  7637. SVGComponentTransferFunctionElement: C,
  7638. SVGDefsElement: C,
  7639. SVGDescElement: C,
  7640. SVGDiscardElement: C,
  7641. SVGElement: C,
  7642. SVGEllipseElement: C,
  7643. SVGFEBlendElement: C,
  7644. SVGFEColorMatrixElement: C,
  7645. SVGFEComponentTransferElement: C,
  7646. SVGFECompositeElement: C,
  7647. SVGFEConvolveMatrixElement: C,
  7648. SVGFEDiffuseLightingElement: C,
  7649. SVGFEDisplacementMapElement: C,
  7650. SVGFEDistantLightElement: C,
  7651. SVGFEDropShadowElement: C,
  7652. SVGFEFloodElement: C,
  7653. SVGFEFuncAElement: C,
  7654. SVGFEFuncBElement: C,
  7655. SVGFEFuncGElement: C,
  7656. SVGFEFuncRElement: C,
  7657. SVGFEGaussianBlurElement: C,
  7658. SVGFEImageElement: C,
  7659. SVGFEMergeElement: C,
  7660. SVGFEMergeNodeElement: C,
  7661. SVGFEMorphologyElement: C,
  7662. SVGFEOffsetElement: C,
  7663. SVGFEPointLightElement: C,
  7664. SVGFESpecularLightingElement: C,
  7665. SVGFESpotLightElement: C,
  7666. SVGFETileElement: C,
  7667. SVGFETurbulenceElement: C,
  7668. SVGFilterElement: C,
  7669. SVGForeignObjectElement: C,
  7670. SVGGElement: C,
  7671. SVGGeometryElement: C,
  7672. SVGGradientElement: C,
  7673. SVGGraphicsElement: C,
  7674. SVGImageElement: C,
  7675. SVGLength: C,
  7676. SVGLengthList: C,
  7677. SVGLinearGradientElement: C,
  7678. SVGLineElement: C,
  7679. SVGMarkerElement: C,
  7680. SVGMaskElement: C,
  7681. SVGMatrix: C,
  7682. SVGMetadataElement: C,
  7683. SVGMPathElement: C,
  7684. SVGNumber: C,
  7685. SVGNumberList: C,
  7686. SVGPathElement: C,
  7687. SVGPatternElement: C,
  7688. SVGPoint: C,
  7689. SVGPointList: C,
  7690. SVGPolygonElement: C,
  7691. SVGPolylineElement: C,
  7692. SVGPreserveAspectRatio: C,
  7693. SVGRadialGradientElement: C,
  7694. SVGRect: C,
  7695. SVGRectElement: C,
  7696. SVGScriptElement: C,
  7697. SVGSetElement: C,
  7698. SVGStopElement: C,
  7699. SVGStringList: C,
  7700. SVGStyleElement: C,
  7701. SVGSVGElement: C,
  7702. SVGSwitchElement: C,
  7703. SVGSymbolElement: C,
  7704. SVGTextContentElement: C,
  7705. SVGTextElement: C,
  7706. SVGTextPathElement: C,
  7707. SVGTextPositioningElement: C,
  7708. SVGTitleElement: C,
  7709. SVGTransform: C,
  7710. SVGTransformList: C,
  7711. SVGTSpanElement: C,
  7712. SVGUnitTypes: C,
  7713. SVGUseElement: C,
  7714. SVGViewElement: C,
  7715. TaskAttributionTiming: C,
  7716. Text: C,
  7717. TextEvent: C,
  7718. TextMetrics: C,
  7719. TextTrack: C,
  7720. TextTrackCue: C,
  7721. TextTrackCueList: C,
  7722. TextTrackList: C,
  7723. TimeRanges: C,
  7724. toolbar: O,
  7725. top: O,
  7726. Touch: C,
  7727. TouchEvent: C,
  7728. TouchList: C,
  7729. TrackEvent: C,
  7730. TransitionEvent: C,
  7731. TreeWalker: C,
  7732. UIEvent: C,
  7733. ValidityState: C,
  7734. visualViewport: O,
  7735. VisualViewport: C,
  7736. VTTCue: C,
  7737. WaveShaperNode: C,
  7738. WebAssembly: O,
  7739. WebGL2RenderingContext: C,
  7740. WebGLActiveInfo: C,
  7741. WebGLBuffer: C,
  7742. WebGLContextEvent: C,
  7743. WebGLFramebuffer: C,
  7744. WebGLProgram: C,
  7745. WebGLQuery: C,
  7746. WebGLRenderbuffer: C,
  7747. WebGLRenderingContext: C,
  7748. WebGLSampler: C,
  7749. WebGLShader: C,
  7750. WebGLShaderPrecisionFormat: C,
  7751. WebGLSync: C,
  7752. WebGLTexture: C,
  7753. WebGLTransformFeedback: C,
  7754. WebGLUniformLocation: C,
  7755. WebGLVertexArrayObject: C,
  7756. WebSocket: C,
  7757. WheelEvent: C,
  7758. Window: C,
  7759. Worker: C,
  7760. WritableStream: C,
  7761. XMLDocument: C,
  7762. XMLHttpRequest: C,
  7763. XMLHttpRequestEventTarget: C,
  7764. XMLHttpRequestUpload: C,
  7765. XMLSerializer: C,
  7766. XPathEvaluator: C,
  7767. XPathExpression: C,
  7768. XPathResult: C,
  7769. XSLTProcessor: C
  7770. };
  7771. for (const global of ['window', 'global', 'self', 'globalThis']) {
  7772. knownGlobals[global] = knownGlobals;
  7773. }
  7774. function getGlobalAtPath(path) {
  7775. let currentGlobal = knownGlobals;
  7776. for (const pathSegment of path) {
  7777. if (typeof pathSegment !== 'string') {
  7778. return null;
  7779. }
  7780. currentGlobal = currentGlobal[pathSegment];
  7781. if (!currentGlobal) {
  7782. return null;
  7783. }
  7784. }
  7785. return currentGlobal[ValueProperties];
  7786. }
  7787. class GlobalVariable extends Variable {
  7788. constructor() {
  7789. super(...arguments);
  7790. // Ensure we use live-bindings for globals as we do not know if they have
  7791. // been reassigned
  7792. this.isReassigned = true;
  7793. }
  7794. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7795. switch (interaction.type) {
  7796. // While there is no point in testing these cases as at the moment, they
  7797. // are also covered via other means, we keep them for completeness
  7798. case INTERACTION_ACCESSED:
  7799. case INTERACTION_ASSIGNED: {
  7800. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  7801. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7802. }
  7803. return;
  7804. }
  7805. case INTERACTION_CALLED: {
  7806. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7807. if (globalAtPath) {
  7808. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  7809. }
  7810. else {
  7811. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7812. }
  7813. return;
  7814. }
  7815. }
  7816. }
  7817. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  7818. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7819. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  7820. }
  7821. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7822. switch (interaction.type) {
  7823. case INTERACTION_ACCESSED: {
  7824. if (path.length === 0) {
  7825. // Technically, "undefined" is a global variable of sorts
  7826. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  7827. }
  7828. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  7829. }
  7830. case INTERACTION_ASSIGNED: {
  7831. return true;
  7832. }
  7833. case INTERACTION_CALLED: {
  7834. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7835. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  7836. }
  7837. }
  7838. }
  7839. }
  7840. const tdzVariableKinds = {
  7841. __proto__: null,
  7842. class: true,
  7843. const: true,
  7844. let: true,
  7845. var: true
  7846. };
  7847. class Identifier extends NodeBase {
  7848. constructor() {
  7849. super(...arguments);
  7850. this.variable = null;
  7851. this.isTDZAccess = null;
  7852. }
  7853. addExportedVariables(variables, exportNamesByVariable) {
  7854. if (exportNamesByVariable.has(this.variable)) {
  7855. variables.push(this.variable);
  7856. }
  7857. }
  7858. bind() {
  7859. if (!this.variable && is_reference(this, this.parent)) {
  7860. this.variable = this.scope.findVariable(this.name);
  7861. this.variable.addReference(this);
  7862. }
  7863. }
  7864. declare(kind, init) {
  7865. let variable;
  7866. const { treeshake } = this.context.options;
  7867. switch (kind) {
  7868. case 'var': {
  7869. variable = this.scope.addDeclaration(this, this.context, init, true);
  7870. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  7871. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  7872. variable.markInitializersForDeoptimization();
  7873. }
  7874. break;
  7875. }
  7876. case 'function': {
  7877. // in strict mode, functions are only hoisted within a scope but not across block scopes
  7878. variable = this.scope.addDeclaration(this, this.context, init, false);
  7879. break;
  7880. }
  7881. case 'let':
  7882. case 'const':
  7883. case 'class': {
  7884. variable = this.scope.addDeclaration(this, this.context, init, false);
  7885. break;
  7886. }
  7887. case 'parameter': {
  7888. variable = this.scope.addParameterDeclaration(this);
  7889. break;
  7890. }
  7891. /* istanbul ignore next */
  7892. default: {
  7893. /* istanbul ignore next */
  7894. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  7895. }
  7896. }
  7897. variable.kind = kind;
  7898. return [(this.variable = variable)];
  7899. }
  7900. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7901. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7902. }
  7903. deoptimizePath(path) {
  7904. if (path.length === 0 && !this.scope.contains(this.name)) {
  7905. this.disallowImportReassignment();
  7906. }
  7907. // We keep conditional chaining because an unknown Node could have an
  7908. // Identifier as property that might be deoptimized by default
  7909. this.variable?.deoptimizePath(path);
  7910. }
  7911. getLiteralValueAtPath(path, recursionTracker, origin) {
  7912. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  7913. }
  7914. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7915. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7916. return [expression, isPure || this.isPureFunction(path)];
  7917. }
  7918. hasEffects(context) {
  7919. if (!this.deoptimized)
  7920. this.applyDeoptimizations();
  7921. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  7922. return true;
  7923. }
  7924. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  7925. this.variable instanceof GlobalVariable &&
  7926. !this.isPureFunction(EMPTY_PATH) &&
  7927. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  7928. }
  7929. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7930. switch (interaction.type) {
  7931. case INTERACTION_ACCESSED: {
  7932. return (this.variable !== null &&
  7933. !this.isPureFunction(path) &&
  7934. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  7935. }
  7936. case INTERACTION_ASSIGNED: {
  7937. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  7938. }
  7939. case INTERACTION_CALLED: {
  7940. return (!this.isPureFunction(path) &&
  7941. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  7942. }
  7943. }
  7944. }
  7945. include() {
  7946. if (!this.deoptimized)
  7947. this.applyDeoptimizations();
  7948. if (!this.included) {
  7949. this.included = true;
  7950. if (this.variable !== null) {
  7951. this.context.includeVariableInModule(this.variable);
  7952. }
  7953. }
  7954. }
  7955. includeCallArguments(context, parameters) {
  7956. this.variable.includeCallArguments(context, parameters);
  7957. }
  7958. isPossibleTDZ() {
  7959. // return cached value to avoid issues with the next tree-shaking pass
  7960. if (this.isTDZAccess !== null)
  7961. return this.isTDZAccess;
  7962. if (!(this.variable instanceof LocalVariable &&
  7963. this.variable.kind &&
  7964. this.variable.kind in tdzVariableKinds &&
  7965. // we ignore possible TDZs due to circular module dependencies as
  7966. // otherwise we get many false positives
  7967. this.variable.module === this.context.module)) {
  7968. return (this.isTDZAccess = false);
  7969. }
  7970. let decl_id;
  7971. if (this.variable.declarations &&
  7972. this.variable.declarations.length === 1 &&
  7973. (decl_id = this.variable.declarations[0]) &&
  7974. this.start < decl_id.start &&
  7975. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  7976. // a variable accessed before its declaration
  7977. // in the same function or at top level of module
  7978. return (this.isTDZAccess = true);
  7979. }
  7980. if (!this.variable.initReached) {
  7981. // Either a const/let TDZ violation or
  7982. // var use before declaration was encountered.
  7983. return (this.isTDZAccess = true);
  7984. }
  7985. return (this.isTDZAccess = false);
  7986. }
  7987. markDeclarationReached() {
  7988. this.variable.initReached = true;
  7989. }
  7990. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  7991. if (this.variable) {
  7992. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  7993. if (name !== this.name) {
  7994. code.overwrite(this.start, this.end, name, {
  7995. contentOnly: true,
  7996. storeName: true
  7997. });
  7998. if (isShorthandProperty) {
  7999. code.prependRight(this.start, `${this.name}: `);
  8000. }
  8001. }
  8002. // In strict mode, any variable named "eval" must be the actual "eval" function
  8003. if (name === 'eval' &&
  8004. renderedParentType === CallExpression$1 &&
  8005. isCalleeOfRenderedParent) {
  8006. code.appendRight(this.start, '0, ');
  8007. }
  8008. }
  8009. }
  8010. applyDeoptimizations() {
  8011. this.deoptimized = true;
  8012. if (this.variable instanceof LocalVariable) {
  8013. this.variable.consolidateInitializers();
  8014. this.context.requestTreeshakingPass();
  8015. }
  8016. }
  8017. disallowImportReassignment() {
  8018. return this.context.error(errorIllegalImportReassignment(this.name, this.context.module.id), this.start);
  8019. }
  8020. getVariableRespectingTDZ() {
  8021. if (this.isPossibleTDZ()) {
  8022. return UNKNOWN_EXPRESSION;
  8023. }
  8024. return this.variable;
  8025. }
  8026. isPureFunction(path) {
  8027. let currentPureFunction = this.context.manualPureFunctions[this.name];
  8028. for (const segment of path) {
  8029. if (currentPureFunction) {
  8030. if (currentPureFunction[PureFunctionKey]) {
  8031. return true;
  8032. }
  8033. currentPureFunction = currentPureFunction[segment];
  8034. }
  8035. else {
  8036. return false;
  8037. }
  8038. }
  8039. return currentPureFunction?.[PureFunctionKey];
  8040. }
  8041. }
  8042. function closestParentFunctionOrProgram(node) {
  8043. while (node && !/^Program|Function/.test(node.type)) {
  8044. node = node.parent;
  8045. }
  8046. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  8047. return node;
  8048. }
  8049. function treeshakeNode(node, code, start, end) {
  8050. code.remove(start, end);
  8051. if (node.annotations) {
  8052. for (const annotation of node.annotations) {
  8053. if (annotation.start < start) {
  8054. code.remove(annotation.start, annotation.end);
  8055. }
  8056. else {
  8057. return;
  8058. }
  8059. }
  8060. }
  8061. }
  8062. function removeAnnotations(node, code) {
  8063. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  8064. node = node.parent;
  8065. }
  8066. if (node.annotations) {
  8067. for (const annotation of node.annotations) {
  8068. code.remove(annotation.start, annotation.end);
  8069. }
  8070. }
  8071. }
  8072. const NO_SEMICOLON = { isNoStatement: true };
  8073. // This assumes there are only white-space and comments between start and the string we are looking for
  8074. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  8075. let searchPos, charCodeAfterSlash;
  8076. searchPos = code.indexOf(searchString, start);
  8077. while (true) {
  8078. start = code.indexOf('/', start);
  8079. if (start === -1 || start >= searchPos)
  8080. return searchPos;
  8081. charCodeAfterSlash = code.charCodeAt(++start);
  8082. ++start;
  8083. // With our assumption, '/' always starts a comment. Determine comment type:
  8084. start =
  8085. charCodeAfterSlash === 47 /*"/"*/
  8086. ? code.indexOf('\n', start) + 1
  8087. : code.indexOf('*/', start) + 2;
  8088. if (start > searchPos) {
  8089. searchPos = code.indexOf(searchString, start);
  8090. }
  8091. }
  8092. }
  8093. const NON_WHITESPACE = /\S/g;
  8094. function findNonWhiteSpace(code, index) {
  8095. NON_WHITESPACE.lastIndex = index;
  8096. const result = NON_WHITESPACE.exec(code);
  8097. return result.index;
  8098. }
  8099. // This assumes "code" only contains white-space and comments
  8100. // Returns position of line-comment if applicable
  8101. function findFirstLineBreakOutsideComment(code) {
  8102. let lineBreakPos, charCodeAfterSlash, start = 0;
  8103. lineBreakPos = code.indexOf('\n', start);
  8104. while (true) {
  8105. start = code.indexOf('/', start);
  8106. if (start === -1 || start > lineBreakPos)
  8107. return [lineBreakPos, lineBreakPos + 1];
  8108. // With our assumption, '/' always starts a comment. Determine comment type:
  8109. charCodeAfterSlash = code.charCodeAt(start + 1);
  8110. if (charCodeAfterSlash === 47 /*"/"*/)
  8111. return [start, lineBreakPos + 1];
  8112. start = code.indexOf('*/', start + 3) + 2;
  8113. if (start > lineBreakPos) {
  8114. lineBreakPos = code.indexOf('\n', start);
  8115. }
  8116. }
  8117. }
  8118. function renderStatementList(statements, code, start, end, options) {
  8119. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  8120. let nextNode = statements[0];
  8121. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  8122. if (nextNodeNeedsBoundaries) {
  8123. nextNodeStart =
  8124. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  8125. }
  8126. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  8127. currentNode = nextNode;
  8128. currentNodeStart = nextNodeStart;
  8129. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  8130. nextNode = statements[nextIndex];
  8131. nextNodeNeedsBoundaries =
  8132. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  8133. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  8134. nextNodeStart =
  8135. currentNode.end +
  8136. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  8137. if (currentNode.included) {
  8138. currentNodeNeedsBoundaries
  8139. ? currentNode.render(code, options, {
  8140. end: nextNodeStart,
  8141. start: currentNodeStart
  8142. })
  8143. : currentNode.render(code, options);
  8144. }
  8145. else {
  8146. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  8147. }
  8148. }
  8149. else {
  8150. currentNode.render(code, options);
  8151. }
  8152. }
  8153. }
  8154. // This assumes that the first character is not part of the first node
  8155. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  8156. const splitUpNodes = [];
  8157. let node, nextNodeStart, contentEnd, char;
  8158. let separator = start - 1;
  8159. for (const nextNode of nodes) {
  8160. if (node !== undefined) {
  8161. separator =
  8162. node.end +
  8163. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  8164. }
  8165. nextNodeStart = contentEnd =
  8166. separator +
  8167. 1 +
  8168. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  8169. while (((char = code.original.charCodeAt(nextNodeStart)),
  8170. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  8171. nextNodeStart++;
  8172. if (node !== undefined) {
  8173. splitUpNodes.push({
  8174. contentEnd,
  8175. end: nextNodeStart,
  8176. node,
  8177. separator,
  8178. start
  8179. });
  8180. }
  8181. node = nextNode;
  8182. start = nextNodeStart;
  8183. }
  8184. splitUpNodes.push({
  8185. contentEnd: end,
  8186. end,
  8187. node: node,
  8188. separator: null,
  8189. start
  8190. });
  8191. return splitUpNodes;
  8192. }
  8193. // This assumes there are only white-space and comments between start and end
  8194. function removeLineBreaks(code, start, end) {
  8195. while (true) {
  8196. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  8197. if (removeStart === -1) {
  8198. break;
  8199. }
  8200. code.remove(start + removeStart, (start += removeEnd));
  8201. }
  8202. }
  8203. class BlockScope extends ChildScope {
  8204. addDeclaration(identifier, context, init, isHoisted) {
  8205. if (isHoisted) {
  8206. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  8207. // Necessary to make sure the init is deoptimized for conditional declarations.
  8208. // We cannot call deoptimizePath here.
  8209. variable.markInitializersForDeoptimization();
  8210. return variable;
  8211. }
  8212. else {
  8213. return super.addDeclaration(identifier, context, init, false);
  8214. }
  8215. }
  8216. }
  8217. class ExpressionStatement extends NodeBase {
  8218. initialise() {
  8219. if (this.directive &&
  8220. this.directive !== 'use strict' &&
  8221. this.parent.type === Program$1) {
  8222. this.context.warn(
  8223. // This is necessary, because either way (deleting or not) can lead to errors.
  8224. errorModuleLevelDirective(this.directive, this.context.module.id), this.start);
  8225. }
  8226. }
  8227. render(code, options) {
  8228. super.render(code, options);
  8229. if (this.included)
  8230. this.insertSemicolon(code);
  8231. }
  8232. shouldBeIncluded(context) {
  8233. if (this.directive && this.directive !== 'use strict')
  8234. return this.parent.type !== Program$1;
  8235. return super.shouldBeIncluded(context);
  8236. }
  8237. applyDeoptimizations() { }
  8238. }
  8239. class BlockStatement extends NodeBase {
  8240. constructor() {
  8241. super(...arguments);
  8242. this.directlyIncluded = false;
  8243. }
  8244. addImplicitReturnExpressionToScope() {
  8245. const lastStatement = this.body[this.body.length - 1];
  8246. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  8247. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  8248. }
  8249. }
  8250. createScope(parentScope) {
  8251. this.scope = this.parent.preventChildBlockScope
  8252. ? parentScope
  8253. : new BlockScope(parentScope);
  8254. }
  8255. hasEffects(context) {
  8256. if (this.deoptimizeBody)
  8257. return true;
  8258. for (const node of this.body) {
  8259. if (context.brokenFlow)
  8260. break;
  8261. if (node.hasEffects(context))
  8262. return true;
  8263. }
  8264. return false;
  8265. }
  8266. include(context, includeChildrenRecursively) {
  8267. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  8268. this.included = true;
  8269. this.directlyIncluded = true;
  8270. if (this.deoptimizeBody)
  8271. includeChildrenRecursively = true;
  8272. for (const node of this.body) {
  8273. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8274. node.include(context, includeChildrenRecursively);
  8275. }
  8276. }
  8277. }
  8278. initialise() {
  8279. const firstBodyStatement = this.body[0];
  8280. this.deoptimizeBody =
  8281. firstBodyStatement instanceof ExpressionStatement &&
  8282. firstBodyStatement.directive === 'use asm';
  8283. }
  8284. render(code, options) {
  8285. if (this.body.length > 0) {
  8286. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  8287. }
  8288. else {
  8289. super.render(code, options);
  8290. }
  8291. }
  8292. }
  8293. class RestElement extends NodeBase {
  8294. constructor() {
  8295. super(...arguments);
  8296. this.declarationInit = null;
  8297. }
  8298. addExportedVariables(variables, exportNamesByVariable) {
  8299. this.argument.addExportedVariables(variables, exportNamesByVariable);
  8300. }
  8301. declare(kind, init) {
  8302. this.declarationInit = init;
  8303. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  8304. }
  8305. deoptimizePath(path) {
  8306. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  8307. }
  8308. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8309. return (path.length > 0 ||
  8310. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  8311. }
  8312. markDeclarationReached() {
  8313. this.argument.markDeclarationReached();
  8314. }
  8315. applyDeoptimizations() {
  8316. this.deoptimized = true;
  8317. if (this.declarationInit !== null) {
  8318. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  8319. this.context.requestTreeshakingPass();
  8320. }
  8321. }
  8322. }
  8323. class FunctionBase extends NodeBase {
  8324. constructor() {
  8325. super(...arguments);
  8326. this.objectEntity = null;
  8327. this.deoptimizedReturn = false;
  8328. }
  8329. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8330. if (interaction.type === INTERACTION_CALLED) {
  8331. const { parameters } = this.scope;
  8332. const { args } = interaction;
  8333. let hasRest = false;
  8334. for (let position = 0; position < args.length - 1; position++) {
  8335. const parameter = this.params[position];
  8336. // Only the "this" argument arg[0] can be null
  8337. const argument = args[position + 1];
  8338. if (hasRest || parameter instanceof RestElement) {
  8339. hasRest = true;
  8340. argument.deoptimizePath(UNKNOWN_PATH);
  8341. }
  8342. else if (parameter instanceof Identifier) {
  8343. parameters[position][0].addEntityToBeDeoptimized(argument);
  8344. this.addArgumentToBeDeoptimized(argument);
  8345. }
  8346. else if (parameter) {
  8347. argument.deoptimizePath(UNKNOWN_PATH);
  8348. }
  8349. else {
  8350. this.addArgumentToBeDeoptimized(argument);
  8351. }
  8352. }
  8353. }
  8354. else {
  8355. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8356. }
  8357. }
  8358. deoptimizePath(path) {
  8359. this.getObjectEntity().deoptimizePath(path);
  8360. if (path.length === 1 && path[0] === UnknownKey) {
  8361. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  8362. // which means the return expression needs to be reassigned
  8363. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  8364. }
  8365. }
  8366. getLiteralValueAtPath(path, recursionTracker, origin) {
  8367. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8368. }
  8369. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8370. if (path.length > 0) {
  8371. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8372. }
  8373. if (this.async) {
  8374. if (!this.deoptimizedReturn) {
  8375. this.deoptimizedReturn = true;
  8376. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  8377. this.context.requestTreeshakingPass();
  8378. }
  8379. return UNKNOWN_RETURN_EXPRESSION;
  8380. }
  8381. return [this.scope.getReturnExpression(), false];
  8382. }
  8383. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8384. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  8385. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  8386. }
  8387. if (this.async) {
  8388. const { propertyReadSideEffects } = this.context.options
  8389. .treeshake;
  8390. const returnExpression = this.scope.getReturnExpression();
  8391. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  8392. (propertyReadSideEffects &&
  8393. (propertyReadSideEffects === 'always' ||
  8394. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  8395. return true;
  8396. }
  8397. }
  8398. for (const parameter of this.params) {
  8399. if (parameter.hasEffects(context))
  8400. return true;
  8401. }
  8402. return false;
  8403. }
  8404. include(context, includeChildrenRecursively) {
  8405. if (!this.deoptimized)
  8406. this.applyDeoptimizations();
  8407. this.included = true;
  8408. const { brokenFlow } = context;
  8409. context.brokenFlow = false;
  8410. this.body.include(context, includeChildrenRecursively);
  8411. context.brokenFlow = brokenFlow;
  8412. }
  8413. includeCallArguments(context, parameters) {
  8414. this.scope.includeCallArguments(context, parameters);
  8415. }
  8416. initialise() {
  8417. this.scope.addParameterVariables(this.params.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  8418. if (this.body instanceof BlockStatement) {
  8419. this.body.addImplicitReturnExpressionToScope();
  8420. }
  8421. else {
  8422. this.scope.addReturnExpression(this.body);
  8423. }
  8424. }
  8425. parseNode(esTreeNode) {
  8426. if (esTreeNode.body.type === BlockStatement$1) {
  8427. this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  8428. }
  8429. super.parseNode(esTreeNode);
  8430. }
  8431. addArgumentToBeDeoptimized(_argument) { }
  8432. applyDeoptimizations() { }
  8433. }
  8434. FunctionBase.prototype.preventChildBlockScope = true;
  8435. class ArrowFunctionExpression extends FunctionBase {
  8436. constructor() {
  8437. super(...arguments);
  8438. this.objectEntity = null;
  8439. }
  8440. createScope(parentScope) {
  8441. this.scope = new ReturnValueScope(parentScope, this.context);
  8442. }
  8443. hasEffects() {
  8444. if (!this.deoptimized)
  8445. this.applyDeoptimizations();
  8446. return false;
  8447. }
  8448. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8449. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  8450. return true;
  8451. if (interaction.type === INTERACTION_CALLED) {
  8452. const { ignore, brokenFlow } = context;
  8453. context.ignore = {
  8454. breaks: false,
  8455. continues: false,
  8456. labels: new Set(),
  8457. returnYield: true,
  8458. this: false
  8459. };
  8460. if (this.body.hasEffects(context))
  8461. return true;
  8462. context.ignore = ignore;
  8463. context.brokenFlow = brokenFlow;
  8464. }
  8465. return false;
  8466. }
  8467. include(context, includeChildrenRecursively) {
  8468. super.include(context, includeChildrenRecursively);
  8469. for (const parameter of this.params) {
  8470. if (!(parameter instanceof Identifier)) {
  8471. parameter.include(context, includeChildrenRecursively);
  8472. }
  8473. }
  8474. }
  8475. getObjectEntity() {
  8476. if (this.objectEntity !== null) {
  8477. return this.objectEntity;
  8478. }
  8479. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  8480. }
  8481. }
  8482. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  8483. if (exportedVariables.length === 1 &&
  8484. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  8485. const variable = exportedVariables[0];
  8486. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
  8487. }
  8488. else {
  8489. const fields = [];
  8490. for (const variable of exportedVariables) {
  8491. for (const exportName of exportNamesByVariable.get(variable)) {
  8492. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  8493. }
  8494. }
  8495. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  8496. }
  8497. }
  8498. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  8499. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  8500. code.appendLeft(expressionEnd, ')');
  8501. }
  8502. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  8503. const { _, getDirectReturnIifeLeft } = options.snippets;
  8504. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  8505. code.appendLeft(expressionEnd, ')');
  8506. }
  8507. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  8508. const { _, getPropertyAccess } = options.snippets;
  8509. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  8510. if (needsParens) {
  8511. code.prependRight(expressionStart, '(');
  8512. code.appendLeft(expressionEnd, ')');
  8513. }
  8514. }
  8515. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  8516. const { _ } = options.snippets;
  8517. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  8518. if (needsParens) {
  8519. code.prependRight(expressionStart, '(');
  8520. code.appendLeft(expressionEnd, ')');
  8521. }
  8522. }
  8523. class ObjectPattern extends NodeBase {
  8524. addExportedVariables(variables, exportNamesByVariable) {
  8525. for (const property of this.properties) {
  8526. if (property.type === Property$1) {
  8527. property.value.addExportedVariables(variables, exportNamesByVariable);
  8528. }
  8529. else {
  8530. property.argument.addExportedVariables(variables, exportNamesByVariable);
  8531. }
  8532. }
  8533. }
  8534. declare(kind, init) {
  8535. const variables = [];
  8536. for (const property of this.properties) {
  8537. variables.push(...property.declare(kind, init));
  8538. }
  8539. return variables;
  8540. }
  8541. deoptimizePath(path) {
  8542. if (path.length === 0) {
  8543. for (const property of this.properties) {
  8544. property.deoptimizePath(path);
  8545. }
  8546. }
  8547. }
  8548. hasEffectsOnInteractionAtPath(
  8549. // At the moment, this is only triggered for assignment left-hand sides,
  8550. // where the path is empty
  8551. _path, interaction, context) {
  8552. for (const property of this.properties) {
  8553. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  8554. return true;
  8555. }
  8556. return false;
  8557. }
  8558. markDeclarationReached() {
  8559. for (const property of this.properties) {
  8560. property.markDeclarationReached();
  8561. }
  8562. }
  8563. }
  8564. class AssignmentExpression extends NodeBase {
  8565. hasEffects(context) {
  8566. const { deoptimized, left, operator, right } = this;
  8567. if (!deoptimized)
  8568. this.applyDeoptimizations();
  8569. // MemberExpressions do not access the property before assignments if the
  8570. // operator is '='.
  8571. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, operator !== '='));
  8572. }
  8573. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8574. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  8575. }
  8576. include(context, includeChildrenRecursively) {
  8577. const { deoptimized, left, right, operator } = this;
  8578. if (!deoptimized)
  8579. this.applyDeoptimizations();
  8580. this.included = true;
  8581. if (includeChildrenRecursively ||
  8582. operator !== '=' ||
  8583. left.included ||
  8584. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  8585. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  8586. }
  8587. right.include(context, includeChildrenRecursively);
  8588. }
  8589. initialise() {
  8590. this.left.setAssignedValue(this.right);
  8591. }
  8592. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  8593. const { left, right, start, end, parent } = this;
  8594. if (left.included) {
  8595. left.render(code, options);
  8596. right.render(code, options);
  8597. }
  8598. else {
  8599. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  8600. code.remove(start, inclusionStart);
  8601. if (preventASI) {
  8602. removeLineBreaks(code, inclusionStart, right.start);
  8603. }
  8604. right.render(code, options, {
  8605. renderedParentType: renderedParentType || parent.type,
  8606. renderedSurroundingElement: renderedSurroundingElement || parent.type
  8607. });
  8608. }
  8609. if (options.format === 'system') {
  8610. if (left instanceof Identifier) {
  8611. const variable = left.variable;
  8612. const exportNames = options.exportNamesByVariable.get(variable);
  8613. if (exportNames) {
  8614. if (exportNames.length === 1) {
  8615. renderSystemExportExpression(variable, start, end, code, options);
  8616. }
  8617. else {
  8618. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  8619. }
  8620. return;
  8621. }
  8622. }
  8623. else {
  8624. const systemPatternExports = [];
  8625. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  8626. if (systemPatternExports.length > 0) {
  8627. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  8628. return;
  8629. }
  8630. }
  8631. }
  8632. if (left.included &&
  8633. left instanceof ObjectPattern &&
  8634. (renderedSurroundingElement === ExpressionStatement$1 ||
  8635. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  8636. code.appendRight(start, '(');
  8637. code.prependLeft(end, ')');
  8638. }
  8639. }
  8640. applyDeoptimizations() {
  8641. this.deoptimized = true;
  8642. this.left.deoptimizePath(EMPTY_PATH);
  8643. this.right.deoptimizePath(UNKNOWN_PATH);
  8644. this.context.requestTreeshakingPass();
  8645. }
  8646. }
  8647. class AssignmentPattern extends NodeBase {
  8648. addExportedVariables(variables, exportNamesByVariable) {
  8649. this.left.addExportedVariables(variables, exportNamesByVariable);
  8650. }
  8651. declare(kind, init) {
  8652. return this.left.declare(kind, init);
  8653. }
  8654. deoptimizePath(path) {
  8655. path.length === 0 && this.left.deoptimizePath(path);
  8656. }
  8657. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8658. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  8659. }
  8660. markDeclarationReached() {
  8661. this.left.markDeclarationReached();
  8662. }
  8663. render(code, options, { isShorthandProperty } = BLANK) {
  8664. this.left.render(code, options, { isShorthandProperty });
  8665. this.right.render(code, options);
  8666. }
  8667. applyDeoptimizations() {
  8668. this.deoptimized = true;
  8669. this.left.deoptimizePath(EMPTY_PATH);
  8670. this.right.deoptimizePath(UNKNOWN_PATH);
  8671. this.context.requestTreeshakingPass();
  8672. }
  8673. }
  8674. class ArgumentsVariable extends LocalVariable {
  8675. constructor(context) {
  8676. super('arguments', null, UNKNOWN_EXPRESSION, context);
  8677. this.deoptimizedArguments = [];
  8678. }
  8679. addArgumentToBeDeoptimized(argument) {
  8680. if (this.included) {
  8681. argument.deoptimizePath(UNKNOWN_PATH);
  8682. }
  8683. else {
  8684. this.deoptimizedArguments.push(argument);
  8685. }
  8686. }
  8687. hasEffectsOnInteractionAtPath(path, { type }) {
  8688. return type !== INTERACTION_ACCESSED || path.length > 1;
  8689. }
  8690. include() {
  8691. super.include();
  8692. for (const argument of this.deoptimizedArguments) {
  8693. argument.deoptimizePath(UNKNOWN_PATH);
  8694. }
  8695. this.deoptimizedArguments.length = 0;
  8696. }
  8697. }
  8698. class ThisVariable extends ParameterVariable {
  8699. constructor(context) {
  8700. super('this', null, context);
  8701. }
  8702. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8703. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  8704. }
  8705. }
  8706. class FunctionScope extends ReturnValueScope {
  8707. constructor(parent, context) {
  8708. super(parent, context);
  8709. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  8710. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  8711. }
  8712. findLexicalBoundary() {
  8713. return this;
  8714. }
  8715. includeCallArguments(context, parameters) {
  8716. super.includeCallArguments(context, parameters);
  8717. if (this.argumentsVariable.included) {
  8718. for (const argument of parameters) {
  8719. if (!argument.included) {
  8720. argument.include(context, false);
  8721. }
  8722. }
  8723. }
  8724. }
  8725. }
  8726. class FunctionNode extends FunctionBase {
  8727. constructor() {
  8728. super(...arguments);
  8729. this.objectEntity = null;
  8730. }
  8731. createScope(parentScope) {
  8732. this.scope = new FunctionScope(parentScope, this.context);
  8733. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  8734. // This makes sure that all deoptimizations of "this" are applied to the
  8735. // constructed entity.
  8736. this.scope.thisVariable.addEntityToBeDeoptimized(this.constructedEntity);
  8737. }
  8738. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8739. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8740. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  8741. // args[0] is the "this" argument
  8742. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.args[0]);
  8743. }
  8744. }
  8745. hasEffects(context) {
  8746. if (!this.deoptimized)
  8747. this.applyDeoptimizations();
  8748. return !!this.id?.hasEffects(context);
  8749. }
  8750. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8751. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  8752. return true;
  8753. if (interaction.type === INTERACTION_CALLED) {
  8754. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  8755. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  8756. const { brokenFlow, ignore, replacedVariableInits } = context;
  8757. context.ignore = {
  8758. breaks: false,
  8759. continues: false,
  8760. labels: new Set(),
  8761. returnYield: true,
  8762. this: interaction.withNew
  8763. };
  8764. if (this.body.hasEffects(context))
  8765. return true;
  8766. context.brokenFlow = brokenFlow;
  8767. if (thisInit) {
  8768. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  8769. }
  8770. else {
  8771. replacedVariableInits.delete(this.scope.thisVariable);
  8772. }
  8773. context.ignore = ignore;
  8774. }
  8775. return false;
  8776. }
  8777. include(context, includeChildrenRecursively) {
  8778. super.include(context, includeChildrenRecursively);
  8779. this.id?.include();
  8780. const hasArguments = this.scope.argumentsVariable.included;
  8781. for (const parameter of this.params) {
  8782. if (!(parameter instanceof Identifier) || hasArguments) {
  8783. parameter.include(context, includeChildrenRecursively);
  8784. }
  8785. }
  8786. }
  8787. initialise() {
  8788. super.initialise();
  8789. this.id?.declare('function', this);
  8790. }
  8791. addArgumentToBeDeoptimized(argument) {
  8792. this.scope.argumentsVariable.addArgumentToBeDeoptimized(argument);
  8793. }
  8794. getObjectEntity() {
  8795. if (this.objectEntity !== null) {
  8796. return this.objectEntity;
  8797. }
  8798. return (this.objectEntity = new ObjectEntity([
  8799. {
  8800. key: 'prototype',
  8801. kind: 'init',
  8802. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  8803. }
  8804. ], OBJECT_PROTOTYPE));
  8805. }
  8806. }
  8807. class AwaitExpression extends NodeBase {
  8808. hasEffects() {
  8809. if (!this.deoptimized)
  8810. this.applyDeoptimizations();
  8811. return true;
  8812. }
  8813. include(context, includeChildrenRecursively) {
  8814. if (!this.deoptimized)
  8815. this.applyDeoptimizations();
  8816. if (!this.included) {
  8817. this.included = true;
  8818. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  8819. let parent = this.parent;
  8820. do {
  8821. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  8822. break checkTopLevelAwait;
  8823. } while ((parent = parent.parent));
  8824. this.context.usesTopLevelAwait = true;
  8825. }
  8826. }
  8827. this.argument.include(context, includeChildrenRecursively);
  8828. }
  8829. }
  8830. const binaryOperators = {
  8831. '!=': (left, right) => left != right,
  8832. '!==': (left, right) => left !== right,
  8833. '%': (left, right) => left % right,
  8834. '&': (left, right) => left & right,
  8835. '*': (left, right) => left * right,
  8836. // At the moment, "**" will be transpiled to Math.pow
  8837. '**': (left, right) => left ** right,
  8838. '+': (left, right) => left + right,
  8839. '-': (left, right) => left - right,
  8840. '/': (left, right) => left / right,
  8841. '<': (left, right) => left < right,
  8842. '<<': (left, right) => left << right,
  8843. '<=': (left, right) => left <= right,
  8844. '==': (left, right) => left == right,
  8845. '===': (left, right) => left === right,
  8846. '>': (left, right) => left > right,
  8847. '>=': (left, right) => left >= right,
  8848. '>>': (left, right) => left >> right,
  8849. '>>>': (left, right) => left >>> right,
  8850. '^': (left, right) => left ^ right,
  8851. '|': (left, right) => left | right
  8852. // We use the fallback for cases where we return something unknown
  8853. // in: () => UnknownValue,
  8854. // instanceof: () => UnknownValue,
  8855. };
  8856. class BinaryExpression extends NodeBase {
  8857. deoptimizeCache() { }
  8858. getLiteralValueAtPath(path, recursionTracker, origin) {
  8859. if (path.length > 0)
  8860. return UnknownValue;
  8861. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8862. if (typeof leftValue === 'symbol')
  8863. return UnknownValue;
  8864. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8865. if (typeof rightValue === 'symbol')
  8866. return UnknownValue;
  8867. const operatorFunction = binaryOperators[this.operator];
  8868. if (!operatorFunction)
  8869. return UnknownValue;
  8870. return operatorFunction(leftValue, rightValue);
  8871. }
  8872. hasEffects(context) {
  8873. // support some implicit type coercion runtime errors
  8874. if (this.operator === '+' &&
  8875. this.parent instanceof ExpressionStatement &&
  8876. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  8877. return true;
  8878. }
  8879. return super.hasEffects(context);
  8880. }
  8881. hasEffectsOnInteractionAtPath(path, { type }) {
  8882. return type !== INTERACTION_ACCESSED || path.length > 1;
  8883. }
  8884. render(code, options, { renderedSurroundingElement } = BLANK) {
  8885. this.left.render(code, options, { renderedSurroundingElement });
  8886. this.right.render(code, options);
  8887. }
  8888. }
  8889. class BreakStatement extends NodeBase {
  8890. hasEffects(context) {
  8891. if (this.label) {
  8892. if (!context.ignore.labels.has(this.label.name))
  8893. return true;
  8894. context.includedLabels.add(this.label.name);
  8895. }
  8896. else {
  8897. if (!context.ignore.breaks)
  8898. return true;
  8899. context.hasBreak = true;
  8900. }
  8901. context.brokenFlow = true;
  8902. return false;
  8903. }
  8904. include(context) {
  8905. this.included = true;
  8906. if (this.label) {
  8907. this.label.include();
  8908. context.includedLabels.add(this.label.name);
  8909. }
  8910. else {
  8911. context.hasBreak = true;
  8912. }
  8913. context.brokenFlow = true;
  8914. }
  8915. }
  8916. function renderCallArguments(code, options, node) {
  8917. if (node.arguments.length > 0) {
  8918. if (node.arguments[node.arguments.length - 1].included) {
  8919. for (const argument of node.arguments) {
  8920. argument.render(code, options);
  8921. }
  8922. }
  8923. else {
  8924. let lastIncludedIndex = node.arguments.length - 2;
  8925. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  8926. lastIncludedIndex--;
  8927. }
  8928. if (lastIncludedIndex >= 0) {
  8929. for (let index = 0; index <= lastIncludedIndex; index++) {
  8930. node.arguments[index].render(code, options);
  8931. }
  8932. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  8933. }
  8934. else {
  8935. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  8936. }
  8937. }
  8938. }
  8939. }
  8940. class Literal extends NodeBase {
  8941. deoptimizeArgumentsOnInteractionAtPath() { }
  8942. getLiteralValueAtPath(path) {
  8943. if (path.length > 0 ||
  8944. // unknown literals can also be null but do not start with an "n"
  8945. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  8946. typeof this.value === 'bigint' ||
  8947. // to support shims for regular expressions
  8948. this.context.code.charCodeAt(this.start) === 47) {
  8949. return UnknownValue;
  8950. }
  8951. return this.value;
  8952. }
  8953. getReturnExpressionWhenCalledAtPath(path) {
  8954. if (path.length !== 1)
  8955. return UNKNOWN_RETURN_EXPRESSION;
  8956. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  8957. }
  8958. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8959. switch (interaction.type) {
  8960. case INTERACTION_ACCESSED: {
  8961. return path.length > (this.value === null ? 0 : 1);
  8962. }
  8963. case INTERACTION_ASSIGNED: {
  8964. return true;
  8965. }
  8966. case INTERACTION_CALLED: {
  8967. if (this.included &&
  8968. this.value instanceof RegExp &&
  8969. (this.value.global || this.value.sticky)) {
  8970. return true;
  8971. }
  8972. return (path.length !== 1 ||
  8973. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  8974. }
  8975. }
  8976. }
  8977. initialise() {
  8978. this.members = getLiteralMembersForValue(this.value);
  8979. }
  8980. parseNode(esTreeNode) {
  8981. this.value = esTreeNode.value;
  8982. this.regex = esTreeNode.regex;
  8983. super.parseNode(esTreeNode);
  8984. }
  8985. render(code) {
  8986. if (typeof this.value === 'string') {
  8987. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  8988. }
  8989. }
  8990. }
  8991. // To avoid infinite recursions
  8992. const MAX_PATH_DEPTH = 7;
  8993. function getResolvablePropertyKey(memberExpression) {
  8994. return memberExpression.computed
  8995. ? getResolvableComputedPropertyKey(memberExpression.property)
  8996. : memberExpression.property.name;
  8997. }
  8998. function getResolvableComputedPropertyKey(propertyKey) {
  8999. if (propertyKey instanceof Literal) {
  9000. return String(propertyKey.value);
  9001. }
  9002. return null;
  9003. }
  9004. function getPathIfNotComputed(memberExpression) {
  9005. const nextPathKey = memberExpression.propertyKey;
  9006. const object = memberExpression.object;
  9007. if (typeof nextPathKey === 'string') {
  9008. if (object instanceof Identifier) {
  9009. return [
  9010. { key: object.name, pos: object.start },
  9011. { key: nextPathKey, pos: memberExpression.property.start }
  9012. ];
  9013. }
  9014. if (object instanceof MemberExpression) {
  9015. const parentPath = getPathIfNotComputed(object);
  9016. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  9017. }
  9018. }
  9019. return null;
  9020. }
  9021. function getStringFromPath(path) {
  9022. let pathString = path[0].key;
  9023. for (let index = 1; index < path.length; index++) {
  9024. pathString += '.' + path[index].key;
  9025. }
  9026. return pathString;
  9027. }
  9028. class MemberExpression extends NodeBase {
  9029. constructor() {
  9030. super(...arguments);
  9031. this.variable = null;
  9032. this.assignmentDeoptimized = false;
  9033. this.bound = false;
  9034. this.expressionsToBeDeoptimized = [];
  9035. this.isUndefined = false;
  9036. }
  9037. bind() {
  9038. this.bound = true;
  9039. const path = getPathIfNotComputed(this);
  9040. const baseVariable = path && this.scope.findVariable(path[0].key);
  9041. if (baseVariable?.isNamespace) {
  9042. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
  9043. if (!resolvedVariable) {
  9044. super.bind();
  9045. }
  9046. else if (resolvedVariable === 'undefined') {
  9047. this.isUndefined = true;
  9048. }
  9049. else {
  9050. this.variable = resolvedVariable;
  9051. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  9052. }
  9053. }
  9054. else {
  9055. super.bind();
  9056. }
  9057. }
  9058. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9059. if (this.variable) {
  9060. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9061. }
  9062. else if (!this.isUndefined) {
  9063. if (path.length < MAX_PATH_DEPTH) {
  9064. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  9065. }
  9066. else {
  9067. deoptimizeInteraction(interaction);
  9068. }
  9069. }
  9070. }
  9071. deoptimizeCache() {
  9072. const { expressionsToBeDeoptimized, object } = this;
  9073. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  9074. this.propertyKey = UnknownKey;
  9075. object.deoptimizePath(UNKNOWN_PATH);
  9076. for (const expression of expressionsToBeDeoptimized) {
  9077. expression.deoptimizeCache();
  9078. }
  9079. }
  9080. deoptimizePath(path) {
  9081. if (path.length === 0)
  9082. this.disallowNamespaceReassignment();
  9083. if (this.variable) {
  9084. this.variable.deoptimizePath(path);
  9085. }
  9086. else if (!this.isUndefined && path.length < MAX_PATH_DEPTH) {
  9087. const propertyKey = this.getPropertyKey();
  9088. this.object.deoptimizePath([
  9089. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  9090. ...path
  9091. ]);
  9092. }
  9093. }
  9094. getLiteralValueAtPath(path, recursionTracker, origin) {
  9095. if (this.variable) {
  9096. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  9097. }
  9098. if (this.isUndefined) {
  9099. return undefined;
  9100. }
  9101. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  9102. this.expressionsToBeDeoptimized.push(origin);
  9103. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  9104. }
  9105. return UnknownValue;
  9106. }
  9107. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9108. if (this.variable) {
  9109. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9110. }
  9111. if (this.isUndefined) {
  9112. return [UNDEFINED_EXPRESSION, false];
  9113. }
  9114. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  9115. this.expressionsToBeDeoptimized.push(origin);
  9116. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  9117. }
  9118. return UNKNOWN_RETURN_EXPRESSION;
  9119. }
  9120. hasEffects(context) {
  9121. if (!this.deoptimized)
  9122. this.applyDeoptimizations();
  9123. return (this.property.hasEffects(context) ||
  9124. this.object.hasEffects(context) ||
  9125. this.hasAccessEffect(context));
  9126. }
  9127. hasEffectsAsAssignmentTarget(context, checkAccess) {
  9128. if (checkAccess && !this.deoptimized)
  9129. this.applyDeoptimizations();
  9130. if (!this.assignmentDeoptimized)
  9131. this.applyAssignmentDeoptimization();
  9132. return (this.property.hasEffects(context) ||
  9133. this.object.hasEffects(context) ||
  9134. (checkAccess && this.hasAccessEffect(context)) ||
  9135. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  9136. }
  9137. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9138. if (this.variable) {
  9139. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  9140. }
  9141. if (this.isUndefined) {
  9142. return true;
  9143. }
  9144. if (path.length < MAX_PATH_DEPTH) {
  9145. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  9146. }
  9147. return true;
  9148. }
  9149. include(context, includeChildrenRecursively) {
  9150. if (!this.deoptimized)
  9151. this.applyDeoptimizations();
  9152. this.includeProperties(context, includeChildrenRecursively);
  9153. }
  9154. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  9155. if (!this.assignmentDeoptimized)
  9156. this.applyAssignmentDeoptimization();
  9157. if (deoptimizeAccess) {
  9158. this.include(context, includeChildrenRecursively);
  9159. }
  9160. else {
  9161. this.includeProperties(context, includeChildrenRecursively);
  9162. }
  9163. }
  9164. includeCallArguments(context, parameters) {
  9165. if (this.variable) {
  9166. this.variable.includeCallArguments(context, parameters);
  9167. }
  9168. else {
  9169. super.includeCallArguments(context, parameters);
  9170. }
  9171. }
  9172. initialise() {
  9173. this.propertyKey = getResolvablePropertyKey(this);
  9174. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  9175. }
  9176. isSkippedAsOptional(origin) {
  9177. return (!this.variable &&
  9178. !this.isUndefined &&
  9179. (this.object.isSkippedAsOptional?.(origin) ||
  9180. (this.optional &&
  9181. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null)));
  9182. }
  9183. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  9184. if (this.variable || this.isUndefined) {
  9185. const { snippets: { getPropertyAccess } } = options;
  9186. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  9187. if (renderedParentType && isCalleeOfRenderedParent)
  9188. replacement = '0, ' + replacement;
  9189. code.overwrite(this.start, this.end, replacement, {
  9190. contentOnly: true,
  9191. storeName: true
  9192. });
  9193. }
  9194. else {
  9195. if (renderedParentType && isCalleeOfRenderedParent) {
  9196. code.appendRight(this.start, '0, ');
  9197. }
  9198. this.object.render(code, options, { renderedSurroundingElement });
  9199. this.property.render(code, options);
  9200. }
  9201. }
  9202. setAssignedValue(value) {
  9203. this.assignmentInteraction = {
  9204. args: [this.object, value],
  9205. type: INTERACTION_ASSIGNED
  9206. };
  9207. }
  9208. applyDeoptimizations() {
  9209. this.deoptimized = true;
  9210. const { propertyReadSideEffects } = this.context.options
  9211. .treeshake;
  9212. if (
  9213. // Namespaces are not bound and should not be deoptimized
  9214. this.bound &&
  9215. propertyReadSideEffects &&
  9216. !(this.variable || this.isUndefined)) {
  9217. const propertyKey = this.getPropertyKey();
  9218. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  9219. this.context.requestTreeshakingPass();
  9220. }
  9221. }
  9222. applyAssignmentDeoptimization() {
  9223. this.assignmentDeoptimized = true;
  9224. const { propertyReadSideEffects } = this.context.options
  9225. .treeshake;
  9226. if (
  9227. // Namespaces are not bound and should not be deoptimized
  9228. this.bound &&
  9229. propertyReadSideEffects &&
  9230. !(this.variable || this.isUndefined)) {
  9231. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  9232. this.context.requestTreeshakingPass();
  9233. }
  9234. }
  9235. disallowNamespaceReassignment() {
  9236. if (this.object instanceof Identifier) {
  9237. const variable = this.scope.findVariable(this.object.name);
  9238. if (variable.isNamespace) {
  9239. if (this.variable) {
  9240. this.context.includeVariableInModule(this.variable);
  9241. }
  9242. this.context.warn(errorIllegalImportReassignment(this.object.name, this.context.module.id), this.start);
  9243. }
  9244. }
  9245. }
  9246. getPropertyKey() {
  9247. if (this.propertyKey === null) {
  9248. this.propertyKey = UnknownKey;
  9249. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9250. return (this.propertyKey =
  9251. value === SymbolToStringTag
  9252. ? value
  9253. : typeof value === 'symbol'
  9254. ? UnknownKey
  9255. : String(value));
  9256. }
  9257. return this.propertyKey;
  9258. }
  9259. hasAccessEffect(context) {
  9260. const { propertyReadSideEffects } = this.context.options
  9261. .treeshake;
  9262. return (!(this.variable || this.isUndefined) &&
  9263. propertyReadSideEffects &&
  9264. (propertyReadSideEffects === 'always' ||
  9265. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  9266. }
  9267. includeProperties(context, includeChildrenRecursively) {
  9268. if (!this.included) {
  9269. this.included = true;
  9270. if (this.variable) {
  9271. this.context.includeVariableInModule(this.variable);
  9272. }
  9273. }
  9274. this.object.include(context, includeChildrenRecursively);
  9275. this.property.include(context, includeChildrenRecursively);
  9276. }
  9277. }
  9278. function resolveNamespaceVariables(baseVariable, path, astContext) {
  9279. if (path.length === 0)
  9280. return baseVariable;
  9281. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  9282. return null;
  9283. const exportName = path[0].key;
  9284. const variable = baseVariable.context.traceExport(exportName);
  9285. if (!variable) {
  9286. if (path.length === 1) {
  9287. const fileName = baseVariable.context.fileName;
  9288. astContext.warn(errorMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  9289. return 'undefined';
  9290. }
  9291. return null;
  9292. }
  9293. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  9294. }
  9295. class CallExpressionBase extends NodeBase {
  9296. constructor() {
  9297. super(...arguments);
  9298. this.returnExpression = null;
  9299. this.deoptimizableDependentExpressions = [];
  9300. this.expressionsToBeDeoptimized = new Set();
  9301. }
  9302. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9303. const { args } = interaction;
  9304. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  9305. if (isPure)
  9306. return;
  9307. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  9308. if (deoptimizedExpressions.length === 0)
  9309. return;
  9310. if (returnExpression === UNKNOWN_EXPRESSION) {
  9311. for (const expression of deoptimizedExpressions) {
  9312. expression.deoptimizePath(UNKNOWN_PATH);
  9313. }
  9314. }
  9315. else {
  9316. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  9317. for (const expression of deoptimizedExpressions) {
  9318. this.expressionsToBeDeoptimized.add(expression);
  9319. }
  9320. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9321. }, null);
  9322. }
  9323. }
  9324. deoptimizeCache() {
  9325. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  9326. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  9327. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  9328. this.expressionsToBeDeoptimized = EMPTY_SET;
  9329. this.deoptimizableDependentExpressions = EMPTY_ARRAY;
  9330. for (const expression of deoptimizableDependentExpressions) {
  9331. expression.deoptimizeCache();
  9332. }
  9333. for (const expression of expressionsToBeDeoptimized) {
  9334. expression.deoptimizePath(UNKNOWN_PATH);
  9335. }
  9336. }
  9337. }
  9338. deoptimizePath(path) {
  9339. if (path.length === 0 ||
  9340. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  9341. return;
  9342. }
  9343. const [returnExpression] = this.getReturnExpression();
  9344. if (returnExpression !== UNKNOWN_EXPRESSION) {
  9345. returnExpression.deoptimizePath(path);
  9346. }
  9347. }
  9348. getLiteralValueAtPath(path, recursionTracker, origin) {
  9349. const [returnExpression] = this.getReturnExpression(recursionTracker);
  9350. if (returnExpression === UNKNOWN_EXPRESSION) {
  9351. return UnknownValue;
  9352. }
  9353. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  9354. this.deoptimizableDependentExpressions.push(origin);
  9355. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  9356. }, UnknownValue);
  9357. }
  9358. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9359. const returnExpression = this.getReturnExpression(recursionTracker);
  9360. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  9361. return returnExpression;
  9362. }
  9363. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  9364. this.deoptimizableDependentExpressions.push(origin);
  9365. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9366. return [expression, isPure || returnExpression[1]];
  9367. }, UNKNOWN_RETURN_EXPRESSION);
  9368. }
  9369. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9370. const { type } = interaction;
  9371. if (type === INTERACTION_CALLED) {
  9372. const { args, withNew } = interaction;
  9373. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  9374. return false;
  9375. }
  9376. }
  9377. else if ((type === INTERACTION_ASSIGNED
  9378. ? context.assigned
  9379. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  9380. return false;
  9381. }
  9382. const [returnExpression, isPure] = this.getReturnExpression();
  9383. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  9384. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  9385. }
  9386. }
  9387. class CallExpression extends CallExpressionBase {
  9388. bind() {
  9389. super.bind();
  9390. if (this.callee instanceof Identifier) {
  9391. const variable = this.scope.findVariable(this.callee.name);
  9392. if (variable.isNamespace) {
  9393. this.context.warn(errorCannotCallNamespace(this.callee.name), this.start);
  9394. }
  9395. if (this.callee.name === 'eval') {
  9396. this.context.warn(errorEval(this.context.module.id), this.start);
  9397. }
  9398. }
  9399. this.interaction = {
  9400. args: [
  9401. this.callee instanceof MemberExpression && !this.callee.variable
  9402. ? this.callee.object
  9403. : null,
  9404. ...this.arguments
  9405. ],
  9406. type: INTERACTION_CALLED,
  9407. withNew: false
  9408. };
  9409. }
  9410. hasEffects(context) {
  9411. try {
  9412. for (const argument of this.arguments) {
  9413. if (argument.hasEffects(context))
  9414. return true;
  9415. }
  9416. if (this.context.options.treeshake.annotations &&
  9417. this.annotations)
  9418. return false;
  9419. return (this.callee.hasEffects(context) ||
  9420. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  9421. }
  9422. finally {
  9423. if (!this.deoptimized)
  9424. this.applyDeoptimizations();
  9425. }
  9426. }
  9427. include(context, includeChildrenRecursively) {
  9428. if (!this.deoptimized)
  9429. this.applyDeoptimizations();
  9430. if (includeChildrenRecursively) {
  9431. super.include(context, includeChildrenRecursively);
  9432. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  9433. this.callee instanceof Identifier &&
  9434. this.callee.variable) {
  9435. this.callee.variable.markCalledFromTryStatement();
  9436. }
  9437. }
  9438. else {
  9439. this.included = true;
  9440. this.callee.include(context, false);
  9441. }
  9442. this.callee.includeCallArguments(context, this.arguments);
  9443. }
  9444. isSkippedAsOptional(origin) {
  9445. return (this.callee.isSkippedAsOptional?.(origin) ||
  9446. (this.optional &&
  9447. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null));
  9448. }
  9449. render(code, options, { renderedSurroundingElement } = BLANK) {
  9450. this.callee.render(code, options, {
  9451. isCalleeOfRenderedParent: true,
  9452. renderedSurroundingElement
  9453. });
  9454. renderCallArguments(code, options, this);
  9455. }
  9456. applyDeoptimizations() {
  9457. this.deoptimized = true;
  9458. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  9459. this.context.requestTreeshakingPass();
  9460. }
  9461. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  9462. if (this.returnExpression === null) {
  9463. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  9464. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  9465. }
  9466. return this.returnExpression;
  9467. }
  9468. }
  9469. class CatchScope extends ParameterScope {
  9470. addDeclaration(identifier, context, init, isHoisted) {
  9471. const existingParameter = this.variables.get(identifier.name);
  9472. if (existingParameter) {
  9473. // While we still create a hoisted declaration, the initializer goes to
  9474. // the parameter. Note that technically, the declaration now belongs to
  9475. // two variables, which is not correct but should not cause issues.
  9476. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  9477. existingParameter.addDeclaration(identifier, init);
  9478. return existingParameter;
  9479. }
  9480. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  9481. }
  9482. }
  9483. class CatchClause extends NodeBase {
  9484. createScope(parentScope) {
  9485. this.scope = new CatchScope(parentScope, this.context);
  9486. }
  9487. parseNode(esTreeNode) {
  9488. // Parameters need to be declared first as the logic is that initializers
  9489. // of hoisted body variables are associated with parameters of the same
  9490. // name instead of the variable
  9491. const { param } = esTreeNode;
  9492. if (param) {
  9493. this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
  9494. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  9495. }
  9496. super.parseNode(esTreeNode);
  9497. }
  9498. }
  9499. class ChainExpression extends NodeBase {
  9500. // deoptimizations are not relevant as we are not caching values
  9501. deoptimizeCache() { }
  9502. getLiteralValueAtPath(path, recursionTracker, origin) {
  9503. if (this.expression.isSkippedAsOptional(origin))
  9504. return undefined;
  9505. return this.expression.getLiteralValueAtPath(path, recursionTracker, origin);
  9506. }
  9507. hasEffects(context) {
  9508. if (this.expression.isSkippedAsOptional(this))
  9509. return false;
  9510. return this.expression.hasEffects(context);
  9511. }
  9512. }
  9513. class ClassBodyScope extends ChildScope {
  9514. constructor(parent, classNode, context) {
  9515. super(parent);
  9516. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  9517. this.instanceScope = new ChildScope(this);
  9518. this.instanceScope.variables.set('this', new ThisVariable(context));
  9519. }
  9520. findLexicalBoundary() {
  9521. return this;
  9522. }
  9523. }
  9524. class ClassBody extends NodeBase {
  9525. createScope(parentScope) {
  9526. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  9527. }
  9528. include(context, includeChildrenRecursively) {
  9529. this.included = true;
  9530. this.context.includeVariableInModule(this.scope.thisVariable);
  9531. for (const definition of this.body) {
  9532. definition.include(context, includeChildrenRecursively);
  9533. }
  9534. }
  9535. parseNode(esTreeNode) {
  9536. const body = (this.body = []);
  9537. for (const definition of esTreeNode.body) {
  9538. body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
  9539. }
  9540. super.parseNode(esTreeNode);
  9541. }
  9542. applyDeoptimizations() { }
  9543. }
  9544. class MethodBase extends NodeBase {
  9545. constructor() {
  9546. super(...arguments);
  9547. this.accessedValue = null;
  9548. }
  9549. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9550. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  9551. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  9552. args: interaction.args,
  9553. type: INTERACTION_CALLED,
  9554. withNew: false
  9555. }, EMPTY_PATH, recursionTracker);
  9556. }
  9557. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  9558. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  9559. args: interaction.args,
  9560. type: INTERACTION_CALLED,
  9561. withNew: false
  9562. }, EMPTY_PATH, recursionTracker);
  9563. }
  9564. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9565. }
  9566. // As getter properties directly receive their values from fixed function
  9567. // expressions, there is no known situation where a getter is deoptimized.
  9568. deoptimizeCache() { }
  9569. deoptimizePath(path) {
  9570. this.getAccessedValue()[0].deoptimizePath(path);
  9571. }
  9572. getLiteralValueAtPath(path, recursionTracker, origin) {
  9573. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  9574. }
  9575. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9576. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9577. }
  9578. hasEffects(context) {
  9579. return this.key.hasEffects(context);
  9580. }
  9581. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9582. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  9583. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  9584. args: interaction.args,
  9585. type: INTERACTION_CALLED,
  9586. withNew: false
  9587. }, context);
  9588. }
  9589. // setters are only called for empty paths
  9590. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  9591. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  9592. args: interaction.args,
  9593. type: INTERACTION_CALLED,
  9594. withNew: false
  9595. }, context);
  9596. }
  9597. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  9598. }
  9599. applyDeoptimizations() { }
  9600. getAccessedValue() {
  9601. if (this.accessedValue === null) {
  9602. if (this.kind === 'get') {
  9603. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  9604. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  9605. }
  9606. else {
  9607. return (this.accessedValue = [this.value, false]);
  9608. }
  9609. }
  9610. return this.accessedValue;
  9611. }
  9612. }
  9613. class MethodDefinition extends MethodBase {
  9614. applyDeoptimizations() { }
  9615. }
  9616. class ObjectMember extends ExpressionEntity {
  9617. constructor(object, key) {
  9618. super();
  9619. this.object = object;
  9620. this.key = key;
  9621. }
  9622. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9623. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  9624. }
  9625. deoptimizePath(path) {
  9626. this.object.deoptimizePath([this.key, ...path]);
  9627. }
  9628. getLiteralValueAtPath(path, recursionTracker, origin) {
  9629. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  9630. }
  9631. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9632. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  9633. }
  9634. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9635. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  9636. }
  9637. }
  9638. class ClassNode extends NodeBase {
  9639. constructor() {
  9640. super(...arguments);
  9641. this.objectEntity = null;
  9642. }
  9643. createScope(parentScope) {
  9644. this.scope = new ChildScope(parentScope);
  9645. }
  9646. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9647. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9648. }
  9649. deoptimizeCache() {
  9650. this.getObjectEntity().deoptimizeAllProperties();
  9651. }
  9652. deoptimizePath(path) {
  9653. this.getObjectEntity().deoptimizePath(path);
  9654. }
  9655. getLiteralValueAtPath(path, recursionTracker, origin) {
  9656. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  9657. }
  9658. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9659. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9660. }
  9661. hasEffects(context) {
  9662. if (!this.deoptimized)
  9663. this.applyDeoptimizations();
  9664. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  9665. this.id?.markDeclarationReached();
  9666. return initEffect || super.hasEffects(context);
  9667. }
  9668. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9669. return interaction.type === INTERACTION_CALLED && path.length === 0
  9670. ? !interaction.withNew ||
  9671. (this.classConstructor === null
  9672. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  9673. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  9674. false
  9675. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  9676. }
  9677. include(context, includeChildrenRecursively) {
  9678. if (!this.deoptimized)
  9679. this.applyDeoptimizations();
  9680. this.included = true;
  9681. this.superClass?.include(context, includeChildrenRecursively);
  9682. this.body.include(context, includeChildrenRecursively);
  9683. if (this.id) {
  9684. this.id.markDeclarationReached();
  9685. this.id.include();
  9686. }
  9687. }
  9688. initialise() {
  9689. this.id?.declare('class', this);
  9690. for (const method of this.body.body) {
  9691. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  9692. this.classConstructor = method;
  9693. return;
  9694. }
  9695. }
  9696. this.classConstructor = null;
  9697. }
  9698. applyDeoptimizations() {
  9699. this.deoptimized = true;
  9700. for (const definition of this.body.body) {
  9701. if (!(definition.static ||
  9702. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  9703. // Calls to methods are not tracked, ensure that the return value is deoptimized
  9704. definition.deoptimizePath(UNKNOWN_PATH);
  9705. }
  9706. }
  9707. this.context.requestTreeshakingPass();
  9708. }
  9709. getObjectEntity() {
  9710. if (this.objectEntity !== null) {
  9711. return this.objectEntity;
  9712. }
  9713. const staticProperties = [];
  9714. const dynamicMethods = [];
  9715. for (const definition of this.body.body) {
  9716. const properties = definition.static ? staticProperties : dynamicMethods;
  9717. const definitionKind = definition.kind;
  9718. // Note that class fields do not end up on the prototype
  9719. if (properties === dynamicMethods && !definitionKind)
  9720. continue;
  9721. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  9722. let key;
  9723. if (definition.computed) {
  9724. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9725. if (typeof keyValue === 'symbol') {
  9726. properties.push({ key: UnknownKey, kind, property: definition });
  9727. continue;
  9728. }
  9729. else {
  9730. key = String(keyValue);
  9731. }
  9732. }
  9733. else {
  9734. key =
  9735. definition.key instanceof Identifier
  9736. ? definition.key.name
  9737. : String(definition.key.value);
  9738. }
  9739. properties.push({ key, kind, property: definition });
  9740. }
  9741. staticProperties.unshift({
  9742. key: 'prototype',
  9743. kind: 'init',
  9744. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  9745. });
  9746. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  9747. }
  9748. }
  9749. class ClassDeclaration extends ClassNode {
  9750. initialise() {
  9751. super.initialise();
  9752. if (this.id !== null) {
  9753. this.id.variable.isId = true;
  9754. }
  9755. }
  9756. parseNode(esTreeNode) {
  9757. if (esTreeNode.id !== null) {
  9758. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  9759. }
  9760. super.parseNode(esTreeNode);
  9761. }
  9762. render(code, options) {
  9763. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  9764. if (this.id) {
  9765. const { variable, name } = this.id;
  9766. if (format === 'system' && exportNamesByVariable.has(variable)) {
  9767. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  9768. }
  9769. const renderedVariable = variable.getName(getPropertyAccess);
  9770. if (renderedVariable !== name) {
  9771. this.superClass?.render(code, options);
  9772. this.body.render(code, {
  9773. ...options,
  9774. useOriginalName: (_variable) => _variable === variable
  9775. });
  9776. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  9777. code.prependLeft(this.end, ';');
  9778. return;
  9779. }
  9780. }
  9781. super.render(code, options);
  9782. }
  9783. applyDeoptimizations() {
  9784. super.applyDeoptimizations();
  9785. const { id, scope } = this;
  9786. if (id) {
  9787. const { name, variable } = id;
  9788. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  9789. if (accessedVariable !== variable) {
  9790. accessedVariable.forbidName(name);
  9791. }
  9792. }
  9793. }
  9794. }
  9795. }
  9796. class ClassExpression extends ClassNode {
  9797. render(code, options, { renderedSurroundingElement } = BLANK) {
  9798. super.render(code, options);
  9799. if (renderedSurroundingElement === ExpressionStatement$1) {
  9800. code.appendRight(this.start, '(');
  9801. code.prependLeft(this.end, ')');
  9802. }
  9803. }
  9804. }
  9805. class MultiExpression extends ExpressionEntity {
  9806. constructor(expressions) {
  9807. super();
  9808. this.expressions = expressions;
  9809. this.included = false;
  9810. }
  9811. deoptimizePath(path) {
  9812. for (const expression of this.expressions) {
  9813. expression.deoptimizePath(path);
  9814. }
  9815. }
  9816. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9817. return [
  9818. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  9819. false
  9820. ];
  9821. }
  9822. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9823. for (const expression of this.expressions) {
  9824. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  9825. return true;
  9826. }
  9827. return false;
  9828. }
  9829. }
  9830. class ConditionalExpression extends NodeBase {
  9831. constructor() {
  9832. super(...arguments);
  9833. this.expressionsToBeDeoptimized = [];
  9834. this.isBranchResolutionAnalysed = false;
  9835. this.usedBranch = null;
  9836. }
  9837. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9838. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9839. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9840. }
  9841. deoptimizeCache() {
  9842. if (this.usedBranch !== null) {
  9843. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  9844. this.usedBranch = null;
  9845. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  9846. const { expressionsToBeDeoptimized } = this;
  9847. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  9848. for (const expression of expressionsToBeDeoptimized) {
  9849. expression.deoptimizeCache();
  9850. }
  9851. }
  9852. }
  9853. deoptimizePath(path) {
  9854. const usedBranch = this.getUsedBranch();
  9855. if (usedBranch) {
  9856. usedBranch.deoptimizePath(path);
  9857. }
  9858. else {
  9859. this.consequent.deoptimizePath(path);
  9860. this.alternate.deoptimizePath(path);
  9861. }
  9862. }
  9863. getLiteralValueAtPath(path, recursionTracker, origin) {
  9864. const usedBranch = this.getUsedBranch();
  9865. if (!usedBranch)
  9866. return UnknownValue;
  9867. this.expressionsToBeDeoptimized.push(origin);
  9868. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  9869. }
  9870. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9871. const usedBranch = this.getUsedBranch();
  9872. if (!usedBranch)
  9873. return [
  9874. new MultiExpression([
  9875. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  9876. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  9877. ]),
  9878. false
  9879. ];
  9880. this.expressionsToBeDeoptimized.push(origin);
  9881. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9882. }
  9883. hasEffects(context) {
  9884. if (this.test.hasEffects(context))
  9885. return true;
  9886. const usedBranch = this.getUsedBranch();
  9887. if (!usedBranch) {
  9888. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  9889. }
  9890. return usedBranch.hasEffects(context);
  9891. }
  9892. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9893. const usedBranch = this.getUsedBranch();
  9894. if (!usedBranch) {
  9895. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  9896. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  9897. }
  9898. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  9899. }
  9900. include(context, includeChildrenRecursively) {
  9901. this.included = true;
  9902. const usedBranch = this.getUsedBranch();
  9903. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  9904. this.test.include(context, includeChildrenRecursively);
  9905. this.consequent.include(context, includeChildrenRecursively);
  9906. this.alternate.include(context, includeChildrenRecursively);
  9907. }
  9908. else {
  9909. usedBranch.include(context, includeChildrenRecursively);
  9910. }
  9911. }
  9912. includeCallArguments(context, parameters) {
  9913. const usedBranch = this.getUsedBranch();
  9914. if (usedBranch) {
  9915. usedBranch.includeCallArguments(context, parameters);
  9916. }
  9917. else {
  9918. this.consequent.includeCallArguments(context, parameters);
  9919. this.alternate.includeCallArguments(context, parameters);
  9920. }
  9921. }
  9922. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  9923. const usedBranch = this.getUsedBranch();
  9924. if (this.test.included) {
  9925. this.test.render(code, options, { renderedSurroundingElement });
  9926. this.consequent.render(code, options);
  9927. this.alternate.render(code, options);
  9928. }
  9929. else {
  9930. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  9931. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  9932. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  9933. : colonPos) + 1);
  9934. if (preventASI) {
  9935. removeLineBreaks(code, inclusionStart, usedBranch.start);
  9936. }
  9937. code.remove(this.start, inclusionStart);
  9938. if (this.consequent.included) {
  9939. code.remove(colonPos, this.end);
  9940. }
  9941. removeAnnotations(this, code);
  9942. usedBranch.render(code, options, {
  9943. isCalleeOfRenderedParent,
  9944. preventASI: true,
  9945. renderedParentType: renderedParentType || this.parent.type,
  9946. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  9947. });
  9948. }
  9949. }
  9950. getUsedBranch() {
  9951. if (this.isBranchResolutionAnalysed) {
  9952. return this.usedBranch;
  9953. }
  9954. this.isBranchResolutionAnalysed = true;
  9955. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9956. return typeof testValue === 'symbol'
  9957. ? null
  9958. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  9959. }
  9960. }
  9961. class ContinueStatement extends NodeBase {
  9962. hasEffects(context) {
  9963. if (this.label) {
  9964. if (!context.ignore.labels.has(this.label.name))
  9965. return true;
  9966. context.includedLabels.add(this.label.name);
  9967. }
  9968. else {
  9969. if (!context.ignore.continues)
  9970. return true;
  9971. context.hasContinue = true;
  9972. }
  9973. context.brokenFlow = true;
  9974. return false;
  9975. }
  9976. include(context) {
  9977. this.included = true;
  9978. if (this.label) {
  9979. this.label.include();
  9980. context.includedLabels.add(this.label.name);
  9981. }
  9982. else {
  9983. context.hasContinue = true;
  9984. }
  9985. context.brokenFlow = true;
  9986. }
  9987. }
  9988. function hasLoopBodyEffects(context, body) {
  9989. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  9990. const { breaks, continues } = ignore;
  9991. ignore.breaks = true;
  9992. ignore.continues = true;
  9993. context.hasBreak = false;
  9994. context.hasContinue = false;
  9995. if (body.hasEffects(context))
  9996. return true;
  9997. ignore.breaks = breaks;
  9998. ignore.continues = continues;
  9999. context.hasBreak = hasBreak;
  10000. context.hasContinue = hasContinue;
  10001. context.brokenFlow = brokenFlow;
  10002. return false;
  10003. }
  10004. function includeLoopBody(context, body, includeChildrenRecursively) {
  10005. const { brokenFlow, hasBreak, hasContinue } = context;
  10006. context.hasBreak = false;
  10007. context.hasContinue = false;
  10008. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  10009. context.hasBreak = hasBreak;
  10010. context.hasContinue = hasContinue;
  10011. context.brokenFlow = brokenFlow;
  10012. }
  10013. class DoWhileStatement extends NodeBase {
  10014. hasEffects(context) {
  10015. if (this.test.hasEffects(context))
  10016. return true;
  10017. return hasLoopBodyEffects(context, this.body);
  10018. }
  10019. include(context, includeChildrenRecursively) {
  10020. this.included = true;
  10021. this.test.include(context, includeChildrenRecursively);
  10022. includeLoopBody(context, this.body, includeChildrenRecursively);
  10023. }
  10024. }
  10025. class EmptyStatement extends NodeBase {
  10026. hasEffects() {
  10027. return false;
  10028. }
  10029. }
  10030. class ExportAllDeclaration extends NodeBase {
  10031. hasEffects() {
  10032. return false;
  10033. }
  10034. initialise() {
  10035. this.context.addExport(this);
  10036. }
  10037. render(code, _options, nodeRenderOptions) {
  10038. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  10039. }
  10040. applyDeoptimizations() { }
  10041. }
  10042. ExportAllDeclaration.prototype.needsBoundaries = true;
  10043. class FunctionDeclaration extends FunctionNode {
  10044. initialise() {
  10045. super.initialise();
  10046. if (this.id !== null) {
  10047. this.id.variable.isId = true;
  10048. }
  10049. }
  10050. parseNode(esTreeNode) {
  10051. if (esTreeNode.id !== null) {
  10052. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  10053. }
  10054. super.parseNode(esTreeNode);
  10055. }
  10056. }
  10057. // The header ends at the first non-white-space after "default"
  10058. function getDeclarationStart(code, start) {
  10059. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  10060. }
  10061. function getFunctionIdInsertPosition(code, start) {
  10062. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  10063. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  10064. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  10065. if (generatorStarPos === -1) {
  10066. return declarationEnd;
  10067. }
  10068. return declarationEnd + generatorStarPos + 1;
  10069. }
  10070. class ExportDefaultDeclaration extends NodeBase {
  10071. include(context, includeChildrenRecursively) {
  10072. super.include(context, includeChildrenRecursively);
  10073. if (includeChildrenRecursively) {
  10074. this.context.includeVariableInModule(this.variable);
  10075. }
  10076. }
  10077. initialise() {
  10078. const declaration = this.declaration;
  10079. this.declarationName =
  10080. (declaration.id && declaration.id.name) || this.declaration.name;
  10081. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  10082. this.context.addExport(this);
  10083. }
  10084. render(code, options, nodeRenderOptions) {
  10085. const { start, end } = nodeRenderOptions;
  10086. const declarationStart = getDeclarationStart(code.original, this.start);
  10087. if (this.declaration instanceof FunctionDeclaration) {
  10088. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  10089. ? getFunctionIdInsertPosition(code.original, declarationStart)
  10090. : null, options);
  10091. }
  10092. else if (this.declaration instanceof ClassDeclaration) {
  10093. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  10094. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  10095. : null, options);
  10096. }
  10097. else if (this.variable.getOriginalVariable() !== this.variable) {
  10098. // Remove altogether to prevent re-declaring the same variable
  10099. treeshakeNode(this, code, start, end);
  10100. return;
  10101. }
  10102. else if (this.variable.included) {
  10103. this.renderVariableDeclaration(code, declarationStart, options);
  10104. }
  10105. else {
  10106. code.remove(this.start, declarationStart);
  10107. this.declaration.render(code, options, {
  10108. renderedSurroundingElement: ExpressionStatement$1
  10109. });
  10110. if (code.original[this.end - 1] !== ';') {
  10111. code.appendLeft(this.end, ';');
  10112. }
  10113. return;
  10114. }
  10115. this.declaration.render(code, options);
  10116. }
  10117. applyDeoptimizations() { }
  10118. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  10119. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  10120. const name = this.variable.getName(getPropertyAccess);
  10121. // Remove `export default`
  10122. code.remove(this.start, declarationStart);
  10123. if (idInsertPosition !== null) {
  10124. code.appendLeft(idInsertPosition, ` ${name}`);
  10125. }
  10126. if (format === 'system' &&
  10127. this.declaration instanceof ClassDeclaration &&
  10128. exportNamesByVariable.has(this.variable)) {
  10129. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  10130. }
  10131. }
  10132. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  10133. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  10134. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  10135. if (systemExportNames) {
  10136. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
  10137. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  10138. }
  10139. else {
  10140. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  10141. if (!hasTrailingSemicolon) {
  10142. code.appendLeft(this.end, ';');
  10143. }
  10144. }
  10145. }
  10146. }
  10147. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  10148. class ExportNamedDeclaration extends NodeBase {
  10149. bind() {
  10150. // Do not bind specifiers
  10151. this.declaration?.bind();
  10152. }
  10153. hasEffects(context) {
  10154. return !!this.declaration?.hasEffects(context);
  10155. }
  10156. initialise() {
  10157. this.context.addExport(this);
  10158. }
  10159. render(code, options, nodeRenderOptions) {
  10160. const { start, end } = nodeRenderOptions;
  10161. if (this.declaration === null) {
  10162. code.remove(start, end);
  10163. }
  10164. else {
  10165. code.remove(this.start, this.declaration.start);
  10166. this.declaration.render(code, options, { end, start });
  10167. }
  10168. }
  10169. applyDeoptimizations() { }
  10170. }
  10171. ExportNamedDeclaration.prototype.needsBoundaries = true;
  10172. class ExportSpecifier extends NodeBase {
  10173. applyDeoptimizations() { }
  10174. }
  10175. class ForInStatement extends NodeBase {
  10176. createScope(parentScope) {
  10177. this.scope = new BlockScope(parentScope);
  10178. }
  10179. hasEffects(context) {
  10180. const { body, deoptimized, left, right } = this;
  10181. if (!deoptimized)
  10182. this.applyDeoptimizations();
  10183. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  10184. return true;
  10185. return hasLoopBodyEffects(context, body);
  10186. }
  10187. include(context, includeChildrenRecursively) {
  10188. const { body, deoptimized, left, right } = this;
  10189. if (!deoptimized)
  10190. this.applyDeoptimizations();
  10191. this.included = true;
  10192. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  10193. right.include(context, includeChildrenRecursively);
  10194. includeLoopBody(context, body, includeChildrenRecursively);
  10195. }
  10196. initialise() {
  10197. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  10198. }
  10199. render(code, options) {
  10200. this.left.render(code, options, NO_SEMICOLON);
  10201. this.right.render(code, options, NO_SEMICOLON);
  10202. // handle no space between "in" and the right side
  10203. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  10204. code.prependLeft(this.right.start, ' ');
  10205. }
  10206. this.body.render(code, options);
  10207. }
  10208. applyDeoptimizations() {
  10209. this.deoptimized = true;
  10210. this.left.deoptimizePath(EMPTY_PATH);
  10211. this.context.requestTreeshakingPass();
  10212. }
  10213. }
  10214. class ForOfStatement extends NodeBase {
  10215. createScope(parentScope) {
  10216. this.scope = new BlockScope(parentScope);
  10217. }
  10218. hasEffects() {
  10219. if (!this.deoptimized)
  10220. this.applyDeoptimizations();
  10221. // Placeholder until proper Symbol.Iterator support
  10222. return true;
  10223. }
  10224. include(context, includeChildrenRecursively) {
  10225. const { body, deoptimized, left, right } = this;
  10226. if (!deoptimized)
  10227. this.applyDeoptimizations();
  10228. this.included = true;
  10229. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  10230. right.include(context, includeChildrenRecursively);
  10231. includeLoopBody(context, body, includeChildrenRecursively);
  10232. }
  10233. initialise() {
  10234. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  10235. }
  10236. render(code, options) {
  10237. this.left.render(code, options, NO_SEMICOLON);
  10238. this.right.render(code, options, NO_SEMICOLON);
  10239. // handle no space between "of" and the right side
  10240. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  10241. code.prependLeft(this.right.start, ' ');
  10242. }
  10243. this.body.render(code, options);
  10244. }
  10245. applyDeoptimizations() {
  10246. this.deoptimized = true;
  10247. this.left.deoptimizePath(EMPTY_PATH);
  10248. this.right.deoptimizePath(UNKNOWN_PATH);
  10249. this.context.requestTreeshakingPass();
  10250. }
  10251. }
  10252. class ForStatement extends NodeBase {
  10253. createScope(parentScope) {
  10254. this.scope = new BlockScope(parentScope);
  10255. }
  10256. hasEffects(context) {
  10257. if (this.init?.hasEffects(context) ||
  10258. this.test?.hasEffects(context) ||
  10259. this.update?.hasEffects(context)) {
  10260. return true;
  10261. }
  10262. return hasLoopBodyEffects(context, this.body);
  10263. }
  10264. include(context, includeChildrenRecursively) {
  10265. this.included = true;
  10266. this.init?.include(context, includeChildrenRecursively, { asSingleStatement: true });
  10267. this.test?.include(context, includeChildrenRecursively);
  10268. this.update?.include(context, includeChildrenRecursively);
  10269. includeLoopBody(context, this.body, includeChildrenRecursively);
  10270. }
  10271. render(code, options) {
  10272. this.init?.render(code, options, NO_SEMICOLON);
  10273. this.test?.render(code, options, NO_SEMICOLON);
  10274. this.update?.render(code, options, NO_SEMICOLON);
  10275. this.body.render(code, options);
  10276. }
  10277. }
  10278. class FunctionExpression extends FunctionNode {
  10279. render(code, options, { renderedSurroundingElement } = BLANK) {
  10280. super.render(code, options);
  10281. if (renderedSurroundingElement === ExpressionStatement$1) {
  10282. code.appendRight(this.start, '(');
  10283. code.prependLeft(this.end, ')');
  10284. }
  10285. }
  10286. }
  10287. class TrackingScope extends BlockScope {
  10288. constructor() {
  10289. super(...arguments);
  10290. this.hoistedDeclarations = [];
  10291. }
  10292. addDeclaration(identifier, context, init, isHoisted) {
  10293. this.hoistedDeclarations.push(identifier);
  10294. return super.addDeclaration(identifier, context, init, isHoisted);
  10295. }
  10296. }
  10297. const unset = Symbol('unset');
  10298. class IfStatement extends NodeBase {
  10299. constructor() {
  10300. super(...arguments);
  10301. this.testValue = unset;
  10302. }
  10303. deoptimizeCache() {
  10304. this.testValue = UnknownValue;
  10305. }
  10306. hasEffects(context) {
  10307. if (this.test.hasEffects(context)) {
  10308. return true;
  10309. }
  10310. const testValue = this.getTestValue();
  10311. if (typeof testValue === 'symbol') {
  10312. const { brokenFlow } = context;
  10313. if (this.consequent.hasEffects(context))
  10314. return true;
  10315. // eslint-disable-next-line unicorn/consistent-destructuring
  10316. const consequentBrokenFlow = context.brokenFlow;
  10317. context.brokenFlow = brokenFlow;
  10318. if (this.alternate === null)
  10319. return false;
  10320. if (this.alternate.hasEffects(context))
  10321. return true;
  10322. // eslint-disable-next-line unicorn/consistent-destructuring
  10323. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  10324. return false;
  10325. }
  10326. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  10327. }
  10328. include(context, includeChildrenRecursively) {
  10329. this.included = true;
  10330. if (includeChildrenRecursively) {
  10331. this.includeRecursively(includeChildrenRecursively, context);
  10332. }
  10333. else {
  10334. const testValue = this.getTestValue();
  10335. if (typeof testValue === 'symbol') {
  10336. this.includeUnknownTest(context);
  10337. }
  10338. else {
  10339. this.includeKnownTest(context, testValue);
  10340. }
  10341. }
  10342. }
  10343. parseNode(esTreeNode) {
  10344. this.consequentScope = new TrackingScope(this.scope);
  10345. this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
  10346. if (esTreeNode.alternate) {
  10347. this.alternateScope = new TrackingScope(this.scope);
  10348. this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
  10349. }
  10350. super.parseNode(esTreeNode);
  10351. }
  10352. render(code, options) {
  10353. const { snippets: { getPropertyAccess } } = options;
  10354. // Note that unknown test values are always included
  10355. const testValue = this.getTestValue();
  10356. const hoistedDeclarations = [];
  10357. const includesIfElse = this.test.included;
  10358. const noTreeshake = !this.context.options.treeshake;
  10359. if (includesIfElse) {
  10360. this.test.render(code, options);
  10361. }
  10362. else {
  10363. code.remove(this.start, this.consequent.start);
  10364. }
  10365. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  10366. this.consequent.render(code, options);
  10367. }
  10368. else {
  10369. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  10370. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  10371. }
  10372. if (this.alternate) {
  10373. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  10374. if (includesIfElse) {
  10375. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  10376. code.prependLeft(this.alternate.start, ' ');
  10377. }
  10378. }
  10379. else {
  10380. code.remove(this.consequent.end, this.alternate.start);
  10381. }
  10382. this.alternate.render(code, options);
  10383. }
  10384. else {
  10385. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  10386. code.overwrite(this.alternate.start, this.end, ';');
  10387. }
  10388. else {
  10389. code.remove(this.consequent.end, this.end);
  10390. }
  10391. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  10392. }
  10393. }
  10394. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  10395. }
  10396. applyDeoptimizations() { }
  10397. getTestValue() {
  10398. if (this.testValue === unset) {
  10399. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  10400. }
  10401. return this.testValue;
  10402. }
  10403. includeKnownTest(context, testValue) {
  10404. if (this.test.shouldBeIncluded(context)) {
  10405. this.test.include(context, false);
  10406. }
  10407. if (testValue && this.consequent.shouldBeIncluded(context)) {
  10408. this.consequent.include(context, false, { asSingleStatement: true });
  10409. }
  10410. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  10411. this.alternate.include(context, false, { asSingleStatement: true });
  10412. }
  10413. }
  10414. includeRecursively(includeChildrenRecursively, context) {
  10415. this.test.include(context, includeChildrenRecursively);
  10416. this.consequent.include(context, includeChildrenRecursively);
  10417. this.alternate?.include(context, includeChildrenRecursively);
  10418. }
  10419. includeUnknownTest(context) {
  10420. this.test.include(context, false);
  10421. const { brokenFlow } = context;
  10422. let consequentBrokenFlow = false;
  10423. if (this.consequent.shouldBeIncluded(context)) {
  10424. this.consequent.include(context, false, { asSingleStatement: true });
  10425. // eslint-disable-next-line unicorn/consistent-destructuring
  10426. consequentBrokenFlow = context.brokenFlow;
  10427. context.brokenFlow = brokenFlow;
  10428. }
  10429. if (this.alternate?.shouldBeIncluded(context)) {
  10430. this.alternate.include(context, false, { asSingleStatement: true });
  10431. // eslint-disable-next-line unicorn/consistent-destructuring
  10432. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  10433. }
  10434. }
  10435. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  10436. const hoistedVariables = [
  10437. ...new Set(hoistedDeclarations.map(identifier => {
  10438. const variable = identifier.variable;
  10439. return variable.included ? variable.getName(getPropertyAccess) : '';
  10440. }))
  10441. ]
  10442. .filter(Boolean)
  10443. .join(', ');
  10444. if (hoistedVariables) {
  10445. const parentType = this.parent.type;
  10446. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  10447. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  10448. if (needsBraces) {
  10449. code.appendLeft(this.end, ` }`);
  10450. }
  10451. }
  10452. }
  10453. shouldKeepAlternateBranch() {
  10454. let currentParent = this.parent;
  10455. do {
  10456. if (currentParent instanceof IfStatement && currentParent.alternate) {
  10457. return true;
  10458. }
  10459. if (currentParent instanceof BlockStatement) {
  10460. return false;
  10461. }
  10462. currentParent = currentParent.parent;
  10463. } while (currentParent);
  10464. return false;
  10465. }
  10466. }
  10467. class ImportAttribute extends NodeBase {
  10468. }
  10469. class ImportDeclaration extends NodeBase {
  10470. // Do not bind specifiers or assertions
  10471. bind() { }
  10472. hasEffects() {
  10473. return false;
  10474. }
  10475. initialise() {
  10476. this.context.addImport(this);
  10477. }
  10478. render(code, _options, nodeRenderOptions) {
  10479. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  10480. }
  10481. applyDeoptimizations() { }
  10482. }
  10483. ImportDeclaration.prototype.needsBoundaries = true;
  10484. class ImportDefaultSpecifier extends NodeBase {
  10485. applyDeoptimizations() { }
  10486. }
  10487. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  10488. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  10489. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  10490. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  10491. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  10492. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  10493. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  10494. const defaultInteropHelpersByInteropType = {
  10495. auto: INTEROP_DEFAULT_VARIABLE,
  10496. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  10497. default: null,
  10498. defaultOnly: null,
  10499. esModule: null
  10500. };
  10501. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  10502. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  10503. const namespaceInteropHelpersByInteropType = {
  10504. auto: INTEROP_NAMESPACE_VARIABLE,
  10505. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  10506. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  10507. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  10508. esModule: null
  10509. };
  10510. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  10511. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
  10512. const usedHelpers = new Set(additionalHelpers);
  10513. for (const variable of HELPER_NAMES) {
  10514. if (accessedGlobals.has(variable)) {
  10515. usedHelpers.add(variable);
  10516. }
  10517. }
  10518. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  10519. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  10520. : '').join('');
  10521. };
  10522. const HELPER_GENERATORS = {
  10523. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  10524. const { _, getDirectReturnFunction, n } = snippets;
  10525. const [left, right] = getDirectReturnFunction(['e'], {
  10526. functionReturn: true,
  10527. lineBreakIndent: null,
  10528. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  10529. });
  10530. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  10531. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  10532. },
  10533. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  10534. const { _, getDirectReturnFunction, n } = snippets;
  10535. const [left, right] = getDirectReturnFunction(['e'], {
  10536. functionReturn: true,
  10537. lineBreakIndent: null,
  10538. name: INTEROP_DEFAULT_VARIABLE
  10539. });
  10540. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  10541. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  10542. },
  10543. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  10544. const { _, getDirectReturnFunction, n } = snippets;
  10545. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  10546. const [left, right] = getDirectReturnFunction(['e'], {
  10547. functionReturn: true,
  10548. lineBreakIndent: null,
  10549. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  10550. });
  10551. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  10552. }
  10553. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  10554. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  10555. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  10556. `}${n}${n}`);
  10557. },
  10558. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
  10559. const { getDirectReturnFunction, getObject, n } = snippets;
  10560. const [left, right] = getDirectReturnFunction(['e'], {
  10561. functionReturn: true,
  10562. lineBreakIndent: null,
  10563. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  10564. });
  10565. return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
  10566. ['__proto__', 'null'],
  10567. ['default', 'e']
  10568. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  10569. },
  10570. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  10571. const { _, n } = snippets;
  10572. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  10573. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  10574. `}${n}${n}`);
  10575. },
  10576. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  10577. const { _, getDirectReturnFunction, n } = snippets;
  10578. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  10579. const [left, right] = getDirectReturnFunction(['e'], {
  10580. functionReturn: true,
  10581. lineBreakIndent: null,
  10582. name: INTEROP_NAMESPACE_VARIABLE
  10583. });
  10584. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  10585. }
  10586. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  10587. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  10588. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  10589. `}${n}${n}`);
  10590. },
  10591. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  10592. const { _, cnst, n } = snippets;
  10593. const useForEach = cnst === 'var' && liveBindings;
  10594. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  10595. `${t}${loopOverNamespaces(`{${n}` +
  10596. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  10597. (liveBindings
  10598. ? useForEach
  10599. ? copyOwnPropertyLiveBinding
  10600. : copyPropertyLiveBinding
  10601. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  10602. `${t}${t}${t}}${n}` +
  10603. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  10604. `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
  10605. `}${n}${n}`);
  10606. }
  10607. };
  10608. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  10609. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  10610. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  10611. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, namespaceToStringTag) => {
  10612. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  10613. const copyProperty = `{${n}` +
  10614. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  10615. `${index}${t}}`;
  10616. return (`${index}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
  10617. ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
  10618. : ''});${n}` +
  10619. `${index}if${_}(e)${_}{${n}` +
  10620. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  10621. `${index}}${n}` +
  10622. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  10623. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  10624. };
  10625. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  10626. ? `for${_}(${cnst} k in e)${_}${body}`
  10627. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10628. isAsync: false,
  10629. name: null
  10630. })}${body})${s}`;
  10631. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  10632. if (useForEach) {
  10633. const [left, right] = getDirectReturnFunction(['e'], {
  10634. functionReturn: false,
  10635. lineBreakIndent: { base: t, t },
  10636. name: null
  10637. });
  10638. return (`m.forEach(${left}` +
  10639. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10640. isAsync: false,
  10641. name: null
  10642. })}${body})${right});`);
  10643. }
  10644. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  10645. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  10646. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  10647. };
  10648. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  10649. const { _, n } = snippets;
  10650. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  10651. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  10652. `${index}}${n}`);
  10653. };
  10654. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10655. const [left, right] = getDirectReturnFunction([], {
  10656. functionReturn: true,
  10657. lineBreakIndent: null,
  10658. name: null
  10659. });
  10660. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10661. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10662. `${index}${t}enumerable:${_}true,${n}` +
  10663. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  10664. `${index}});${n}`);
  10665. };
  10666. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10667. const [left, right] = getDirectReturnFunction([], {
  10668. functionReturn: true,
  10669. lineBreakIndent: null,
  10670. name: null
  10671. });
  10672. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10673. `${index}if${_}(d)${_}{${n}` +
  10674. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10675. `${index}${t}${t}enumerable:${_}true,${n}` +
  10676. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  10677. `${index}${t}});${n}` +
  10678. `${index}}${n}`);
  10679. };
  10680. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  10681. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  10682. const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
  10683. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  10684. : fragment;
  10685. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  10686. function getToStringTagValue(getObject) {
  10687. return getObject([['value', "'Module'"]], {
  10688. lineBreakIndent: null
  10689. });
  10690. }
  10691. function isReassignedExportsMember(variable, exportNamesByVariable) {
  10692. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  10693. }
  10694. class VariableDeclarator extends NodeBase {
  10695. declareDeclarator(kind) {
  10696. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  10697. }
  10698. deoptimizePath(path) {
  10699. this.id.deoptimizePath(path);
  10700. }
  10701. hasEffects(context) {
  10702. if (!this.deoptimized)
  10703. this.applyDeoptimizations();
  10704. const initEffect = this.init?.hasEffects(context);
  10705. this.id.markDeclarationReached();
  10706. return initEffect || this.id.hasEffects(context);
  10707. }
  10708. include(context, includeChildrenRecursively) {
  10709. const { deoptimized, id, init } = this;
  10710. if (!deoptimized)
  10711. this.applyDeoptimizations();
  10712. this.included = true;
  10713. init?.include(context, includeChildrenRecursively);
  10714. id.markDeclarationReached();
  10715. if (includeChildrenRecursively || id.shouldBeIncluded(context)) {
  10716. id.include(context, includeChildrenRecursively);
  10717. }
  10718. }
  10719. render(code, options) {
  10720. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  10721. const { end, id, init, start } = this;
  10722. const renderId = id.included;
  10723. if (renderId) {
  10724. id.render(code, options);
  10725. }
  10726. else {
  10727. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  10728. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  10729. }
  10730. if (init) {
  10731. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  10732. const renderedVariable = id.variable.getName(getPropertyAccess);
  10733. if (renderedVariable !== id.name) {
  10734. code.appendLeft(init.start + 5, ` ${id.name}`);
  10735. }
  10736. }
  10737. init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  10738. }
  10739. else if (id instanceof Identifier &&
  10740. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  10741. code.appendLeft(end, `${_}=${_}void 0`);
  10742. }
  10743. }
  10744. applyDeoptimizations() {
  10745. this.deoptimized = true;
  10746. const { id, init } = this;
  10747. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  10748. const { name, variable } = id;
  10749. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  10750. if (accessedVariable !== variable) {
  10751. accessedVariable.forbidName(name);
  10752. }
  10753. }
  10754. }
  10755. }
  10756. }
  10757. // TODO once ImportExpression follows official ESTree specs with "null" as
  10758. // default, keys.ts should be updated
  10759. class ImportExpression extends NodeBase {
  10760. constructor() {
  10761. super(...arguments);
  10762. this.inlineNamespace = null;
  10763. this.assertions = null;
  10764. this.mechanism = null;
  10765. this.namespaceExportName = undefined;
  10766. this.resolution = null;
  10767. this.resolutionString = null;
  10768. }
  10769. // Do not bind assertions
  10770. bind() {
  10771. this.source.bind();
  10772. }
  10773. /**
  10774. * Get imported variables for deterministic usage, valid cases are:
  10775. *
  10776. * - `const { foo } = await import('bar')`.
  10777. * - `(await import('bar')).foo`
  10778. * - `import('bar').then(({ foo }) => {})`
  10779. *
  10780. * Returns empty array if it's side-effect only import.
  10781. * Returns undefined if it's not fully deterministic.
  10782. */
  10783. getDeterministicImportedNames() {
  10784. const parent1 = this.parent;
  10785. // Side-effect only: import('bar')
  10786. if (parent1 instanceof ExpressionStatement) {
  10787. return EMPTY_ARRAY;
  10788. }
  10789. if (parent1 instanceof AwaitExpression) {
  10790. const parent2 = parent1.parent;
  10791. // Side-effect only: await import('bar')
  10792. if (parent2 instanceof ExpressionStatement) {
  10793. return EMPTY_ARRAY;
  10794. }
  10795. // Case 1: const { foo } = await import('bar')
  10796. if (parent2 instanceof VariableDeclarator) {
  10797. const declaration = parent2.id;
  10798. return declaration instanceof ObjectPattern
  10799. ? getDeterministicObjectDestructure(declaration)
  10800. : undefined;
  10801. }
  10802. // Case 2: (await import('bar')).foo
  10803. if (parent2 instanceof MemberExpression) {
  10804. const id = parent2.property;
  10805. if (!parent2.computed && id instanceof Identifier) {
  10806. return [id.name];
  10807. }
  10808. }
  10809. return;
  10810. }
  10811. // Case 3: import('bar').then(({ foo }) => {})
  10812. if (parent1 instanceof MemberExpression) {
  10813. const callExpression = parent1.parent;
  10814. const property = parent1.property;
  10815. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  10816. return;
  10817. }
  10818. const memberName = property.name;
  10819. // side-effect only, when only chaining .catch or .finally
  10820. if (callExpression.parent instanceof ExpressionStatement &&
  10821. ['catch', 'finally'].includes(memberName)) {
  10822. return EMPTY_ARRAY;
  10823. }
  10824. if (memberName !== 'then')
  10825. return;
  10826. // Side-effect only: import('bar').then()
  10827. if (callExpression.arguments.length === 0) {
  10828. return EMPTY_ARRAY;
  10829. }
  10830. const argument = callExpression.arguments[0];
  10831. if (callExpression.arguments.length !== 1 ||
  10832. !(argument instanceof ArrowFunctionExpression || argument instanceof FunctionExpression)) {
  10833. return;
  10834. }
  10835. // Side-effect only: import('bar').then(() => {})
  10836. if (argument.params.length === 0) {
  10837. return EMPTY_ARRAY;
  10838. }
  10839. const declaration = argument.params[0];
  10840. if (argument.params.length === 1 && declaration instanceof ObjectPattern) {
  10841. return getDeterministicObjectDestructure(declaration);
  10842. }
  10843. return;
  10844. }
  10845. }
  10846. hasEffects() {
  10847. return true;
  10848. }
  10849. include(context, includeChildrenRecursively) {
  10850. if (!this.included) {
  10851. this.included = true;
  10852. this.context.includeDynamicImport(this);
  10853. this.scope.addAccessedDynamicImport(this);
  10854. }
  10855. this.source.include(context, includeChildrenRecursively);
  10856. }
  10857. initialise() {
  10858. this.context.addDynamicImport(this);
  10859. }
  10860. parseNode(esTreeNode) {
  10861. // Keep the source AST to be used by renderDynamicImport
  10862. super.parseNode(esTreeNode, ['source']);
  10863. }
  10864. render(code, options) {
  10865. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess } } = options;
  10866. if (this.inlineNamespace) {
  10867. const [left, right] = getDirectReturnFunction([], {
  10868. functionReturn: true,
  10869. lineBreakIndent: null,
  10870. name: null
  10871. });
  10872. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  10873. return;
  10874. }
  10875. if (this.mechanism) {
  10876. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  10877. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  10878. }
  10879. if (this.resolutionString) {
  10880. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  10881. if (this.namespaceExportName) {
  10882. const [left, right] = getDirectReturnFunction(['n'], {
  10883. functionReturn: true,
  10884. lineBreakIndent: null,
  10885. name: null
  10886. });
  10887. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  10888. }
  10889. }
  10890. else {
  10891. this.source.render(code, options);
  10892. }
  10893. if (this.assertions !== true) {
  10894. if (this.arguments) {
  10895. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  10896. }
  10897. if (this.assertions) {
  10898. code.appendLeft(this.end - 1, `,${_}${getObject([['assert', this.assertions]], {
  10899. lineBreakIndent: null
  10900. })}`);
  10901. }
  10902. }
  10903. }
  10904. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, assertions) {
  10905. const { format } = options;
  10906. this.inlineNamespace = null;
  10907. this.resolution = resolution;
  10908. this.resolutionString = resolutionString;
  10909. this.namespaceExportName = namespaceExportName;
  10910. this.assertions = assertions;
  10911. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  10912. let helper;
  10913. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  10914. if (helper) {
  10915. accessedGlobals.push(helper);
  10916. }
  10917. if (accessedGlobals.length > 0) {
  10918. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  10919. }
  10920. }
  10921. setInternalResolution(inlineNamespace) {
  10922. this.inlineNamespace = inlineNamespace;
  10923. }
  10924. applyDeoptimizations() { }
  10925. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  10926. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  10927. {
  10928. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  10929. format,
  10930. moduleId: this.context.module.id,
  10931. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  10932. }
  10933. ]);
  10934. if (mechanism) {
  10935. return { helper: null, mechanism };
  10936. }
  10937. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  10938. switch (format) {
  10939. case 'cjs': {
  10940. if (dynamicImportInCjs &&
  10941. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  10942. return { helper: null, mechanism: null };
  10943. }
  10944. const helper = getInteropHelper(resolution, exportMode, interop);
  10945. let left = `require(`;
  10946. let right = `)`;
  10947. if (helper) {
  10948. left = `/*#__PURE__*/${helper}(${left}`;
  10949. right += ')';
  10950. }
  10951. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  10952. functionReturn: true,
  10953. lineBreakIndent: null,
  10954. name: null
  10955. });
  10956. left = `Promise.resolve().then(${functionLeft}${left}`;
  10957. right += `${functionRight})`;
  10958. if (!arrowFunctions && hasDynamicTarget) {
  10959. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  10960. needsArrowReturnParens: false,
  10961. needsWrappedFunction: true
  10962. });
  10963. right = ')';
  10964. }
  10965. return {
  10966. helper,
  10967. mechanism: { left, right }
  10968. };
  10969. }
  10970. case 'amd': {
  10971. const resolve = compact ? 'c' : 'resolve';
  10972. const reject = compact ? 'e' : 'reject';
  10973. const helper = getInteropHelper(resolution, exportMode, interop);
  10974. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  10975. functionReturn: false,
  10976. lineBreakIndent: null,
  10977. name: null
  10978. });
  10979. const resolveNamespace = helper
  10980. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  10981. : resolve;
  10982. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  10983. functionReturn: false,
  10984. lineBreakIndent: null,
  10985. name: null
  10986. });
  10987. let left = `new Promise(${handlerLeft}require([`;
  10988. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  10989. if (!arrowFunctions && hasDynamicTarget) {
  10990. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  10991. needsArrowReturnParens: false,
  10992. needsWrappedFunction: true
  10993. });
  10994. right = ')';
  10995. }
  10996. return {
  10997. helper,
  10998. mechanism: { left, right }
  10999. };
  11000. }
  11001. case 'system': {
  11002. return {
  11003. helper: null,
  11004. mechanism: {
  11005. left: 'module.import(',
  11006. right: ')'
  11007. }
  11008. };
  11009. }
  11010. case 'es': {
  11011. if (dynamicImportFunction) {
  11012. return {
  11013. helper: null,
  11014. mechanism: {
  11015. left: `${dynamicImportFunction}(`,
  11016. right: ')'
  11017. }
  11018. };
  11019. }
  11020. }
  11021. }
  11022. return { helper: null, mechanism: null };
  11023. }
  11024. }
  11025. function getInteropHelper(resolution, exportMode, interop) {
  11026. return exportMode === 'external'
  11027. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  11028. : exportMode === 'default'
  11029. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  11030. : null;
  11031. }
  11032. const accessedImportGlobals = {
  11033. amd: ['require'],
  11034. cjs: ['require'],
  11035. system: ['module']
  11036. };
  11037. function getDeterministicObjectDestructure(objectPattern) {
  11038. const variables = [];
  11039. for (const property of objectPattern.properties) {
  11040. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  11041. return;
  11042. variables.push(property.key.name);
  11043. }
  11044. return variables;
  11045. }
  11046. class ImportNamespaceSpecifier extends NodeBase {
  11047. applyDeoptimizations() { }
  11048. }
  11049. class ImportSpecifier extends NodeBase {
  11050. applyDeoptimizations() { }
  11051. }
  11052. class LabeledStatement extends NodeBase {
  11053. hasEffects(context) {
  11054. const brokenFlow = context.brokenFlow;
  11055. context.ignore.labels.add(this.label.name);
  11056. if (this.body.hasEffects(context))
  11057. return true;
  11058. context.ignore.labels.delete(this.label.name);
  11059. if (context.includedLabels.has(this.label.name)) {
  11060. context.includedLabels.delete(this.label.name);
  11061. context.brokenFlow = brokenFlow;
  11062. }
  11063. return false;
  11064. }
  11065. include(context, includeChildrenRecursively) {
  11066. this.included = true;
  11067. const brokenFlow = context.brokenFlow;
  11068. this.body.include(context, includeChildrenRecursively);
  11069. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  11070. this.label.include();
  11071. context.includedLabels.delete(this.label.name);
  11072. context.brokenFlow = brokenFlow;
  11073. }
  11074. }
  11075. render(code, options) {
  11076. if (this.label.included) {
  11077. this.label.render(code, options);
  11078. }
  11079. else {
  11080. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  11081. }
  11082. this.body.render(code, options);
  11083. }
  11084. }
  11085. class LogicalExpression extends NodeBase {
  11086. constructor() {
  11087. super(...arguments);
  11088. // We collect deoptimization information if usedBranch !== null
  11089. this.expressionsToBeDeoptimized = [];
  11090. this.isBranchResolutionAnalysed = false;
  11091. this.usedBranch = null;
  11092. }
  11093. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11094. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11095. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11096. }
  11097. deoptimizeCache() {
  11098. if (this.usedBranch) {
  11099. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  11100. this.usedBranch = null;
  11101. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  11102. const { context, expressionsToBeDeoptimized } = this;
  11103. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  11104. for (const expression of expressionsToBeDeoptimized) {
  11105. expression.deoptimizeCache();
  11106. }
  11107. // Request another pass because we need to ensure "include" runs again if
  11108. // it is rendered
  11109. context.requestTreeshakingPass();
  11110. }
  11111. }
  11112. deoptimizePath(path) {
  11113. const usedBranch = this.getUsedBranch();
  11114. if (usedBranch) {
  11115. usedBranch.deoptimizePath(path);
  11116. }
  11117. else {
  11118. this.left.deoptimizePath(path);
  11119. this.right.deoptimizePath(path);
  11120. }
  11121. }
  11122. getLiteralValueAtPath(path, recursionTracker, origin) {
  11123. const usedBranch = this.getUsedBranch();
  11124. if (!usedBranch)
  11125. return UnknownValue;
  11126. this.expressionsToBeDeoptimized.push(origin);
  11127. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  11128. }
  11129. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11130. const usedBranch = this.getUsedBranch();
  11131. if (!usedBranch)
  11132. return [
  11133. new MultiExpression([
  11134. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  11135. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  11136. ]),
  11137. false
  11138. ];
  11139. this.expressionsToBeDeoptimized.push(origin);
  11140. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11141. }
  11142. hasEffects(context) {
  11143. if (this.left.hasEffects(context)) {
  11144. return true;
  11145. }
  11146. if (this.getUsedBranch() !== this.left) {
  11147. return this.right.hasEffects(context);
  11148. }
  11149. return false;
  11150. }
  11151. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11152. const usedBranch = this.getUsedBranch();
  11153. if (!usedBranch) {
  11154. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  11155. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  11156. }
  11157. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  11158. }
  11159. include(context, includeChildrenRecursively) {
  11160. this.included = true;
  11161. const usedBranch = this.getUsedBranch();
  11162. if (includeChildrenRecursively ||
  11163. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  11164. !usedBranch) {
  11165. this.left.include(context, includeChildrenRecursively);
  11166. this.right.include(context, includeChildrenRecursively);
  11167. }
  11168. else {
  11169. usedBranch.include(context, includeChildrenRecursively);
  11170. }
  11171. }
  11172. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  11173. if (!this.left.included || !this.right.included) {
  11174. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  11175. if (this.right.included) {
  11176. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  11177. code.remove(this.start, removePos);
  11178. if (preventASI) {
  11179. removeLineBreaks(code, removePos, this.right.start);
  11180. }
  11181. }
  11182. else {
  11183. code.remove(operatorPos, this.end);
  11184. }
  11185. removeAnnotations(this, code);
  11186. this.getUsedBranch().render(code, options, {
  11187. isCalleeOfRenderedParent,
  11188. preventASI,
  11189. renderedParentType: renderedParentType || this.parent.type,
  11190. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  11191. });
  11192. }
  11193. else {
  11194. this.left.render(code, options, {
  11195. preventASI,
  11196. renderedSurroundingElement
  11197. });
  11198. this.right.render(code, options);
  11199. }
  11200. }
  11201. getUsedBranch() {
  11202. if (!this.isBranchResolutionAnalysed) {
  11203. this.isBranchResolutionAnalysed = true;
  11204. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  11205. if (typeof leftValue === 'symbol') {
  11206. return null;
  11207. }
  11208. else {
  11209. this.usedBranch =
  11210. (this.operator === '||' && leftValue) ||
  11211. (this.operator === '&&' && !leftValue) ||
  11212. (this.operator === '??' && leftValue != null)
  11213. ? this.left
  11214. : this.right;
  11215. }
  11216. }
  11217. return this.usedBranch;
  11218. }
  11219. }
  11220. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  11221. const IMPORT = 'import';
  11222. class MetaProperty extends NodeBase {
  11223. constructor() {
  11224. super(...arguments);
  11225. this.metaProperty = null;
  11226. this.preliminaryChunkId = null;
  11227. this.referenceId = null;
  11228. }
  11229. getReferencedFileName(outputPluginDriver) {
  11230. const { meta: { name }, metaProperty } = this;
  11231. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  11232. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  11233. }
  11234. return null;
  11235. }
  11236. hasEffects() {
  11237. return false;
  11238. }
  11239. hasEffectsOnInteractionAtPath(path, { type }) {
  11240. return path.length > 1 || type !== INTERACTION_ACCESSED;
  11241. }
  11242. include() {
  11243. if (!this.included) {
  11244. this.included = true;
  11245. if (this.meta.name === IMPORT) {
  11246. this.context.addImportMeta(this);
  11247. const parent = this.parent;
  11248. const metaProperty = (this.metaProperty =
  11249. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  11250. ? parent.propertyKey
  11251. : null);
  11252. if (metaProperty?.startsWith(FILE_PREFIX)) {
  11253. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  11254. }
  11255. }
  11256. }
  11257. }
  11258. render(code, { format, pluginDriver, snippets }) {
  11259. const { context: { module: { id: moduleId } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  11260. if (name !== IMPORT)
  11261. return;
  11262. const chunkId = preliminaryChunkId;
  11263. if (referenceId) {
  11264. const fileName = pluginDriver.getFileName(referenceId);
  11265. const relativePath = normalize(node_path.relative(node_path.dirname(chunkId), fileName));
  11266. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  11267. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  11268. ]) || relativeUrlMechanisms[format](relativePath);
  11269. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  11270. return;
  11271. }
  11272. const replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  11273. metaProperty,
  11274. { chunkId, format, moduleId }
  11275. ]) || importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  11276. if (typeof replacement === 'string') {
  11277. if (parent instanceof MemberExpression) {
  11278. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  11279. }
  11280. else {
  11281. code.overwrite(start, end, replacement, { contentOnly: true });
  11282. }
  11283. }
  11284. }
  11285. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  11286. this.preliminaryChunkId = preliminaryChunkId;
  11287. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  11288. if (accessedGlobals.length > 0) {
  11289. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  11290. }
  11291. }
  11292. }
  11293. const accessedMetaUrlGlobals = {
  11294. amd: ['document', 'module', 'URL'],
  11295. cjs: ['document', 'require', 'URL'],
  11296. es: [],
  11297. iife: ['document', 'URL'],
  11298. system: ['module'],
  11299. umd: ['document', 'require', 'URL']
  11300. };
  11301. const accessedFileUrlGlobals = {
  11302. amd: ['document', 'require', 'URL'],
  11303. cjs: ['document', 'require', 'URL'],
  11304. es: [],
  11305. iife: ['document', 'URL'],
  11306. system: ['module', 'URL'],
  11307. umd: ['document', 'require', 'URL']
  11308. };
  11309. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  11310. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
  11311. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  11312. const urlMechanism = getUrl(chunkId);
  11313. return property === null
  11314. ? `({ url: ${urlMechanism} })`
  11315. : property === 'url'
  11316. ? urlMechanism
  11317. : 'undefined';
  11318. };
  11319. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  11320. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${path}'`);
  11321. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.src || new URL('${escapeId(chunkId)}', document.baseURI).href)`;
  11322. const relativeUrlMechanisms = {
  11323. amd: relativePath => {
  11324. if (relativePath[0] !== '.')
  11325. relativePath = './' + relativePath;
  11326. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  11327. },
  11328. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  11329. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  11330. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  11331. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  11332. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  11333. };
  11334. const importMetaMechanisms = {
  11335. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  11336. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  11337. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  11338. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  11339. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  11340. };
  11341. class NewExpression extends NodeBase {
  11342. hasEffects(context) {
  11343. try {
  11344. for (const argument of this.arguments) {
  11345. if (argument.hasEffects(context))
  11346. return true;
  11347. }
  11348. if (this.context.options.treeshake.annotations &&
  11349. this.annotations) {
  11350. return false;
  11351. }
  11352. return (this.callee.hasEffects(context) ||
  11353. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  11354. }
  11355. finally {
  11356. if (!this.deoptimized)
  11357. this.applyDeoptimizations();
  11358. }
  11359. }
  11360. hasEffectsOnInteractionAtPath(path, { type }) {
  11361. return path.length > 0 || type !== INTERACTION_ACCESSED;
  11362. }
  11363. include(context, includeChildrenRecursively) {
  11364. if (!this.deoptimized)
  11365. this.applyDeoptimizations();
  11366. if (includeChildrenRecursively) {
  11367. super.include(context, includeChildrenRecursively);
  11368. }
  11369. else {
  11370. this.included = true;
  11371. this.callee.include(context, false);
  11372. }
  11373. this.callee.includeCallArguments(context, this.arguments);
  11374. }
  11375. initialise() {
  11376. this.interaction = {
  11377. args: [null, ...this.arguments],
  11378. type: INTERACTION_CALLED,
  11379. withNew: true
  11380. };
  11381. }
  11382. render(code, options) {
  11383. this.callee.render(code, options);
  11384. renderCallArguments(code, options, this);
  11385. }
  11386. applyDeoptimizations() {
  11387. this.deoptimized = true;
  11388. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  11389. this.context.requestTreeshakingPass();
  11390. }
  11391. }
  11392. class ObjectExpression extends NodeBase {
  11393. constructor() {
  11394. super(...arguments);
  11395. this.objectEntity = null;
  11396. }
  11397. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11398. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11399. }
  11400. deoptimizeCache() {
  11401. this.getObjectEntity().deoptimizeAllProperties();
  11402. }
  11403. deoptimizePath(path) {
  11404. this.getObjectEntity().deoptimizePath(path);
  11405. }
  11406. getLiteralValueAtPath(path, recursionTracker, origin) {
  11407. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  11408. }
  11409. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11410. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11411. }
  11412. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11413. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  11414. }
  11415. render(code, options, { renderedSurroundingElement } = BLANK) {
  11416. super.render(code, options);
  11417. if (renderedSurroundingElement === ExpressionStatement$1 ||
  11418. renderedSurroundingElement === ArrowFunctionExpression$1) {
  11419. code.appendRight(this.start, '(');
  11420. code.prependLeft(this.end, ')');
  11421. }
  11422. }
  11423. applyDeoptimizations() { }
  11424. getObjectEntity() {
  11425. if (this.objectEntity !== null) {
  11426. return this.objectEntity;
  11427. }
  11428. let prototype = OBJECT_PROTOTYPE;
  11429. const properties = [];
  11430. for (const property of this.properties) {
  11431. if (property instanceof SpreadElement) {
  11432. properties.push({ key: UnknownKey, kind: 'init', property });
  11433. continue;
  11434. }
  11435. let key;
  11436. if (property.computed) {
  11437. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  11438. if (typeof keyValue === 'symbol') {
  11439. properties.push({ key: UnknownKey, kind: property.kind, property });
  11440. continue;
  11441. }
  11442. else {
  11443. key = String(keyValue);
  11444. }
  11445. }
  11446. else {
  11447. key =
  11448. property.key instanceof Identifier
  11449. ? property.key.name
  11450. : String(property.key.value);
  11451. if (key === '__proto__' && property.kind === 'init') {
  11452. prototype =
  11453. property.value instanceof Literal && property.value.value === null
  11454. ? null
  11455. : property.value;
  11456. continue;
  11457. }
  11458. }
  11459. properties.push({ key, kind: property.kind, property });
  11460. }
  11461. return (this.objectEntity = new ObjectEntity(properties, prototype));
  11462. }
  11463. }
  11464. class PrivateIdentifier extends NodeBase {
  11465. }
  11466. function getOriginalLocation(sourcemapChain, location) {
  11467. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !!sourcemap.mappings);
  11468. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  11469. const sourcemap = filteredSourcemapChain.pop();
  11470. const line = sourcemap.mappings[location.line - 1];
  11471. if (line) {
  11472. const filteredLine = line.filter((segment) => segment.length > 1);
  11473. const lastSegment = filteredLine[filteredLine.length - 1];
  11474. for (const segment of filteredLine) {
  11475. if (segment[0] >= location.column || segment === lastSegment) {
  11476. location = {
  11477. column: segment[3],
  11478. line: segment[2] + 1
  11479. };
  11480. continue traceSourcemap;
  11481. }
  11482. }
  11483. }
  11484. throw new Error("Can't resolve original location of error.");
  11485. }
  11486. return location;
  11487. }
  11488. class Program extends NodeBase {
  11489. constructor() {
  11490. super(...arguments);
  11491. this.hasCachedEffect = null;
  11492. this.hasLoggedEffect = false;
  11493. }
  11494. hasCachedEffects() {
  11495. if (!this.included) {
  11496. return false;
  11497. }
  11498. return this.hasCachedEffect === null
  11499. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  11500. : this.hasCachedEffect;
  11501. }
  11502. hasEffects(context) {
  11503. for (const node of this.body) {
  11504. if (node.hasEffects(context)) {
  11505. if (this.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  11506. this.hasLoggedEffect = true;
  11507. const { code, module } = this.context;
  11508. const { line, column } = locate(code, node.start, { offsetLine: 1 });
  11509. console.log(`First side effect in ${relativeId(module.id)} is at (${line}:${column})\n${getCodeFrame(code, line, column)}`);
  11510. try {
  11511. const { column: originalColumn, line: originalLine } = getOriginalLocation(module.sourcemapChain, { column, line });
  11512. if (originalLine !== line) {
  11513. console.log(`Original location is at (${originalLine}:${originalColumn})\n${getCodeFrame(module.originalCode, originalLine, originalColumn)}\n`);
  11514. }
  11515. }
  11516. catch {
  11517. /* ignored */
  11518. }
  11519. console.log();
  11520. }
  11521. return (this.hasCachedEffect = true);
  11522. }
  11523. }
  11524. return false;
  11525. }
  11526. include(context, includeChildrenRecursively) {
  11527. this.included = true;
  11528. for (const node of this.body) {
  11529. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  11530. node.include(context, includeChildrenRecursively);
  11531. }
  11532. }
  11533. }
  11534. render(code, options) {
  11535. let start = this.start;
  11536. if (code.original.startsWith('#!')) {
  11537. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  11538. code.remove(0, start);
  11539. }
  11540. if (this.body.length > 0) {
  11541. // Keep all consecutive lines that start with a comment
  11542. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  11543. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  11544. if (firstLineBreak[0] === -1) {
  11545. break;
  11546. }
  11547. start += firstLineBreak[1];
  11548. }
  11549. renderStatementList(this.body, code, start, this.end, options);
  11550. }
  11551. else {
  11552. super.render(code, options);
  11553. }
  11554. }
  11555. applyDeoptimizations() { }
  11556. }
  11557. class Property extends MethodBase {
  11558. constructor() {
  11559. super(...arguments);
  11560. this.declarationInit = null;
  11561. }
  11562. declare(kind, init) {
  11563. this.declarationInit = init;
  11564. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  11565. }
  11566. hasEffects(context) {
  11567. if (!this.deoptimized)
  11568. this.applyDeoptimizations();
  11569. const propertyReadSideEffects = this.context.options.treeshake
  11570. .propertyReadSideEffects;
  11571. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  11572. this.key.hasEffects(context) ||
  11573. this.value.hasEffects(context));
  11574. }
  11575. markDeclarationReached() {
  11576. this.value.markDeclarationReached();
  11577. }
  11578. render(code, options) {
  11579. if (!this.shorthand) {
  11580. this.key.render(code, options);
  11581. }
  11582. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  11583. }
  11584. applyDeoptimizations() {
  11585. this.deoptimized = true;
  11586. if (this.declarationInit !== null) {
  11587. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  11588. this.context.requestTreeshakingPass();
  11589. }
  11590. }
  11591. }
  11592. class PropertyDefinition extends NodeBase {
  11593. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11594. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11595. }
  11596. deoptimizePath(path) {
  11597. this.value?.deoptimizePath(path);
  11598. }
  11599. getLiteralValueAtPath(path, recursionTracker, origin) {
  11600. return this.value
  11601. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  11602. : UnknownValue;
  11603. }
  11604. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11605. return this.value
  11606. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  11607. : UNKNOWN_RETURN_EXPRESSION;
  11608. }
  11609. hasEffects(context) {
  11610. return this.key.hasEffects(context) || (this.static && !!this.value?.hasEffects(context));
  11611. }
  11612. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11613. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  11614. }
  11615. applyDeoptimizations() { }
  11616. }
  11617. class ReturnStatement extends NodeBase {
  11618. hasEffects(context) {
  11619. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  11620. return true;
  11621. context.brokenFlow = true;
  11622. return false;
  11623. }
  11624. include(context, includeChildrenRecursively) {
  11625. this.included = true;
  11626. this.argument?.include(context, includeChildrenRecursively);
  11627. context.brokenFlow = true;
  11628. }
  11629. initialise() {
  11630. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  11631. }
  11632. render(code, options) {
  11633. if (this.argument) {
  11634. this.argument.render(code, options, { preventASI: true });
  11635. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  11636. code.prependLeft(this.start + 6, ' ');
  11637. }
  11638. }
  11639. }
  11640. }
  11641. class SequenceExpression extends NodeBase {
  11642. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11643. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11644. }
  11645. deoptimizePath(path) {
  11646. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  11647. }
  11648. getLiteralValueAtPath(path, recursionTracker, origin) {
  11649. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  11650. }
  11651. hasEffects(context) {
  11652. for (const expression of this.expressions) {
  11653. if (expression.hasEffects(context))
  11654. return true;
  11655. }
  11656. return false;
  11657. }
  11658. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11659. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  11660. }
  11661. include(context, includeChildrenRecursively) {
  11662. this.included = true;
  11663. const lastExpression = this.expressions[this.expressions.length - 1];
  11664. for (const expression of this.expressions) {
  11665. if (includeChildrenRecursively ||
  11666. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  11667. expression.shouldBeIncluded(context))
  11668. expression.include(context, includeChildrenRecursively);
  11669. }
  11670. }
  11671. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  11672. let includedNodes = 0;
  11673. let lastSeparatorPos = null;
  11674. const lastNode = this.expressions[this.expressions.length - 1];
  11675. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  11676. if (!node.included) {
  11677. treeshakeNode(node, code, start, end);
  11678. continue;
  11679. }
  11680. includedNodes++;
  11681. lastSeparatorPos = separator;
  11682. if (includedNodes === 1 && preventASI) {
  11683. removeLineBreaks(code, start, node.start);
  11684. }
  11685. if (includedNodes === 1) {
  11686. const parentType = renderedParentType || this.parent.type;
  11687. node.render(code, options, {
  11688. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  11689. renderedParentType: parentType,
  11690. renderedSurroundingElement: parentType
  11691. });
  11692. }
  11693. else {
  11694. node.render(code, options);
  11695. }
  11696. }
  11697. if (lastSeparatorPos) {
  11698. code.remove(lastSeparatorPos, this.end);
  11699. }
  11700. }
  11701. }
  11702. class StaticBlock extends NodeBase {
  11703. createScope(parentScope) {
  11704. this.scope = new BlockScope(parentScope);
  11705. }
  11706. hasEffects(context) {
  11707. for (const node of this.body) {
  11708. if (node.hasEffects(context))
  11709. return true;
  11710. }
  11711. return false;
  11712. }
  11713. include(context, includeChildrenRecursively) {
  11714. this.included = true;
  11715. for (const node of this.body) {
  11716. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  11717. node.include(context, includeChildrenRecursively);
  11718. }
  11719. }
  11720. render(code, options) {
  11721. if (this.body.length > 0) {
  11722. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  11723. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  11724. }
  11725. else {
  11726. super.render(code, options);
  11727. }
  11728. }
  11729. }
  11730. class Super extends NodeBase {
  11731. bind() {
  11732. this.variable = this.scope.findVariable('this');
  11733. }
  11734. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11735. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11736. }
  11737. deoptimizePath(path) {
  11738. this.variable.deoptimizePath(path);
  11739. }
  11740. include() {
  11741. if (!this.included) {
  11742. this.included = true;
  11743. this.context.includeVariableInModule(this.variable);
  11744. }
  11745. }
  11746. }
  11747. class SwitchCase extends NodeBase {
  11748. hasEffects(context) {
  11749. if (this.test?.hasEffects(context))
  11750. return true;
  11751. for (const node of this.consequent) {
  11752. if (context.brokenFlow)
  11753. break;
  11754. if (node.hasEffects(context))
  11755. return true;
  11756. }
  11757. return false;
  11758. }
  11759. include(context, includeChildrenRecursively) {
  11760. this.included = true;
  11761. this.test?.include(context, includeChildrenRecursively);
  11762. for (const node of this.consequent) {
  11763. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  11764. node.include(context, includeChildrenRecursively);
  11765. }
  11766. }
  11767. render(code, options, nodeRenderOptions) {
  11768. if (this.consequent.length > 0) {
  11769. this.test && this.test.render(code, options);
  11770. const testEnd = this.test
  11771. ? this.test.end
  11772. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  11773. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  11774. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  11775. }
  11776. else {
  11777. super.render(code, options);
  11778. }
  11779. }
  11780. }
  11781. SwitchCase.prototype.needsBoundaries = true;
  11782. class SwitchStatement extends NodeBase {
  11783. createScope(parentScope) {
  11784. this.parentScope = parentScope;
  11785. this.scope = new BlockScope(parentScope);
  11786. }
  11787. hasEffects(context) {
  11788. if (this.discriminant.hasEffects(context))
  11789. return true;
  11790. const { brokenFlow, hasBreak, ignore } = context;
  11791. const { breaks } = ignore;
  11792. ignore.breaks = true;
  11793. context.hasBreak = false;
  11794. let onlyHasBrokenFlow = true;
  11795. for (const switchCase of this.cases) {
  11796. if (switchCase.hasEffects(context))
  11797. return true;
  11798. // eslint-disable-next-line unicorn/consistent-destructuring
  11799. onlyHasBrokenFlow && (onlyHasBrokenFlow = context.brokenFlow && !context.hasBreak);
  11800. context.hasBreak = false;
  11801. context.brokenFlow = brokenFlow;
  11802. }
  11803. if (this.defaultCase !== null) {
  11804. context.brokenFlow = onlyHasBrokenFlow;
  11805. }
  11806. ignore.breaks = breaks;
  11807. context.hasBreak = hasBreak;
  11808. return false;
  11809. }
  11810. include(context, includeChildrenRecursively) {
  11811. this.included = true;
  11812. this.discriminant.include(context, includeChildrenRecursively);
  11813. const { brokenFlow, hasBreak } = context;
  11814. context.hasBreak = false;
  11815. let onlyHasBrokenFlow = true;
  11816. let isCaseIncluded = includeChildrenRecursively ||
  11817. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  11818. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  11819. const switchCase = this.cases[caseIndex];
  11820. if (switchCase.included) {
  11821. isCaseIncluded = true;
  11822. }
  11823. if (!isCaseIncluded) {
  11824. const hasEffectsContext = createHasEffectsContext();
  11825. hasEffectsContext.ignore.breaks = true;
  11826. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  11827. }
  11828. if (isCaseIncluded) {
  11829. switchCase.include(context, includeChildrenRecursively);
  11830. // eslint-disable-next-line unicorn/consistent-destructuring
  11831. onlyHasBrokenFlow && (onlyHasBrokenFlow = context.brokenFlow && !context.hasBreak);
  11832. context.hasBreak = false;
  11833. context.brokenFlow = brokenFlow;
  11834. }
  11835. else {
  11836. onlyHasBrokenFlow = brokenFlow;
  11837. }
  11838. }
  11839. if (isCaseIncluded && this.defaultCase !== null) {
  11840. context.brokenFlow = onlyHasBrokenFlow;
  11841. }
  11842. context.hasBreak = hasBreak;
  11843. }
  11844. initialise() {
  11845. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  11846. if (this.cases[caseIndex].test === null) {
  11847. this.defaultCase = caseIndex;
  11848. return;
  11849. }
  11850. }
  11851. this.defaultCase = null;
  11852. }
  11853. parseNode(esTreeNode) {
  11854. this.discriminant = new (this.context.getNodeConstructor(esTreeNode.discriminant.type))(esTreeNode.discriminant, this, this.parentScope);
  11855. super.parseNode(esTreeNode);
  11856. }
  11857. render(code, options) {
  11858. this.discriminant.render(code, options);
  11859. if (this.cases.length > 0) {
  11860. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  11861. }
  11862. }
  11863. }
  11864. class TaggedTemplateExpression extends CallExpressionBase {
  11865. bind() {
  11866. super.bind();
  11867. if (this.tag.type === Identifier$1) {
  11868. const name = this.tag.name;
  11869. const variable = this.scope.findVariable(name);
  11870. if (variable.isNamespace) {
  11871. this.context.warn(errorCannotCallNamespace(name), this.start);
  11872. }
  11873. }
  11874. }
  11875. hasEffects(context) {
  11876. try {
  11877. for (const argument of this.quasi.expressions) {
  11878. if (argument.hasEffects(context))
  11879. return true;
  11880. }
  11881. return (this.tag.hasEffects(context) ||
  11882. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  11883. }
  11884. finally {
  11885. if (!this.deoptimized)
  11886. this.applyDeoptimizations();
  11887. }
  11888. }
  11889. include(context, includeChildrenRecursively) {
  11890. if (!this.deoptimized)
  11891. this.applyDeoptimizations();
  11892. if (includeChildrenRecursively) {
  11893. super.include(context, includeChildrenRecursively);
  11894. }
  11895. else {
  11896. this.included = true;
  11897. this.tag.include(context, includeChildrenRecursively);
  11898. this.quasi.include(context, includeChildrenRecursively);
  11899. }
  11900. this.tag.includeCallArguments(context, this.args);
  11901. const [returnExpression] = this.getReturnExpression();
  11902. if (!returnExpression.included) {
  11903. returnExpression.include(context, false);
  11904. }
  11905. }
  11906. initialise() {
  11907. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  11908. this.interaction = {
  11909. args: [
  11910. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  11911. ...this.args
  11912. ],
  11913. type: INTERACTION_CALLED,
  11914. withNew: false
  11915. };
  11916. }
  11917. render(code, options) {
  11918. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  11919. this.quasi.render(code, options);
  11920. }
  11921. applyDeoptimizations() {
  11922. this.deoptimized = true;
  11923. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  11924. this.context.requestTreeshakingPass();
  11925. }
  11926. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  11927. if (this.returnExpression === null) {
  11928. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11929. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  11930. }
  11931. return this.returnExpression;
  11932. }
  11933. }
  11934. class TemplateElement extends NodeBase {
  11935. // Do not try to bind value
  11936. bind() { }
  11937. hasEffects() {
  11938. return false;
  11939. }
  11940. include() {
  11941. this.included = true;
  11942. }
  11943. parseNode(esTreeNode) {
  11944. this.value = esTreeNode.value;
  11945. super.parseNode(esTreeNode);
  11946. }
  11947. render() { }
  11948. }
  11949. class TemplateLiteral extends NodeBase {
  11950. deoptimizeArgumentsOnInteractionAtPath() { }
  11951. getLiteralValueAtPath(path) {
  11952. if (path.length > 0 || this.quasis.length !== 1) {
  11953. return UnknownValue;
  11954. }
  11955. return this.quasis[0].value.cooked;
  11956. }
  11957. getReturnExpressionWhenCalledAtPath(path) {
  11958. if (path.length !== 1) {
  11959. return UNKNOWN_RETURN_EXPRESSION;
  11960. }
  11961. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  11962. }
  11963. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11964. if (interaction.type === INTERACTION_ACCESSED) {
  11965. return path.length > 1;
  11966. }
  11967. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  11968. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  11969. }
  11970. return true;
  11971. }
  11972. render(code, options) {
  11973. code.indentExclusionRanges.push([this.start, this.end]);
  11974. super.render(code, options);
  11975. }
  11976. }
  11977. class UndefinedVariable extends Variable {
  11978. constructor() {
  11979. super('undefined');
  11980. }
  11981. getLiteralValueAtPath() {
  11982. return undefined;
  11983. }
  11984. }
  11985. class ExportDefaultVariable extends LocalVariable {
  11986. constructor(name, exportDefaultDeclaration, context) {
  11987. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  11988. this.hasId = false;
  11989. this.originalId = null;
  11990. this.originalVariable = null;
  11991. const declaration = exportDefaultDeclaration.declaration;
  11992. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  11993. declaration.id) {
  11994. this.hasId = true;
  11995. this.originalId = declaration.id;
  11996. }
  11997. else if (declaration instanceof Identifier) {
  11998. this.originalId = declaration;
  11999. }
  12000. }
  12001. addReference(identifier) {
  12002. if (!this.hasId) {
  12003. this.name = identifier.name;
  12004. }
  12005. }
  12006. forbidName(name) {
  12007. const original = this.getOriginalVariable();
  12008. if (original === this) {
  12009. super.forbidName(name);
  12010. }
  12011. else {
  12012. original.forbidName(name);
  12013. }
  12014. }
  12015. getAssignedVariableName() {
  12016. return (this.originalId && this.originalId.name) || null;
  12017. }
  12018. getBaseVariableName() {
  12019. const original = this.getOriginalVariable();
  12020. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  12021. }
  12022. getDirectOriginalVariable() {
  12023. return this.originalId &&
  12024. (this.hasId ||
  12025. !(this.originalId.isPossibleTDZ() ||
  12026. this.originalId.variable.isReassigned ||
  12027. this.originalId.variable instanceof UndefinedVariable ||
  12028. // this avoids a circular dependency
  12029. 'syntheticNamespace' in this.originalId.variable))
  12030. ? this.originalId.variable
  12031. : null;
  12032. }
  12033. getName(getPropertyAccess) {
  12034. const original = this.getOriginalVariable();
  12035. return original === this
  12036. ? super.getName(getPropertyAccess)
  12037. : original.getName(getPropertyAccess);
  12038. }
  12039. getOriginalVariable() {
  12040. if (this.originalVariable)
  12041. return this.originalVariable;
  12042. // eslint-disable-next-line @typescript-eslint/no-this-alias
  12043. let original = this;
  12044. let currentVariable;
  12045. const checkedVariables = new Set();
  12046. do {
  12047. checkedVariables.add(original);
  12048. currentVariable = original;
  12049. original = currentVariable.getDirectOriginalVariable();
  12050. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  12051. return (this.originalVariable = original || currentVariable);
  12052. }
  12053. }
  12054. class ModuleScope extends ChildScope {
  12055. constructor(parent, context) {
  12056. super(parent);
  12057. this.context = context;
  12058. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  12059. }
  12060. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  12061. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  12062. this.variables.set('default', variable);
  12063. return variable;
  12064. }
  12065. addNamespaceMemberAccess() { }
  12066. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  12067. // all module level variables are already deconflicted when deconflicting the chunk
  12068. for (const scope of this.children)
  12069. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  12070. }
  12071. findLexicalBoundary() {
  12072. return this;
  12073. }
  12074. findVariable(name) {
  12075. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  12076. if (knownVariable) {
  12077. return knownVariable;
  12078. }
  12079. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  12080. if (variable instanceof GlobalVariable) {
  12081. this.accessedOutsideVariables.set(name, variable);
  12082. }
  12083. return variable;
  12084. }
  12085. }
  12086. class ThisExpression extends NodeBase {
  12087. bind() {
  12088. this.variable = this.scope.findVariable('this');
  12089. }
  12090. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12091. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12092. }
  12093. deoptimizePath(path) {
  12094. this.variable.deoptimizePath(path);
  12095. }
  12096. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12097. if (path.length === 0) {
  12098. return interaction.type !== INTERACTION_ACCESSED;
  12099. }
  12100. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  12101. }
  12102. include() {
  12103. if (!this.included) {
  12104. this.included = true;
  12105. this.context.includeVariableInModule(this.variable);
  12106. }
  12107. }
  12108. initialise() {
  12109. this.alias =
  12110. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  12111. if (this.alias === 'undefined') {
  12112. this.context.warn(errorThisIsUndefined(), this.start);
  12113. }
  12114. }
  12115. render(code) {
  12116. if (this.alias !== null) {
  12117. code.overwrite(this.start, this.end, this.alias, {
  12118. contentOnly: false,
  12119. storeName: true
  12120. });
  12121. }
  12122. }
  12123. }
  12124. class ThrowStatement extends NodeBase {
  12125. hasEffects() {
  12126. return true;
  12127. }
  12128. include(context, includeChildrenRecursively) {
  12129. this.included = true;
  12130. this.argument.include(context, includeChildrenRecursively);
  12131. context.brokenFlow = true;
  12132. }
  12133. render(code, options) {
  12134. this.argument.render(code, options, { preventASI: true });
  12135. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  12136. code.prependLeft(this.start + 5, ' ');
  12137. }
  12138. }
  12139. }
  12140. class TryStatement extends NodeBase {
  12141. constructor() {
  12142. super(...arguments);
  12143. this.directlyIncluded = false;
  12144. this.includedLabelsAfterBlock = null;
  12145. }
  12146. hasEffects(context) {
  12147. return ((this.context.options.treeshake.tryCatchDeoptimization
  12148. ? this.block.body.length > 0
  12149. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  12150. }
  12151. include(context, includeChildrenRecursively) {
  12152. const tryCatchDeoptimization = this.context.options.treeshake
  12153. ?.tryCatchDeoptimization;
  12154. const { brokenFlow, includedLabels } = context;
  12155. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  12156. this.included = true;
  12157. this.directlyIncluded = true;
  12158. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  12159. if (includedLabels.size > 0) {
  12160. this.includedLabelsAfterBlock = [...includedLabels];
  12161. }
  12162. context.brokenFlow = brokenFlow;
  12163. }
  12164. else if (this.includedLabelsAfterBlock) {
  12165. for (const label of this.includedLabelsAfterBlock) {
  12166. includedLabels.add(label);
  12167. }
  12168. }
  12169. if (this.handler !== null) {
  12170. this.handler.include(context, includeChildrenRecursively);
  12171. context.brokenFlow = brokenFlow;
  12172. }
  12173. this.finalizer?.include(context, includeChildrenRecursively);
  12174. }
  12175. }
  12176. const unaryOperators = {
  12177. '!': value => !value,
  12178. '+': value => +value,
  12179. '-': value => -value,
  12180. delete: () => UnknownValue,
  12181. typeof: value => typeof value,
  12182. void: () => undefined,
  12183. '~': value => ~value
  12184. };
  12185. class UnaryExpression extends NodeBase {
  12186. getLiteralValueAtPath(path, recursionTracker, origin) {
  12187. if (path.length > 0)
  12188. return UnknownValue;
  12189. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  12190. if (typeof argumentValue === 'symbol')
  12191. return UnknownValue;
  12192. return unaryOperators[this.operator](argumentValue);
  12193. }
  12194. hasEffects(context) {
  12195. if (!this.deoptimized)
  12196. this.applyDeoptimizations();
  12197. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  12198. return false;
  12199. return (this.argument.hasEffects(context) ||
  12200. (this.operator === 'delete' &&
  12201. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  12202. }
  12203. hasEffectsOnInteractionAtPath(path, { type }) {
  12204. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  12205. }
  12206. applyDeoptimizations() {
  12207. this.deoptimized = true;
  12208. if (this.operator === 'delete') {
  12209. this.argument.deoptimizePath(EMPTY_PATH);
  12210. this.context.requestTreeshakingPass();
  12211. }
  12212. }
  12213. }
  12214. class UnknownNode extends NodeBase {
  12215. hasEffects() {
  12216. return true;
  12217. }
  12218. include(context) {
  12219. super.include(context, true);
  12220. }
  12221. }
  12222. class UpdateExpression extends NodeBase {
  12223. hasEffects(context) {
  12224. if (!this.deoptimized)
  12225. this.applyDeoptimizations();
  12226. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  12227. }
  12228. hasEffectsOnInteractionAtPath(path, { type }) {
  12229. return path.length > 1 || type !== INTERACTION_ACCESSED;
  12230. }
  12231. include(context, includeChildrenRecursively) {
  12232. if (!this.deoptimized)
  12233. this.applyDeoptimizations();
  12234. this.included = true;
  12235. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  12236. }
  12237. initialise() {
  12238. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  12239. }
  12240. render(code, options) {
  12241. const { exportNamesByVariable, format, snippets: { _ } } = options;
  12242. this.argument.render(code, options);
  12243. if (format === 'system') {
  12244. const variable = this.argument.variable;
  12245. const exportNames = exportNamesByVariable.get(variable);
  12246. if (exportNames) {
  12247. if (this.prefix) {
  12248. if (exportNames.length === 1) {
  12249. renderSystemExportExpression(variable, this.start, this.end, code, options);
  12250. }
  12251. else {
  12252. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  12253. }
  12254. }
  12255. else {
  12256. const operator = this.operator[0];
  12257. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  12258. }
  12259. }
  12260. }
  12261. }
  12262. applyDeoptimizations() {
  12263. this.deoptimized = true;
  12264. this.argument.deoptimizePath(EMPTY_PATH);
  12265. if (this.argument instanceof Identifier) {
  12266. const variable = this.scope.findVariable(this.argument.name);
  12267. variable.isReassigned = true;
  12268. }
  12269. this.context.requestTreeshakingPass();
  12270. }
  12271. }
  12272. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  12273. for (const declarator of declarations) {
  12274. if (!declarator.id.included)
  12275. return false;
  12276. if (declarator.id.type === Identifier$1) {
  12277. if (exportNamesByVariable.has(declarator.id.variable))
  12278. return false;
  12279. }
  12280. else {
  12281. const exportedVariables = [];
  12282. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  12283. if (exportedVariables.length > 0)
  12284. return false;
  12285. }
  12286. }
  12287. return true;
  12288. }
  12289. class VariableDeclaration extends NodeBase {
  12290. deoptimizePath() {
  12291. for (const declarator of this.declarations) {
  12292. declarator.deoptimizePath(EMPTY_PATH);
  12293. }
  12294. }
  12295. hasEffectsOnInteractionAtPath() {
  12296. return false;
  12297. }
  12298. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  12299. this.included = true;
  12300. for (const declarator of this.declarations) {
  12301. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  12302. declarator.include(context, includeChildrenRecursively);
  12303. const { id, init } = declarator;
  12304. if (asSingleStatement) {
  12305. id.include(context, includeChildrenRecursively);
  12306. }
  12307. if (init &&
  12308. id.included &&
  12309. !init.included &&
  12310. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  12311. init.include(context, includeChildrenRecursively);
  12312. }
  12313. }
  12314. }
  12315. initialise() {
  12316. for (const declarator of this.declarations) {
  12317. declarator.declareDeclarator(this.kind);
  12318. }
  12319. }
  12320. render(code, options, nodeRenderOptions = BLANK) {
  12321. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  12322. for (const declarator of this.declarations) {
  12323. declarator.render(code, options);
  12324. }
  12325. if (!nodeRenderOptions.isNoStatement &&
  12326. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  12327. code.appendLeft(this.end, ';');
  12328. }
  12329. }
  12330. else {
  12331. this.renderReplacedDeclarations(code, options);
  12332. }
  12333. }
  12334. applyDeoptimizations() { }
  12335. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  12336. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  12337. code.remove(this.end - 1, this.end);
  12338. }
  12339. separatorString += ';';
  12340. if (lastSeparatorPos === null) {
  12341. code.appendLeft(renderedContentEnd, separatorString);
  12342. }
  12343. else {
  12344. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  12345. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  12346. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  12347. actualContentEnd--;
  12348. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  12349. actualContentEnd--;
  12350. }
  12351. }
  12352. if (actualContentEnd === lastSeparatorPos + 1) {
  12353. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  12354. }
  12355. else {
  12356. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  12357. code.remove(actualContentEnd, renderedContentEnd);
  12358. }
  12359. }
  12360. if (systemPatternExports.length > 0) {
  12361. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  12362. }
  12363. }
  12364. renderReplacedDeclarations(code, options) {
  12365. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  12366. let actualContentEnd, renderedContentEnd;
  12367. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  12368. let lastSeparatorPos = renderedContentEnd - 1;
  12369. code.remove(this.start, lastSeparatorPos);
  12370. let isInDeclaration = false;
  12371. let hasRenderedContent = false;
  12372. let separatorString = '', leadingString, nextSeparatorString;
  12373. const aggregatedSystemExports = [];
  12374. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  12375. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  12376. if (!node.included) {
  12377. code.remove(start, end);
  12378. continue;
  12379. }
  12380. node.render(code, options);
  12381. leadingString = '';
  12382. nextSeparatorString = '';
  12383. if (!node.id.included ||
  12384. (node.id instanceof Identifier &&
  12385. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  12386. if (hasRenderedContent) {
  12387. separatorString += ';';
  12388. }
  12389. isInDeclaration = false;
  12390. }
  12391. else {
  12392. if (singleSystemExport && singleSystemExport === node.id.variable) {
  12393. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  12394. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  12395. }
  12396. if (isInDeclaration) {
  12397. separatorString += ',';
  12398. }
  12399. else {
  12400. if (hasRenderedContent) {
  12401. separatorString += ';';
  12402. }
  12403. leadingString += `${this.kind} `;
  12404. isInDeclaration = true;
  12405. }
  12406. }
  12407. if (renderedContentEnd === lastSeparatorPos + 1) {
  12408. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  12409. }
  12410. else {
  12411. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  12412. code.appendLeft(renderedContentEnd, leadingString);
  12413. }
  12414. actualContentEnd = contentEnd;
  12415. renderedContentEnd = end;
  12416. hasRenderedContent = true;
  12417. lastSeparatorPos = separator;
  12418. separatorString = nextSeparatorString;
  12419. }
  12420. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  12421. }
  12422. }
  12423. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  12424. let singleSystemExport = null;
  12425. if (options.format === 'system') {
  12426. for (const { node } of separatedNodes) {
  12427. if (node.id instanceof Identifier &&
  12428. node.init &&
  12429. aggregatedSystemExports.length === 0 &&
  12430. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  12431. singleSystemExport = node.id.variable;
  12432. aggregatedSystemExports.push(singleSystemExport);
  12433. }
  12434. else {
  12435. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  12436. }
  12437. }
  12438. if (aggregatedSystemExports.length > 1) {
  12439. singleSystemExport = null;
  12440. }
  12441. else if (singleSystemExport) {
  12442. aggregatedSystemExports.length = 0;
  12443. }
  12444. }
  12445. return singleSystemExport;
  12446. }
  12447. class WhileStatement extends NodeBase {
  12448. hasEffects(context) {
  12449. if (this.test.hasEffects(context))
  12450. return true;
  12451. return hasLoopBodyEffects(context, this.body);
  12452. }
  12453. include(context, includeChildrenRecursively) {
  12454. this.included = true;
  12455. this.test.include(context, includeChildrenRecursively);
  12456. includeLoopBody(context, this.body, includeChildrenRecursively);
  12457. }
  12458. }
  12459. class YieldExpression extends NodeBase {
  12460. hasEffects(context) {
  12461. if (!this.deoptimized)
  12462. this.applyDeoptimizations();
  12463. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  12464. }
  12465. render(code, options) {
  12466. if (this.argument) {
  12467. this.argument.render(code, options, { preventASI: true });
  12468. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  12469. code.prependLeft(this.start + 5, ' ');
  12470. }
  12471. }
  12472. }
  12473. }
  12474. const nodeConstructors = {
  12475. ArrayExpression,
  12476. ArrayPattern,
  12477. ArrowFunctionExpression,
  12478. AssignmentExpression,
  12479. AssignmentPattern,
  12480. AwaitExpression,
  12481. BinaryExpression,
  12482. BlockStatement,
  12483. BreakStatement,
  12484. CallExpression,
  12485. CatchClause,
  12486. ChainExpression,
  12487. ClassBody,
  12488. ClassDeclaration,
  12489. ClassExpression,
  12490. ConditionalExpression,
  12491. ContinueStatement,
  12492. DoWhileStatement,
  12493. EmptyStatement,
  12494. ExportAllDeclaration,
  12495. ExportDefaultDeclaration,
  12496. ExportNamedDeclaration,
  12497. ExportSpecifier,
  12498. ExpressionStatement,
  12499. ForInStatement,
  12500. ForOfStatement,
  12501. ForStatement,
  12502. FunctionDeclaration,
  12503. FunctionExpression,
  12504. Identifier,
  12505. IfStatement,
  12506. ImportAttribute,
  12507. ImportDeclaration,
  12508. ImportDefaultSpecifier,
  12509. ImportExpression,
  12510. ImportNamespaceSpecifier,
  12511. ImportSpecifier,
  12512. LabeledStatement,
  12513. Literal,
  12514. LogicalExpression,
  12515. MemberExpression,
  12516. MetaProperty,
  12517. MethodDefinition,
  12518. NewExpression,
  12519. ObjectExpression,
  12520. ObjectPattern,
  12521. PrivateIdentifier,
  12522. Program,
  12523. Property,
  12524. PropertyDefinition,
  12525. RestElement,
  12526. ReturnStatement,
  12527. SequenceExpression,
  12528. SpreadElement,
  12529. StaticBlock,
  12530. Super,
  12531. SwitchCase,
  12532. SwitchStatement,
  12533. TaggedTemplateExpression,
  12534. TemplateElement,
  12535. TemplateLiteral,
  12536. ThisExpression,
  12537. ThrowStatement,
  12538. TryStatement,
  12539. UnaryExpression,
  12540. UnknownNode,
  12541. UpdateExpression,
  12542. VariableDeclaration,
  12543. VariableDeclarator,
  12544. WhileStatement,
  12545. YieldExpression
  12546. };
  12547. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  12548. class ExportShimVariable extends Variable {
  12549. constructor(module) {
  12550. super(MISSING_EXPORT_SHIM_VARIABLE);
  12551. this.module = module;
  12552. }
  12553. include() {
  12554. super.include();
  12555. this.module.needsExportShim = true;
  12556. }
  12557. }
  12558. class NamespaceVariable extends Variable {
  12559. constructor(context) {
  12560. super(context.getModuleName());
  12561. this.memberVariables = null;
  12562. this.mergedNamespaces = [];
  12563. this.referencedEarly = false;
  12564. this.references = [];
  12565. this.context = context;
  12566. this.module = context.module;
  12567. }
  12568. addReference(identifier) {
  12569. this.references.push(identifier);
  12570. this.name = identifier.name;
  12571. }
  12572. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12573. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  12574. const key = path[0];
  12575. if (typeof key === 'string') {
  12576. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  12577. }
  12578. else {
  12579. deoptimizeInteraction(interaction);
  12580. }
  12581. }
  12582. }
  12583. deoptimizePath(path) {
  12584. if (path.length > 1) {
  12585. const key = path[0];
  12586. if (typeof key === 'string') {
  12587. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  12588. }
  12589. }
  12590. }
  12591. getLiteralValueAtPath(path) {
  12592. if (path[0] === SymbolToStringTag) {
  12593. return 'Module';
  12594. }
  12595. return UnknownValue;
  12596. }
  12597. getMemberVariables() {
  12598. if (this.memberVariables) {
  12599. return this.memberVariables;
  12600. }
  12601. const memberVariables = Object.create(null);
  12602. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  12603. for (const name of sortedExports) {
  12604. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  12605. const exportedVariable = this.context.traceExport(name);
  12606. if (exportedVariable) {
  12607. memberVariables[name] = exportedVariable;
  12608. }
  12609. }
  12610. }
  12611. return (this.memberVariables = memberVariables);
  12612. }
  12613. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12614. const { type } = interaction;
  12615. if (path.length === 0) {
  12616. // This can only be a call anyway
  12617. return true;
  12618. }
  12619. if (path.length === 1 && type !== INTERACTION_CALLED) {
  12620. return type === INTERACTION_ASSIGNED;
  12621. }
  12622. const key = path[0];
  12623. if (typeof key !== 'string') {
  12624. return true;
  12625. }
  12626. const memberVariable = this.getMemberVariables()[key];
  12627. return (!memberVariable ||
  12628. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  12629. }
  12630. include() {
  12631. this.included = true;
  12632. this.context.includeAllExports();
  12633. }
  12634. prepare(accessedGlobalsByScope) {
  12635. if (this.mergedNamespaces.length > 0) {
  12636. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  12637. }
  12638. }
  12639. renderBlock(options) {
  12640. const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  12641. const memberVariables = this.getMemberVariables();
  12642. const members = Object.entries(memberVariables)
  12643. .filter(([_, variable]) => variable.included)
  12644. .map(([name, variable]) => {
  12645. if (this.referencedEarly || variable.isReassigned || variable === this) {
  12646. return [
  12647. null,
  12648. `get ${name}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  12649. ];
  12650. }
  12651. return [name, variable.getName(getPropertyAccess)];
  12652. });
  12653. members.unshift([null, `__proto__:${_}null`]);
  12654. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  12655. if (this.mergedNamespaces.length > 0) {
  12656. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  12657. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  12658. }
  12659. else {
  12660. // The helper to merge namespaces will also take care of freezing and toStringTag
  12661. if (namespaceToStringTag) {
  12662. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  12663. }
  12664. if (freeze) {
  12665. output = `/*#__PURE__*/Object.freeze(${output})`;
  12666. }
  12667. }
  12668. const name = this.getName(getPropertyAccess);
  12669. output = `${cnst} ${name}${_}=${_}${output};`;
  12670. if (format === 'system' && exportNamesByVariable.has(this)) {
  12671. output += `${n}${getSystemExportStatement([this], options)};`;
  12672. }
  12673. return output;
  12674. }
  12675. renderFirst() {
  12676. return this.referencedEarly;
  12677. }
  12678. setMergedNamespaces(mergedNamespaces) {
  12679. this.mergedNamespaces = mergedNamespaces;
  12680. const moduleExecIndex = this.context.getModuleExecIndex();
  12681. for (const identifier of this.references) {
  12682. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  12683. this.referencedEarly = true;
  12684. break;
  12685. }
  12686. }
  12687. }
  12688. }
  12689. NamespaceVariable.prototype.isNamespace = true;
  12690. class SyntheticNamedExportVariable extends Variable {
  12691. constructor(context, name, syntheticNamespace) {
  12692. super(name);
  12693. this.baseVariable = null;
  12694. this.context = context;
  12695. this.module = context.module;
  12696. this.syntheticNamespace = syntheticNamespace;
  12697. }
  12698. getBaseVariable() {
  12699. if (this.baseVariable)
  12700. return this.baseVariable;
  12701. let baseVariable = this.syntheticNamespace;
  12702. while (baseVariable instanceof ExportDefaultVariable ||
  12703. baseVariable instanceof SyntheticNamedExportVariable) {
  12704. if (baseVariable instanceof ExportDefaultVariable) {
  12705. const original = baseVariable.getOriginalVariable();
  12706. if (original === baseVariable)
  12707. break;
  12708. baseVariable = original;
  12709. }
  12710. if (baseVariable instanceof SyntheticNamedExportVariable) {
  12711. baseVariable = baseVariable.syntheticNamespace;
  12712. }
  12713. }
  12714. return (this.baseVariable = baseVariable);
  12715. }
  12716. getBaseVariableName() {
  12717. return this.syntheticNamespace.getBaseVariableName();
  12718. }
  12719. getName(getPropertyAccess) {
  12720. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  12721. }
  12722. include() {
  12723. this.included = true;
  12724. this.context.includeVariableInModule(this.syntheticNamespace);
  12725. }
  12726. setRenderNames(baseName, name) {
  12727. super.setRenderNames(baseName, name);
  12728. }
  12729. }
  12730. var BuildPhase;
  12731. (function (BuildPhase) {
  12732. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  12733. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  12734. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  12735. })(BuildPhase || (BuildPhase = {}));
  12736. function getId(m) {
  12737. return m.id;
  12738. }
  12739. function getAssertionsFromImportExpression(node) {
  12740. const assertProperty = node.arguments?.[0]?.properties.find((property) => getPropertyKey(property) === 'assert')?.value;
  12741. if (!assertProperty) {
  12742. return EMPTY_OBJECT;
  12743. }
  12744. const assertFields = assertProperty.properties
  12745. .map(property => {
  12746. const key = getPropertyKey(property);
  12747. if (typeof key === 'string' &&
  12748. typeof property.value.value === 'string') {
  12749. return [key, property.value.value];
  12750. }
  12751. return null;
  12752. })
  12753. .filter((property) => !!property);
  12754. if (assertFields.length > 0) {
  12755. return Object.fromEntries(assertFields);
  12756. }
  12757. return EMPTY_OBJECT;
  12758. }
  12759. const getPropertyKey = (property) => {
  12760. const key = property.key;
  12761. return key && (key.name || key.value);
  12762. };
  12763. function getAssertionsFromImportExportDeclaration(assertions) {
  12764. return assertions?.length
  12765. ? Object.fromEntries(assertions.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  12766. : EMPTY_OBJECT;
  12767. }
  12768. function doAssertionsDiffer(assertionA, assertionB) {
  12769. const keysA = Object.keys(assertionA);
  12770. return (keysA.length !== Object.keys(assertionB).length ||
  12771. keysA.some(key => assertionA[key] !== assertionB[key]));
  12772. }
  12773. let timers = new Map();
  12774. function getPersistedLabel(label, level) {
  12775. switch (level) {
  12776. case 1: {
  12777. return `# ${label}`;
  12778. }
  12779. case 2: {
  12780. return `## ${label}`;
  12781. }
  12782. case 3: {
  12783. return label;
  12784. }
  12785. default: {
  12786. return `${' '.repeat(level - 4)}- ${label}`;
  12787. }
  12788. }
  12789. }
  12790. function timeStartImpl(label, level = 3) {
  12791. label = getPersistedLabel(label, level);
  12792. const startMemory = process$1.memoryUsage().heapUsed;
  12793. const startTime = node_perf_hooks.performance.now();
  12794. const timer = timers.get(label);
  12795. if (timer === undefined) {
  12796. timers.set(label, {
  12797. memory: 0,
  12798. startMemory,
  12799. startTime,
  12800. time: 0,
  12801. totalMemory: 0
  12802. });
  12803. }
  12804. else {
  12805. timer.startMemory = startMemory;
  12806. timer.startTime = startTime;
  12807. }
  12808. }
  12809. function timeEndImpl(label, level = 3) {
  12810. label = getPersistedLabel(label, level);
  12811. const timer = timers.get(label);
  12812. if (timer !== undefined) {
  12813. const currentMemory = process$1.memoryUsage().heapUsed;
  12814. timer.memory += currentMemory - timer.startMemory;
  12815. timer.time += node_perf_hooks.performance.now() - timer.startTime;
  12816. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  12817. }
  12818. }
  12819. function getTimings() {
  12820. const newTimings = {};
  12821. for (const [label, { memory, time, totalMemory }] of timers) {
  12822. newTimings[label] = [time, memory, totalMemory];
  12823. }
  12824. return newTimings;
  12825. }
  12826. let timeStart = doNothing;
  12827. let timeEnd = doNothing;
  12828. const TIMED_PLUGIN_HOOKS = [
  12829. 'augmentChunkHash',
  12830. 'buildEnd',
  12831. 'buildStart',
  12832. 'generateBundle',
  12833. 'load',
  12834. 'moduleParsed',
  12835. 'options',
  12836. 'outputOptions',
  12837. 'renderChunk',
  12838. 'renderDynamicImport',
  12839. 'renderStart',
  12840. 'resolveDynamicImport',
  12841. 'resolveFileUrl',
  12842. 'resolveId',
  12843. 'resolveImportMeta',
  12844. 'shouldTransformCachedModule',
  12845. 'transform',
  12846. 'writeBundle'
  12847. ];
  12848. function getPluginWithTimers(plugin, index) {
  12849. for (const hook of TIMED_PLUGIN_HOOKS) {
  12850. if (hook in plugin) {
  12851. let timerLabel = `plugin ${index}`;
  12852. if (plugin.name) {
  12853. timerLabel += ` (${plugin.name})`;
  12854. }
  12855. timerLabel += ` - ${hook}`;
  12856. const handler = function (...parameters) {
  12857. timeStart(timerLabel, 4);
  12858. const result = hookFunction.apply(this, parameters);
  12859. timeEnd(timerLabel, 4);
  12860. return result;
  12861. };
  12862. let hookFunction;
  12863. if (typeof plugin[hook].handler === 'function') {
  12864. hookFunction = plugin[hook].handler;
  12865. plugin[hook].handler = handler;
  12866. }
  12867. else {
  12868. hookFunction = plugin[hook];
  12869. plugin[hook] = handler;
  12870. }
  12871. }
  12872. }
  12873. return plugin;
  12874. }
  12875. function initialiseTimers(inputOptions) {
  12876. if (inputOptions.perf) {
  12877. timers = new Map();
  12878. timeStart = timeStartImpl;
  12879. timeEnd = timeEndImpl;
  12880. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  12881. }
  12882. else {
  12883. timeStart = doNothing;
  12884. timeEnd = doNothing;
  12885. }
  12886. }
  12887. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  12888. baseModule.isExecuted = true;
  12889. const modules = [baseModule];
  12890. const visitedModules = new Set();
  12891. for (const module of modules) {
  12892. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  12893. if (!(dependency instanceof ExternalModule) &&
  12894. !dependency.isExecuted &&
  12895. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  12896. !visitedModules.has(dependency.id)) {
  12897. dependency.isExecuted = true;
  12898. visitedModules.add(dependency.id);
  12899. modules.push(dependency);
  12900. }
  12901. }
  12902. }
  12903. }
  12904. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  12905. identifier: null,
  12906. localName: MISSING_EXPORT_SHIM_VARIABLE
  12907. };
  12908. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  12909. const searchedModules = searchedNamesAndModules.get(name);
  12910. if (searchedModules) {
  12911. if (searchedModules.has(target)) {
  12912. return isExportAllSearch ? [null] : error(errorCircularReexport(name, target.id));
  12913. }
  12914. searchedModules.add(target);
  12915. }
  12916. else {
  12917. searchedNamesAndModules.set(name, new Set([target]));
  12918. }
  12919. return target.getVariableForExportName(name, {
  12920. importerForSideEffects,
  12921. isExportAllSearch,
  12922. searchedNamesAndModules
  12923. });
  12924. }
  12925. function getAndExtendSideEffectModules(variable, module) {
  12926. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  12927. let currentVariable = variable;
  12928. const referencedVariables = new Set([currentVariable]);
  12929. while (true) {
  12930. const importingModule = currentVariable.module;
  12931. currentVariable =
  12932. currentVariable instanceof ExportDefaultVariable
  12933. ? currentVariable.getDirectOriginalVariable()
  12934. : currentVariable instanceof SyntheticNamedExportVariable
  12935. ? currentVariable.syntheticNamespace
  12936. : null;
  12937. if (!currentVariable || referencedVariables.has(currentVariable)) {
  12938. break;
  12939. }
  12940. referencedVariables.add(currentVariable);
  12941. sideEffectModules.add(importingModule);
  12942. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  12943. if (originalSideEffects) {
  12944. for (const module of originalSideEffects) {
  12945. sideEffectModules.add(module);
  12946. }
  12947. }
  12948. }
  12949. return sideEffectModules;
  12950. }
  12951. class Module {
  12952. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, assertions) {
  12953. this.graph = graph;
  12954. this.id = id;
  12955. this.options = options;
  12956. this.alternativeReexportModules = new Map();
  12957. this.chunkFileNames = new Set();
  12958. this.chunkNames = [];
  12959. this.cycles = new Set();
  12960. this.dependencies = new Set();
  12961. this.dynamicDependencies = new Set();
  12962. this.dynamicImporters = [];
  12963. this.dynamicImports = [];
  12964. this.execIndex = Infinity;
  12965. this.implicitlyLoadedAfter = new Set();
  12966. this.implicitlyLoadedBefore = new Set();
  12967. this.importDescriptions = new Map();
  12968. this.importMetas = [];
  12969. this.importedFromNotTreeshaken = false;
  12970. this.importers = [];
  12971. this.includedDynamicImporters = [];
  12972. this.includedImports = new Set();
  12973. this.isExecuted = false;
  12974. this.isUserDefinedEntryPoint = false;
  12975. this.needsExportShim = false;
  12976. this.sideEffectDependenciesByVariable = new Map();
  12977. this.sourcesWithAssertions = new Map();
  12978. this.allExportNames = null;
  12979. this.ast = null;
  12980. this.exportAllModules = [];
  12981. this.exportAllSources = new Set();
  12982. this.exportNamesByVariable = null;
  12983. this.exportShimVariable = new ExportShimVariable(this);
  12984. this.exports = new Map();
  12985. this.namespaceReexportsByName = new Map();
  12986. this.reexportDescriptions = new Map();
  12987. this.relevantDependencies = null;
  12988. this.syntheticExports = new Map();
  12989. this.syntheticNamespace = null;
  12990. this.transformDependencies = [];
  12991. this.transitiveReexports = null;
  12992. this.excludeFromSourcemap = /\0/.test(id);
  12993. this.context = options.moduleContext(id);
  12994. this.preserveSignature = this.options.preserveEntrySignatures;
  12995. // eslint-disable-next-line @typescript-eslint/no-this-alias
  12996. const module = this;
  12997. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAssertions } = this;
  12998. this.info = {
  12999. assertions,
  13000. ast: null,
  13001. code: null,
  13002. get dynamicallyImportedIdResolutions() {
  13003. return dynamicImports
  13004. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  13005. .filter(Boolean);
  13006. },
  13007. get dynamicallyImportedIds() {
  13008. // We cannot use this.dynamicDependencies because this is needed before
  13009. // dynamicDependencies are populated
  13010. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  13011. },
  13012. get dynamicImporters() {
  13013. return dynamicImporters.sort();
  13014. },
  13015. get exportedBindings() {
  13016. const exportBindings = { '.': [...exports.keys()] };
  13017. for (const [name, { source }] of reexportDescriptions) {
  13018. (exportBindings[source] ?? (exportBindings[source] = [])).push(name);
  13019. }
  13020. for (const source of exportAllSources) {
  13021. (exportBindings[source] ?? (exportBindings[source] = [])).push('*');
  13022. }
  13023. return exportBindings;
  13024. },
  13025. get exports() {
  13026. return [
  13027. ...exports.keys(),
  13028. ...reexportDescriptions.keys(),
  13029. ...[...exportAllSources].map(() => '*')
  13030. ];
  13031. },
  13032. get hasDefaultExport() {
  13033. // This information is only valid after parsing
  13034. if (!module.ast) {
  13035. return null;
  13036. }
  13037. return module.exports.has('default') || reexportDescriptions.has('default');
  13038. },
  13039. get hasModuleSideEffects() {
  13040. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options);
  13041. return this.moduleSideEffects;
  13042. },
  13043. id,
  13044. get implicitlyLoadedAfterOneOf() {
  13045. // eslint-disable-next-line unicorn/prefer-spread
  13046. return Array.from(implicitlyLoadedAfter, getId).sort();
  13047. },
  13048. get implicitlyLoadedBefore() {
  13049. // eslint-disable-next-line unicorn/prefer-spread
  13050. return Array.from(implicitlyLoadedBefore, getId).sort();
  13051. },
  13052. get importedIdResolutions() {
  13053. // eslint-disable-next-line unicorn/prefer-spread
  13054. return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]).filter(Boolean);
  13055. },
  13056. get importedIds() {
  13057. // We cannot use this.dependencies because this is needed before
  13058. // dependencies are populated
  13059. // eslint-disable-next-line unicorn/prefer-spread
  13060. return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  13061. },
  13062. get importers() {
  13063. return importers.sort();
  13064. },
  13065. isEntry,
  13066. isExternal: false,
  13067. get isIncluded() {
  13068. if (graph.phase !== BuildPhase.GENERATE) {
  13069. return null;
  13070. }
  13071. return module.isIncluded();
  13072. },
  13073. meta: { ...meta },
  13074. moduleSideEffects,
  13075. syntheticNamedExports
  13076. };
  13077. // Hide the deprecated key so that it only warns when accessed explicitly
  13078. // eslint-disable-next-line unicorn/consistent-destructuring
  13079. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  13080. enumerable: false
  13081. });
  13082. }
  13083. basename() {
  13084. const base = node_path.basename(this.id);
  13085. const extension = node_path.extname(this.id);
  13086. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  13087. }
  13088. bindReferences() {
  13089. this.ast.bind();
  13090. }
  13091. error(properties, pos) {
  13092. this.addLocationToLogProps(properties, pos);
  13093. return error(properties);
  13094. }
  13095. // sum up the length of all ast nodes that are included
  13096. estimateSize() {
  13097. let size = 0;
  13098. for (const node of this.ast.body) {
  13099. if (node.included) {
  13100. size += node.end - node.start;
  13101. }
  13102. }
  13103. return size;
  13104. }
  13105. getAllExportNames() {
  13106. if (this.allExportNames) {
  13107. return this.allExportNames;
  13108. }
  13109. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  13110. for (const module of this.exportAllModules) {
  13111. if (module instanceof ExternalModule) {
  13112. this.allExportNames.add(`*${module.id}`);
  13113. continue;
  13114. }
  13115. for (const name of module.getAllExportNames()) {
  13116. if (name !== 'default')
  13117. this.allExportNames.add(name);
  13118. }
  13119. }
  13120. // We do not count the synthetic namespace as a regular export to hide it
  13121. // from entry signatures and namespace objects
  13122. if (typeof this.info.syntheticNamedExports === 'string') {
  13123. this.allExportNames.delete(this.info.syntheticNamedExports);
  13124. }
  13125. return this.allExportNames;
  13126. }
  13127. getDependenciesToBeIncluded() {
  13128. if (this.relevantDependencies)
  13129. return this.relevantDependencies;
  13130. this.relevantDependencies = new Set();
  13131. const necessaryDependencies = new Set();
  13132. const alwaysCheckedDependencies = new Set();
  13133. const dependencyVariables = new Set(this.includedImports);
  13134. if (this.info.isEntry ||
  13135. this.includedDynamicImporters.length > 0 ||
  13136. this.namespace.included ||
  13137. this.implicitlyLoadedAfter.size > 0) {
  13138. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  13139. const [exportedVariable] = this.getVariableForExportName(exportName);
  13140. if (exportedVariable) {
  13141. dependencyVariables.add(exportedVariable);
  13142. }
  13143. }
  13144. }
  13145. for (let variable of dependencyVariables) {
  13146. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  13147. if (sideEffectDependencies) {
  13148. for (const module of sideEffectDependencies) {
  13149. alwaysCheckedDependencies.add(module);
  13150. }
  13151. }
  13152. if (variable instanceof SyntheticNamedExportVariable) {
  13153. variable = variable.getBaseVariable();
  13154. }
  13155. else if (variable instanceof ExportDefaultVariable) {
  13156. variable = variable.getOriginalVariable();
  13157. }
  13158. necessaryDependencies.add(variable.module);
  13159. }
  13160. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  13161. for (const dependency of this.dependencies) {
  13162. this.relevantDependencies.add(dependency);
  13163. }
  13164. }
  13165. else {
  13166. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  13167. }
  13168. for (const dependency of necessaryDependencies) {
  13169. this.relevantDependencies.add(dependency);
  13170. }
  13171. return this.relevantDependencies;
  13172. }
  13173. getExportNamesByVariable() {
  13174. if (this.exportNamesByVariable) {
  13175. return this.exportNamesByVariable;
  13176. }
  13177. const exportNamesByVariable = new Map();
  13178. for (const exportName of this.getAllExportNames()) {
  13179. let [tracedVariable] = this.getVariableForExportName(exportName);
  13180. if (tracedVariable instanceof ExportDefaultVariable) {
  13181. tracedVariable = tracedVariable.getOriginalVariable();
  13182. }
  13183. if (!tracedVariable ||
  13184. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  13185. continue;
  13186. }
  13187. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  13188. if (existingExportNames) {
  13189. existingExportNames.push(exportName);
  13190. }
  13191. else {
  13192. exportNamesByVariable.set(tracedVariable, [exportName]);
  13193. }
  13194. }
  13195. return (this.exportNamesByVariable = exportNamesByVariable);
  13196. }
  13197. getExports() {
  13198. return [...this.exports.keys()];
  13199. }
  13200. getReexports() {
  13201. if (this.transitiveReexports) {
  13202. return this.transitiveReexports;
  13203. }
  13204. // to avoid infinite recursion when using circular `export * from X`
  13205. this.transitiveReexports = [];
  13206. const reexports = new Set(this.reexportDescriptions.keys());
  13207. for (const module of this.exportAllModules) {
  13208. if (module instanceof ExternalModule) {
  13209. reexports.add(`*${module.id}`);
  13210. }
  13211. else {
  13212. for (const name of [...module.getReexports(), ...module.getExports()]) {
  13213. if (name !== 'default')
  13214. reexports.add(name);
  13215. }
  13216. }
  13217. }
  13218. return (this.transitiveReexports = [...reexports]);
  13219. }
  13220. getRenderedExports() {
  13221. // only direct exports are counted here, not reexports at all
  13222. const renderedExports = [];
  13223. const removedExports = [];
  13224. for (const exportName of this.exports.keys()) {
  13225. const [variable] = this.getVariableForExportName(exportName);
  13226. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  13227. }
  13228. return { removedExports, renderedExports };
  13229. }
  13230. getSyntheticNamespace() {
  13231. if (this.syntheticNamespace === null) {
  13232. this.syntheticNamespace = undefined;
  13233. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  13234. ? this.info.syntheticNamedExports
  13235. : 'default', { onlyExplicit: true });
  13236. }
  13237. if (!this.syntheticNamespace) {
  13238. return error(errorSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  13239. }
  13240. return this.syntheticNamespace;
  13241. }
  13242. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  13243. if (name[0] === '*') {
  13244. if (name.length === 1) {
  13245. // export * from './other'
  13246. return [this.namespace];
  13247. }
  13248. // export * from 'external'
  13249. const module = this.graph.modulesById.get(name.slice(1));
  13250. return module.getVariableForExportName('*');
  13251. }
  13252. // export { foo } from './other'
  13253. const reexportDeclaration = this.reexportDescriptions.get(name);
  13254. if (reexportDeclaration) {
  13255. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  13256. if (!variable) {
  13257. return this.error(errorMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  13258. }
  13259. if (importerForSideEffects) {
  13260. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  13261. if (this.info.moduleSideEffects) {
  13262. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  13263. }
  13264. }
  13265. return [variable];
  13266. }
  13267. const exportDeclaration = this.exports.get(name);
  13268. if (exportDeclaration) {
  13269. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  13270. return [this.exportShimVariable];
  13271. }
  13272. const name = exportDeclaration.localName;
  13273. const variable = this.traceVariable(name, {
  13274. importerForSideEffects,
  13275. searchedNamesAndModules
  13276. });
  13277. if (importerForSideEffects) {
  13278. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  13279. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  13280. }
  13281. return [variable];
  13282. }
  13283. if (onlyExplicit) {
  13284. return [null];
  13285. }
  13286. if (name !== 'default') {
  13287. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  13288. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  13289. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  13290. if (foundNamespaceReexport[0]) {
  13291. return foundNamespaceReexport;
  13292. }
  13293. }
  13294. if (this.info.syntheticNamedExports) {
  13295. return [
  13296. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  13297. ];
  13298. }
  13299. // we don't want to create shims when we are just
  13300. // probing export * modules for exports
  13301. if (!isExportAllSearch && this.options.shimMissingExports) {
  13302. this.shimMissingExport(name);
  13303. return [this.exportShimVariable];
  13304. }
  13305. return [null];
  13306. }
  13307. hasEffects() {
  13308. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  13309. }
  13310. include() {
  13311. const context = createInclusionContext();
  13312. if (this.ast.shouldBeIncluded(context))
  13313. this.ast.include(context, false);
  13314. }
  13315. includeAllExports(includeNamespaceMembers) {
  13316. if (!this.isExecuted) {
  13317. markModuleAndImpureDependenciesAsExecuted(this);
  13318. this.graph.needsTreeshakingPass = true;
  13319. }
  13320. for (const exportName of this.exports.keys()) {
  13321. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  13322. const variable = this.getVariableForExportName(exportName)[0];
  13323. variable.deoptimizePath(UNKNOWN_PATH);
  13324. if (!variable.included) {
  13325. this.includeVariable(variable);
  13326. }
  13327. }
  13328. }
  13329. for (const name of this.getReexports()) {
  13330. const [variable] = this.getVariableForExportName(name);
  13331. if (variable) {
  13332. variable.deoptimizePath(UNKNOWN_PATH);
  13333. if (!variable.included) {
  13334. this.includeVariable(variable);
  13335. }
  13336. if (variable instanceof ExternalVariable) {
  13337. variable.module.reexported = true;
  13338. }
  13339. }
  13340. }
  13341. if (includeNamespaceMembers) {
  13342. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  13343. }
  13344. }
  13345. includeAllInBundle() {
  13346. this.ast.include(createInclusionContext(), true);
  13347. this.includeAllExports(false);
  13348. }
  13349. includeExportsByNames(names) {
  13350. if (!this.isExecuted) {
  13351. markModuleAndImpureDependenciesAsExecuted(this);
  13352. this.graph.needsTreeshakingPass = true;
  13353. }
  13354. let includeNamespaceMembers = false;
  13355. for (const name of names) {
  13356. const variable = this.getVariableForExportName(name)[0];
  13357. if (variable) {
  13358. variable.deoptimizePath(UNKNOWN_PATH);
  13359. if (!variable.included) {
  13360. this.includeVariable(variable);
  13361. }
  13362. }
  13363. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  13364. includeNamespaceMembers = true;
  13365. }
  13366. }
  13367. if (includeNamespaceMembers) {
  13368. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  13369. }
  13370. }
  13371. isIncluded() {
  13372. // Modules where this.ast is missing have been loaded via this.load and are
  13373. // not yet fully processed, hence they cannot be included.
  13374. return (this.ast &&
  13375. (this.ast.included ||
  13376. this.namespace.included ||
  13377. this.importedFromNotTreeshaken ||
  13378. this.exportShimVariable.included));
  13379. }
  13380. linkImports() {
  13381. this.addModulesToImportDescriptions(this.importDescriptions);
  13382. this.addModulesToImportDescriptions(this.reexportDescriptions);
  13383. const externalExportAllModules = [];
  13384. for (const source of this.exportAllSources) {
  13385. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  13386. if (module instanceof ExternalModule) {
  13387. externalExportAllModules.push(module);
  13388. continue;
  13389. }
  13390. this.exportAllModules.push(module);
  13391. }
  13392. this.exportAllModules.push(...externalExportAllModules);
  13393. }
  13394. render(options) {
  13395. const source = this.magicString.clone();
  13396. this.ast.render(source, options);
  13397. source.trim();
  13398. const { usesTopLevelAwait } = this.astContext;
  13399. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  13400. return error(errorInvalidFormatForTopLevelAwait(this.id, options.format));
  13401. }
  13402. return { source, usesTopLevelAwait };
  13403. }
  13404. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  13405. timeStart('generate ast', 3);
  13406. this.info.code = code;
  13407. this.originalCode = originalCode;
  13408. this.originalSourcemap = originalSourcemap;
  13409. this.sourcemapChain = sourcemapChain;
  13410. if (transformFiles) {
  13411. this.transformFiles = transformFiles;
  13412. }
  13413. this.transformDependencies = transformDependencies;
  13414. this.customTransformCache = customTransformCache;
  13415. this.updateOptions(moduleOptions);
  13416. const moduleAst = ast ?? this.tryParse();
  13417. timeEnd('generate ast', 3);
  13418. timeStart('analyze ast', 3);
  13419. this.resolvedIds = resolvedIds ?? Object.create(null);
  13420. // By default, `id` is the file name. Custom resolvers and loaders
  13421. // can change that, but it makes sense to use it for the source file name
  13422. const fileName = this.id;
  13423. this.magicString = new MagicString(code, {
  13424. filename: (this.excludeFromSourcemap ? null : fileName),
  13425. indentExclusionRanges: []
  13426. });
  13427. this.astContext = {
  13428. addDynamicImport: this.addDynamicImport.bind(this),
  13429. addExport: this.addExport.bind(this),
  13430. addImport: this.addImport.bind(this),
  13431. addImportMeta: this.addImportMeta.bind(this),
  13432. code,
  13433. deoptimizationTracker: this.graph.deoptimizationTracker,
  13434. error: this.error.bind(this),
  13435. fileName,
  13436. getExports: this.getExports.bind(this),
  13437. getModuleExecIndex: () => this.execIndex,
  13438. getModuleName: this.basename.bind(this),
  13439. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  13440. getReexports: this.getReexports.bind(this),
  13441. importDescriptions: this.importDescriptions,
  13442. includeAllExports: () => this.includeAllExports(true),
  13443. includeDynamicImport: this.includeDynamicImport.bind(this),
  13444. includeVariableInModule: this.includeVariableInModule.bind(this),
  13445. magicString: this.magicString,
  13446. manualPureFunctions: this.graph.pureFunctions,
  13447. module: this,
  13448. moduleContext: this.context,
  13449. options: this.options,
  13450. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  13451. traceExport: (name) => this.getVariableForExportName(name)[0],
  13452. traceVariable: this.traceVariable.bind(this),
  13453. usesTopLevelAwait: false,
  13454. warn: this.warn.bind(this)
  13455. };
  13456. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  13457. this.namespace = new NamespaceVariable(this.astContext);
  13458. this.ast = new Program(moduleAst, { context: this.astContext, type: 'Module' }, this.scope);
  13459. // Assign AST directly if has existing one as there's no way to drop it from memory.
  13460. // If cache is enabled, also assign directly as otherwise it takes more CPU and memory to re-compute.
  13461. if (ast || this.options.cache !== false) {
  13462. this.info.ast = moduleAst;
  13463. }
  13464. else {
  13465. // Make lazy and apply LRU cache to not hog the memory
  13466. Object.defineProperty(this.info, 'ast', {
  13467. get: () => {
  13468. if (this.graph.astLru.has(fileName)) {
  13469. return this.graph.astLru.get(fileName);
  13470. }
  13471. else {
  13472. const parsedAst = this.tryParse();
  13473. this.graph.astLru.set(fileName, parsedAst);
  13474. return parsedAst;
  13475. }
  13476. }
  13477. });
  13478. }
  13479. timeEnd('analyze ast', 3);
  13480. }
  13481. toJSON() {
  13482. return {
  13483. assertions: this.info.assertions,
  13484. ast: this.info.ast,
  13485. code: this.info.code,
  13486. customTransformCache: this.customTransformCache,
  13487. // eslint-disable-next-line unicorn/prefer-spread
  13488. dependencies: Array.from(this.dependencies, getId),
  13489. id: this.id,
  13490. meta: this.info.meta,
  13491. moduleSideEffects: this.info.moduleSideEffects,
  13492. originalCode: this.originalCode,
  13493. originalSourcemap: this.originalSourcemap,
  13494. resolvedIds: this.resolvedIds,
  13495. sourcemapChain: this.sourcemapChain,
  13496. syntheticNamedExports: this.info.syntheticNamedExports,
  13497. transformDependencies: this.transformDependencies,
  13498. transformFiles: this.transformFiles
  13499. };
  13500. }
  13501. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  13502. const localVariable = this.scope.variables.get(name);
  13503. if (localVariable) {
  13504. return localVariable;
  13505. }
  13506. const importDescription = this.importDescriptions.get(name);
  13507. if (importDescription) {
  13508. const otherModule = importDescription.module;
  13509. if (otherModule instanceof Module && importDescription.name === '*') {
  13510. return otherModule.namespace;
  13511. }
  13512. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  13513. if (!declaration) {
  13514. return this.error(errorMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  13515. }
  13516. return declaration;
  13517. }
  13518. return null;
  13519. }
  13520. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  13521. if (moduleSideEffects != null) {
  13522. this.info.moduleSideEffects = moduleSideEffects;
  13523. }
  13524. if (syntheticNamedExports != null) {
  13525. this.info.syntheticNamedExports = syntheticNamedExports;
  13526. }
  13527. if (meta != null) {
  13528. Object.assign(this.info.meta, meta);
  13529. }
  13530. }
  13531. warn(properties, pos) {
  13532. this.addLocationToLogProps(properties, pos);
  13533. this.options.onwarn(properties);
  13534. }
  13535. addDynamicImport(node) {
  13536. let argument = node.source;
  13537. if (argument instanceof TemplateLiteral) {
  13538. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  13539. argument = argument.quasis[0].value.cooked;
  13540. }
  13541. }
  13542. else if (argument instanceof Literal && typeof argument.value === 'string') {
  13543. argument = argument.value;
  13544. }
  13545. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  13546. }
  13547. addExport(node) {
  13548. if (node instanceof ExportDefaultDeclaration) {
  13549. // export default foo;
  13550. this.exports.set('default', {
  13551. identifier: node.variable.getAssignedVariableName(),
  13552. localName: 'default'
  13553. });
  13554. }
  13555. else if (node instanceof ExportAllDeclaration) {
  13556. const source = node.source.value;
  13557. this.addSource(source, node);
  13558. if (node.exported) {
  13559. // export * as name from './other'
  13560. const name = node.exported.name;
  13561. this.reexportDescriptions.set(name, {
  13562. localName: '*',
  13563. module: null,
  13564. source,
  13565. start: node.start
  13566. });
  13567. }
  13568. else {
  13569. // export * from './other'
  13570. this.exportAllSources.add(source);
  13571. }
  13572. }
  13573. else if (node.source instanceof Literal) {
  13574. // export { name } from './other'
  13575. const source = node.source.value;
  13576. this.addSource(source, node);
  13577. for (const { exported, local, start } of node.specifiers) {
  13578. const name = exported instanceof Literal ? exported.value : exported.name;
  13579. this.reexportDescriptions.set(name, {
  13580. localName: local instanceof Literal ? local.value : local.name,
  13581. module: null,
  13582. source,
  13583. start
  13584. });
  13585. }
  13586. }
  13587. else if (node.declaration) {
  13588. const declaration = node.declaration;
  13589. if (declaration instanceof VariableDeclaration) {
  13590. // export var { foo, bar } = ...
  13591. // export var foo = 1, bar = 2;
  13592. for (const declarator of declaration.declarations) {
  13593. for (const localName of extractAssignedNames(declarator.id)) {
  13594. this.exports.set(localName, { identifier: null, localName });
  13595. }
  13596. }
  13597. }
  13598. else {
  13599. // export function foo () {}
  13600. const localName = declaration.id.name;
  13601. this.exports.set(localName, { identifier: null, localName });
  13602. }
  13603. }
  13604. else {
  13605. // export { foo, bar, baz }
  13606. for (const { local, exported } of node.specifiers) {
  13607. // except for reexports, local must be an Identifier
  13608. const localName = local.name;
  13609. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  13610. this.exports.set(exportedName, { identifier: null, localName });
  13611. }
  13612. }
  13613. }
  13614. addImport(node) {
  13615. const source = node.source.value;
  13616. this.addSource(source, node);
  13617. for (const specifier of node.specifiers) {
  13618. const name = specifier instanceof ImportDefaultSpecifier
  13619. ? 'default'
  13620. : specifier instanceof ImportNamespaceSpecifier
  13621. ? '*'
  13622. : specifier.imported instanceof Identifier
  13623. ? specifier.imported.name
  13624. : specifier.imported.value;
  13625. this.importDescriptions.set(specifier.local.name, {
  13626. module: null,
  13627. name,
  13628. source,
  13629. start: specifier.start
  13630. });
  13631. }
  13632. }
  13633. addImportMeta(node) {
  13634. this.importMetas.push(node);
  13635. }
  13636. addLocationToLogProps(properties, pos) {
  13637. properties.id = this.id;
  13638. properties.pos = pos;
  13639. let code = this.info.code;
  13640. const location = locate(code, pos, { offsetLine: 1 });
  13641. if (location) {
  13642. let { column, line } = location;
  13643. try {
  13644. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  13645. code = this.originalCode;
  13646. }
  13647. catch (error_) {
  13648. this.options.onwarn(errorInvalidSourcemapForError(error_, this.id, column, line, pos));
  13649. }
  13650. augmentCodeLocation(properties, { column, line }, code, this.id);
  13651. }
  13652. }
  13653. addModulesToImportDescriptions(importDescription) {
  13654. for (const specifier of importDescription.values()) {
  13655. const { id } = this.resolvedIds[specifier.source];
  13656. specifier.module = this.graph.modulesById.get(id);
  13657. }
  13658. }
  13659. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  13660. const handledDependencies = new Set();
  13661. const addSideEffectDependencies = (possibleDependencies) => {
  13662. for (const dependency of possibleDependencies) {
  13663. if (handledDependencies.has(dependency)) {
  13664. continue;
  13665. }
  13666. handledDependencies.add(dependency);
  13667. if (necessaryDependencies.has(dependency)) {
  13668. relevantDependencies.add(dependency);
  13669. continue;
  13670. }
  13671. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  13672. continue;
  13673. }
  13674. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  13675. relevantDependencies.add(dependency);
  13676. continue;
  13677. }
  13678. addSideEffectDependencies(dependency.dependencies);
  13679. }
  13680. };
  13681. addSideEffectDependencies(this.dependencies);
  13682. addSideEffectDependencies(alwaysCheckedDependencies);
  13683. }
  13684. addSource(source, declaration) {
  13685. const parsedAssertions = getAssertionsFromImportExportDeclaration(declaration.assertions);
  13686. const existingAssertions = this.sourcesWithAssertions.get(source);
  13687. if (existingAssertions) {
  13688. if (doAssertionsDiffer(existingAssertions, parsedAssertions)) {
  13689. this.warn(errorInconsistentImportAssertions(existingAssertions, parsedAssertions, source, this.id), declaration.start);
  13690. }
  13691. }
  13692. else {
  13693. this.sourcesWithAssertions.set(source, parsedAssertions);
  13694. }
  13695. }
  13696. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  13697. let foundSyntheticDeclaration = null;
  13698. const foundInternalDeclarations = new Map();
  13699. const foundExternalDeclarations = new Set();
  13700. for (const module of this.exportAllModules) {
  13701. // Synthetic namespaces should not hide "regular" exports of the same name
  13702. if (module.info.syntheticNamedExports === name) {
  13703. continue;
  13704. }
  13705. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  13706. // We are creating a copy to handle the case where the same binding is
  13707. // imported through different namespace reexports gracefully
  13708. copyNameToModulesMap(searchedNamesAndModules));
  13709. if (module instanceof ExternalModule || indirectExternal) {
  13710. foundExternalDeclarations.add(variable);
  13711. }
  13712. else if (variable instanceof SyntheticNamedExportVariable) {
  13713. if (!foundSyntheticDeclaration) {
  13714. foundSyntheticDeclaration = variable;
  13715. }
  13716. }
  13717. else if (variable) {
  13718. foundInternalDeclarations.set(variable, module);
  13719. }
  13720. }
  13721. if (foundInternalDeclarations.size > 0) {
  13722. const foundDeclarationList = [...foundInternalDeclarations];
  13723. const usedDeclaration = foundDeclarationList[0][0];
  13724. if (foundDeclarationList.length === 1) {
  13725. return [usedDeclaration];
  13726. }
  13727. this.options.onwarn(errorNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  13728. // TODO we are pretending it was not found while it should behave like "undefined"
  13729. return [null];
  13730. }
  13731. if (foundExternalDeclarations.size > 0) {
  13732. const foundDeclarationList = [...foundExternalDeclarations];
  13733. const usedDeclaration = foundDeclarationList[0];
  13734. if (foundDeclarationList.length > 1) {
  13735. this.options.onwarn(errorAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  13736. }
  13737. return [usedDeclaration, true];
  13738. }
  13739. if (foundSyntheticDeclaration) {
  13740. return [foundSyntheticDeclaration];
  13741. }
  13742. return [null];
  13743. }
  13744. includeAndGetAdditionalMergedNamespaces() {
  13745. const externalNamespaces = new Set();
  13746. const syntheticNamespaces = new Set();
  13747. for (const module of [this, ...this.exportAllModules]) {
  13748. if (module instanceof ExternalModule) {
  13749. const [externalVariable] = module.getVariableForExportName('*');
  13750. externalVariable.include();
  13751. this.includedImports.add(externalVariable);
  13752. externalNamespaces.add(externalVariable);
  13753. }
  13754. else if (module.info.syntheticNamedExports) {
  13755. const syntheticNamespace = module.getSyntheticNamespace();
  13756. syntheticNamespace.include();
  13757. this.includedImports.add(syntheticNamespace);
  13758. syntheticNamespaces.add(syntheticNamespace);
  13759. }
  13760. }
  13761. return [...syntheticNamespaces, ...externalNamespaces];
  13762. }
  13763. includeDynamicImport(node) {
  13764. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  13765. if (resolution instanceof Module) {
  13766. resolution.includedDynamicImporters.push(this);
  13767. const importedNames = this.options.treeshake
  13768. ? node.getDeterministicImportedNames()
  13769. : undefined;
  13770. if (importedNames) {
  13771. resolution.includeExportsByNames(importedNames);
  13772. }
  13773. else {
  13774. resolution.includeAllExports(true);
  13775. }
  13776. }
  13777. }
  13778. includeVariable(variable) {
  13779. if (!variable.included) {
  13780. variable.include();
  13781. this.graph.needsTreeshakingPass = true;
  13782. const variableModule = variable.module;
  13783. if (variableModule instanceof Module) {
  13784. if (!variableModule.isExecuted) {
  13785. markModuleAndImpureDependenciesAsExecuted(variableModule);
  13786. }
  13787. if (variableModule !== this) {
  13788. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  13789. for (const module of sideEffectModules) {
  13790. if (!module.isExecuted) {
  13791. markModuleAndImpureDependenciesAsExecuted(module);
  13792. }
  13793. }
  13794. }
  13795. }
  13796. }
  13797. }
  13798. includeVariableInModule(variable) {
  13799. this.includeVariable(variable);
  13800. const variableModule = variable.module;
  13801. if (variableModule && variableModule !== this) {
  13802. this.includedImports.add(variable);
  13803. }
  13804. }
  13805. shimMissingExport(name) {
  13806. this.options.onwarn(errorShimmedExport(this.id, name));
  13807. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  13808. }
  13809. tryParse() {
  13810. try {
  13811. return this.graph.contextParse(this.info.code);
  13812. }
  13813. catch (error_) {
  13814. return this.error(errorParseError(error_, this.id), error_.pos);
  13815. }
  13816. }
  13817. }
  13818. // if there is a cyclic import in the reexport chain, we should not
  13819. // import from the original module but from the cyclic module to not
  13820. // mess up execution order.
  13821. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  13822. if (variable.module instanceof Module && variable.module !== reexporter) {
  13823. const exporterCycles = variable.module.cycles;
  13824. if (exporterCycles.size > 0) {
  13825. const importerCycles = reexporter.cycles;
  13826. for (const cycleSymbol of importerCycles) {
  13827. if (exporterCycles.has(cycleSymbol)) {
  13828. importer.alternativeReexportModules.set(variable, reexporter);
  13829. break;
  13830. }
  13831. }
  13832. }
  13833. }
  13834. }
  13835. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  13836. // eslint-disable-next-line unicorn/prefer-spread
  13837. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  13838. function removeJsExtension(name) {
  13839. return name.endsWith('.js') ? name.slice(0, -3) : name;
  13840. }
  13841. function getCompleteAmdId(options, chunkId) {
  13842. if (options.autoId) {
  13843. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  13844. }
  13845. return options.id ?? '';
  13846. }
  13847. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
  13848. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  13849. if (!namedExportsMode) {
  13850. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  13851. }
  13852. let exportBlock = '';
  13853. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13854. if (reexports && namedExportsMode) {
  13855. for (const specifier of reexports) {
  13856. if (specifier.reexported !== '*') {
  13857. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  13858. if (exportBlock)
  13859. exportBlock += n;
  13860. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  13861. const [left, right] = getDirectReturnFunction([], {
  13862. functionReturn: true,
  13863. lineBreakIndent: null,
  13864. name: null
  13865. });
  13866. exportBlock +=
  13867. `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  13868. `${t}enumerable:${_}true,${n}` +
  13869. `${t}get:${_}${left}${importName}${right}${n}});`;
  13870. }
  13871. else {
  13872. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  13873. }
  13874. }
  13875. }
  13876. }
  13877. }
  13878. for (const { exported, local } of exports) {
  13879. const lhs = `exports${getPropertyAccess(exported)}`;
  13880. const rhs = local;
  13881. if (lhs !== rhs) {
  13882. if (exportBlock)
  13883. exportBlock += n;
  13884. exportBlock += `${lhs}${_}=${_}${rhs};`;
  13885. }
  13886. }
  13887. for (const { name, reexports } of dependencies) {
  13888. if (reexports && namedExportsMode) {
  13889. for (const specifier of reexports) {
  13890. if (specifier.reexported === '*') {
  13891. if (exportBlock)
  13892. exportBlock += n;
  13893. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  13894. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  13895. isAsync: false,
  13896. name: null
  13897. })}${copyPropertyIfNecessary});`;
  13898. }
  13899. }
  13900. }
  13901. }
  13902. if (exportBlock) {
  13903. return `${n}${n}${exportBlock}`;
  13904. }
  13905. return '';
  13906. }
  13907. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  13908. if (exports.length > 0) {
  13909. return exports[0].local;
  13910. }
  13911. else {
  13912. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13913. if (reexports) {
  13914. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  13915. }
  13916. }
  13917. }
  13918. }
  13919. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  13920. if (imported === 'default') {
  13921. if (!isChunk) {
  13922. const moduleInterop = interop(moduleId);
  13923. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  13924. ? defaultVariableName
  13925. : moduleVariableName;
  13926. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  13927. ? `${variableName}${getPropertyAccess('default')}`
  13928. : variableName;
  13929. }
  13930. return depNamedExportsMode
  13931. ? `${moduleVariableName}${getPropertyAccess('default')}`
  13932. : moduleVariableName;
  13933. }
  13934. if (imported === '*') {
  13935. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  13936. ? namespaceVariableName
  13937. : moduleVariableName;
  13938. }
  13939. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  13940. }
  13941. function getEsModuleValue(getObject) {
  13942. return getObject([['value', 'true']], {
  13943. lineBreakIndent: null
  13944. });
  13945. }
  13946. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  13947. if (hasNamedExports) {
  13948. if (addEsModule) {
  13949. if (addNamespaceToStringTag) {
  13950. return `Object.defineProperties(exports,${_}${getObject([
  13951. ['__esModule', getEsModuleValue(getObject)],
  13952. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  13953. ], {
  13954. lineBreakIndent: null
  13955. })});`;
  13956. }
  13957. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  13958. }
  13959. if (addNamespaceToStringTag) {
  13960. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  13961. }
  13962. }
  13963. return '';
  13964. }
  13965. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  13966. if (needsLiveBinding) {
  13967. const [left, right] = getDirectReturnFunction([], {
  13968. functionReturn: true,
  13969. lineBreakIndent: null,
  13970. name: null
  13971. });
  13972. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  13973. `${t}${t}enumerable:${_}true,${n}` +
  13974. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  13975. }
  13976. return `exports[k]${_}=${_}${name}[k]`;
  13977. };
  13978. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
  13979. const { _, cnst, n } = snippets;
  13980. const neededInteropHelpers = new Set();
  13981. const interopStatements = [];
  13982. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  13983. neededInteropHelpers.add(helper);
  13984. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  13985. };
  13986. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13987. if (isChunk) {
  13988. for (const { imported, reexported } of [
  13989. ...(imports || []),
  13990. ...(reexports || [])
  13991. ]) {
  13992. if (imported === '*' && reexported !== '*') {
  13993. if (!namedExportsMode) {
  13994. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  13995. }
  13996. break;
  13997. }
  13998. }
  13999. }
  14000. else {
  14001. const moduleInterop = interop(importPath);
  14002. let hasDefault = false;
  14003. let hasNamespace = false;
  14004. for (const { imported, reexported } of [
  14005. ...(imports || []),
  14006. ...(reexports || [])
  14007. ]) {
  14008. let helper;
  14009. let variableName;
  14010. if (imported === 'default') {
  14011. if (!hasDefault) {
  14012. hasDefault = true;
  14013. if (defaultVariableName !== namespaceVariableName) {
  14014. variableName = defaultVariableName;
  14015. helper = defaultInteropHelpersByInteropType[moduleInterop];
  14016. }
  14017. }
  14018. }
  14019. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  14020. hasNamespace = true;
  14021. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  14022. variableName = namespaceVariableName;
  14023. }
  14024. if (helper) {
  14025. addInteropStatement(variableName, helper, name);
  14026. }
  14027. }
  14028. }
  14029. }
  14030. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  14031. }
  14032. function addJsExtension(name) {
  14033. return name.endsWith('.js') ? name : name + '.js';
  14034. }
  14035. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  14036. // The assumption is that this makes sense for all relative ids:
  14037. // https://requirejs.org/docs/api.html#jsfiles
  14038. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  14039. if (id[0] !== '.') {
  14040. return id;
  14041. }
  14042. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  14043. }
  14044. const require$$0 = [
  14045. "assert",
  14046. "async_hooks",
  14047. "buffer",
  14048. "child_process",
  14049. "cluster",
  14050. "console",
  14051. "constants",
  14052. "crypto",
  14053. "dgram",
  14054. "diagnostics_channel",
  14055. "dns",
  14056. "domain",
  14057. "events",
  14058. "fs",
  14059. "http",
  14060. "http2",
  14061. "https",
  14062. "inspector",
  14063. "module",
  14064. "net",
  14065. "os",
  14066. "path",
  14067. "perf_hooks",
  14068. "process",
  14069. "punycode",
  14070. "querystring",
  14071. "readline",
  14072. "repl",
  14073. "stream",
  14074. "string_decoder",
  14075. "timers",
  14076. "tls",
  14077. "trace_events",
  14078. "tty",
  14079. "url",
  14080. "util",
  14081. "v8",
  14082. "vm",
  14083. "wasi",
  14084. "worker_threads",
  14085. "zlib"
  14086. ];
  14087. var _static = require$$0;
  14088. const builtinModules = /*@__PURE__*/getDefaultExportFromCjs(_static);
  14089. const nodeBuiltins = new Set([
  14090. ...builtinModules,
  14091. // TODO
  14092. // remove once builtin-modules includes PR: https://github.com/sindresorhus/builtin-modules/pull/17
  14093. 'assert/strict',
  14094. 'dns/promises',
  14095. 'fs/promises',
  14096. 'path/posix',
  14097. 'path/win32',
  14098. 'readline/promises',
  14099. 'stream/consumers',
  14100. 'stream/promises',
  14101. 'stream/web',
  14102. 'timers/promises',
  14103. 'util/types'
  14104. ]);
  14105. function warnOnBuiltins(warn, dependencies) {
  14106. const externalBuiltins = dependencies
  14107. .map(({ importPath }) => importPath)
  14108. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  14109. if (externalBuiltins.length === 0)
  14110. return;
  14111. warn(errorMissingNodeBuiltins(externalBuiltins));
  14112. }
  14113. 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 }) {
  14114. warnOnBuiltins(onwarn, dependencies);
  14115. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  14116. const parameters = dependencies.map(m => m.name);
  14117. const { n, getNonArrowFunctionIntro, _ } = snippets;
  14118. if (namedExportsMode && hasExports) {
  14119. parameters.unshift(`exports`);
  14120. deps.unshift(`'exports'`);
  14121. }
  14122. if (accessedGlobals.has('require')) {
  14123. parameters.unshift('require');
  14124. deps.unshift(`'require'`);
  14125. }
  14126. if (accessedGlobals.has('module')) {
  14127. parameters.unshift('module');
  14128. deps.unshift(`'module'`);
  14129. }
  14130. const completeAmdId = getCompleteAmdId(amd, id);
  14131. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  14132. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  14133. const useStrict = strict ? `${_}'use strict';` : '';
  14134. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  14135. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  14136. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets);
  14137. if (namespaceMarkers) {
  14138. namespaceMarkers = n + n + namespaceMarkers;
  14139. }
  14140. magicString
  14141. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  14142. .indent(t)
  14143. // factory function should be wrapped by parentheses to avoid lazy parsing,
  14144. // cf. https://v8.dev/blog/preparser#pife
  14145. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  14146. isAsync: false,
  14147. name: null
  14148. })}{${useStrict}${n}${n}`)
  14149. .append(`${n}${n}}));`);
  14150. }
  14151. function cjs(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  14152. const { _, n } = snippets;
  14153. const useStrict = strict ? `'use strict';${n}${n}` : '';
  14154. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets);
  14155. if (namespaceMarkers) {
  14156. namespaceMarkers += n + n;
  14157. }
  14158. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  14159. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  14160. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  14161. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
  14162. magicString.append(`${exportBlock}${outro}`);
  14163. }
  14164. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  14165. let importBlock = '';
  14166. let definingVariable = false;
  14167. for (const { importPath, name, reexports, imports } of dependencies) {
  14168. if (!reexports && !imports) {
  14169. if (importBlock) {
  14170. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  14171. }
  14172. definingVariable = false;
  14173. importBlock += `require('${importPath}')`;
  14174. }
  14175. else {
  14176. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  14177. definingVariable = true;
  14178. importBlock += `${name}${_}=${_}require('${importPath}')`;
  14179. }
  14180. }
  14181. if (importBlock) {
  14182. return `${importBlock};${n}${n}`;
  14183. }
  14184. return '';
  14185. }
  14186. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
  14187. const { n } = snippets;
  14188. const importBlock = getImportBlock(dependencies, snippets);
  14189. if (importBlock.length > 0)
  14190. intro += importBlock.join(n) + n + n;
  14191. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
  14192. if (intro)
  14193. magicString.prepend(intro);
  14194. const exportBlock = getExportBlock(exports, snippets);
  14195. if (exportBlock.length > 0)
  14196. magicString.append(n + n + exportBlock.join(n).trim());
  14197. if (outro)
  14198. magicString.append(outro);
  14199. magicString.trim();
  14200. }
  14201. function getImportBlock(dependencies, { _ }) {
  14202. const importBlock = [];
  14203. for (const { importPath, reexports, imports, name, assertions } of dependencies) {
  14204. const assertion = assertions ? `${_}assert${_}${assertions}` : '';
  14205. const pathWithAssertion = `'${importPath}'${assertion};`;
  14206. if (!reexports && !imports) {
  14207. importBlock.push(`import${_}${pathWithAssertion}`);
  14208. continue;
  14209. }
  14210. if (imports) {
  14211. let defaultImport = null;
  14212. let starImport = null;
  14213. const importedNames = [];
  14214. for (const specifier of imports) {
  14215. if (specifier.imported === 'default') {
  14216. defaultImport = specifier;
  14217. }
  14218. else if (specifier.imported === '*') {
  14219. starImport = specifier;
  14220. }
  14221. else {
  14222. importedNames.push(specifier);
  14223. }
  14224. }
  14225. if (starImport) {
  14226. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  14227. }
  14228. if (defaultImport && importedNames.length === 0) {
  14229. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  14230. }
  14231. else if (importedNames.length > 0) {
  14232. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  14233. .map(specifier => specifier.imported === specifier.local
  14234. ? specifier.imported
  14235. : `${specifier.imported} as ${specifier.local}`)
  14236. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  14237. }
  14238. }
  14239. if (reexports) {
  14240. let starExport = null;
  14241. const namespaceReexports = [];
  14242. const namedReexports = [];
  14243. for (const specifier of reexports) {
  14244. if (specifier.reexported === '*') {
  14245. starExport = specifier;
  14246. }
  14247. else if (specifier.imported === '*') {
  14248. namespaceReexports.push(specifier);
  14249. }
  14250. else {
  14251. namedReexports.push(specifier);
  14252. }
  14253. }
  14254. if (starExport) {
  14255. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  14256. }
  14257. if (namespaceReexports.length > 0) {
  14258. if (!imports ||
  14259. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  14260. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  14261. }
  14262. for (const specifier of namespaceReexports) {
  14263. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  14264. }
  14265. }
  14266. if (namedReexports.length > 0) {
  14267. importBlock.push(`export${_}{${_}${namedReexports
  14268. .map(specifier => specifier.imported === specifier.reexported
  14269. ? specifier.imported
  14270. : `${specifier.imported} as ${specifier.reexported}`)
  14271. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  14272. }
  14273. }
  14274. }
  14275. return importBlock;
  14276. }
  14277. function getExportBlock(exports, { _, cnst }) {
  14278. const exportBlock = [];
  14279. const exportDeclaration = [];
  14280. for (const specifier of exports) {
  14281. if (specifier.expression) {
  14282. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  14283. }
  14284. exportDeclaration.push(specifier.exported === specifier.local
  14285. ? specifier.local
  14286. : `${specifier.local} as ${specifier.exported}`);
  14287. }
  14288. if (exportDeclaration.length > 0) {
  14289. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  14290. }
  14291. return exportBlock;
  14292. }
  14293. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  14294. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
  14295. const parts = name.split('.');
  14296. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  14297. parts.pop();
  14298. let propertyPath = root;
  14299. return (parts
  14300. .map(part => {
  14301. propertyPath += getPropertyAccess(part);
  14302. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  14303. })
  14304. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  14305. }
  14306. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
  14307. const parts = deepName.split('.');
  14308. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  14309. const last = parts.pop();
  14310. let propertyPath = root;
  14311. let deepAssignment = [
  14312. ...parts.map(part => {
  14313. propertyPath += getPropertyAccess(part);
  14314. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  14315. }),
  14316. `${propertyPath}${getPropertyAccess(last)}`
  14317. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  14318. if (parts.length > 0) {
  14319. deepAssignment = `(${deepAssignment})`;
  14320. }
  14321. return deepAssignment;
  14322. }
  14323. function trimEmptyImports(dependencies) {
  14324. let index = dependencies.length;
  14325. while (index--) {
  14326. const { imports, reexports } = dependencies[index];
  14327. if (imports || reexports) {
  14328. return dependencies.slice(0, index + 1);
  14329. }
  14330. }
  14331. return [];
  14332. }
  14333. 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 }) {
  14334. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  14335. const isNamespaced = name && name.includes('.');
  14336. const useVariableAssignment = !extend && !isNamespaced;
  14337. if (name && useVariableAssignment && !isLegal(name)) {
  14338. return error(errorIllegalIdentifierAsName(name));
  14339. }
  14340. warnOnBuiltins(onwarn, dependencies);
  14341. const external = trimEmptyImports(dependencies);
  14342. const deps = external.map(dep => dep.globalName || 'null');
  14343. const parameters = external.map(m => m.name);
  14344. if (hasExports && !name) {
  14345. onwarn(errorMissingNameOptionForIifeExport());
  14346. }
  14347. if (namedExportsMode && hasExports) {
  14348. if (extend) {
  14349. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  14350. parameters.unshift('exports');
  14351. }
  14352. else {
  14353. deps.unshift('{}');
  14354. parameters.unshift('exports');
  14355. }
  14356. }
  14357. const useStrict = strict ? `${t}'use strict';${n}` : '';
  14358. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  14359. magicString.prepend(`${intro}${interopBlock}`);
  14360. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  14361. isAsync: false,
  14362. name: null
  14363. })}{${n}${useStrict}${n}`;
  14364. if (hasExports) {
  14365. if (name && !(extend && namedExportsMode)) {
  14366. wrapperIntro =
  14367. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  14368. `${_}=${_}${wrapperIntro}`;
  14369. }
  14370. if (isNamespaced) {
  14371. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
  14372. }
  14373. }
  14374. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  14375. if (hasExports && !extend && namedExportsMode) {
  14376. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  14377. }
  14378. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  14379. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets);
  14380. if (namespaceMarkers) {
  14381. namespaceMarkers = n + n + namespaceMarkers;
  14382. }
  14383. magicString
  14384. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  14385. .indent(t)
  14386. .prepend(wrapperIntro)
  14387. .append(wrapperOutro);
  14388. }
  14389. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
  14390. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  14391. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  14392. const registeredName = name ? `'${name}',${_}` : '';
  14393. const wrapperParameters = accessedGlobals.has('module')
  14394. ? ['exports', 'module']
  14395. : hasExports
  14396. ? ['exports']
  14397. : [];
  14398. // factory function should be wrapped by parentheses to avoid lazy parsing,
  14399. // cf. https://v8.dev/blog/preparser#pife
  14400. let wrapperStart = `System.register(${registeredName}[` +
  14401. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  14402. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  14403. isAsync: false,
  14404. name: null
  14405. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  14406. getStarExcludesBlock(starExcludes, t, snippets) +
  14407. getImportBindingsBlock(importBindings, t, snippets) +
  14408. `${n}${t}return${_}{${setters.length > 0
  14409. ? `${n}${t}${t}setters:${_}[${setters
  14410. .map(setter => setter
  14411. ? `${getFunctionIntro(['module'], {
  14412. isAsync: false,
  14413. name: null
  14414. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  14415. : systemNullSetters
  14416. ? `null`
  14417. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  14418. .join(`,${_}`)}],`
  14419. : ''}${n}`;
  14420. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  14421. isAsync: usesTopLevelAwait,
  14422. name: null
  14423. })}{${n}${n}`;
  14424. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  14425. magicString
  14426. .prepend(intro +
  14427. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
  14428. getHoistedExportsBlock(exports, t, snippets))
  14429. .append(`${outro}${n}${n}` +
  14430. getSyntheticExportsBlock(exports, t, snippets) +
  14431. getMissingExportsBlock(exports, t, snippets))
  14432. .indent(`${t}${t}${t}`)
  14433. .append(wrapperEnd)
  14434. .prepend(wrapperStart);
  14435. }
  14436. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  14437. const importBindings = [];
  14438. const setters = [];
  14439. let starExcludes = null;
  14440. for (const { imports, reexports } of dependencies) {
  14441. const setter = [];
  14442. if (imports) {
  14443. for (const specifier of imports) {
  14444. importBindings.push(specifier.local);
  14445. if (specifier.imported === '*') {
  14446. setter.push(`${specifier.local}${_}=${_}module;`);
  14447. }
  14448. else {
  14449. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  14450. }
  14451. }
  14452. }
  14453. if (reexports) {
  14454. const reexportedNames = [];
  14455. let hasStarReexport = false;
  14456. for (const { imported, reexported } of reexports) {
  14457. if (reexported === '*') {
  14458. hasStarReexport = true;
  14459. }
  14460. else {
  14461. reexportedNames.push([
  14462. reexported,
  14463. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  14464. ]);
  14465. }
  14466. }
  14467. if (reexportedNames.length > 1 || hasStarReexport) {
  14468. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  14469. if (hasStarReexport) {
  14470. if (!starExcludes) {
  14471. starExcludes = getStarExcludes({ dependencies, exports });
  14472. }
  14473. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  14474. }
  14475. else {
  14476. setter.push(`exports(${exportMapping});`);
  14477. }
  14478. }
  14479. else {
  14480. const [key, value] = reexportedNames[0];
  14481. setter.push(`exports('${key}',${_}${value});`);
  14482. }
  14483. }
  14484. setters.push(setter.join(`${n}${t}${t}${t}`));
  14485. }
  14486. return { importBindings, setters, starExcludes };
  14487. }
  14488. const getStarExcludes = ({ dependencies, exports }) => {
  14489. const starExcludes = new Set(exports.map(expt => expt.exported));
  14490. starExcludes.add('default');
  14491. for (const { reexports } of dependencies) {
  14492. if (reexports) {
  14493. for (const reexport of reexports) {
  14494. if (reexport.reexported !== '*')
  14495. starExcludes.add(reexport.reexported);
  14496. }
  14497. }
  14498. }
  14499. return starExcludes;
  14500. };
  14501. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
  14502. ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(property => [property, '1']), { lineBreakIndent: { base: t, t } })};`
  14503. : '';
  14504. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  14505. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  14506. function getExportsBlock(exports, t, { _, n }) {
  14507. if (exports.length === 0) {
  14508. return '';
  14509. }
  14510. if (exports.length === 1) {
  14511. return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  14512. }
  14513. return (`exports({${n}` +
  14514. exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
  14515. `${n}});${n}${n}`);
  14516. }
  14517. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  14518. .filter(expt => expt.expression)
  14519. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  14520. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  14521. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  14522. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  14523. function globalProperty(name, globalVariable, getPropertyAccess) {
  14524. if (!name)
  14525. return 'null';
  14526. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  14527. }
  14528. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  14529. let propertyPath = globalVariable;
  14530. return name
  14531. .split('.')
  14532. .map(part => (propertyPath += getPropertyAccess(part)))
  14533. .join(`${_}&&${_}`);
  14534. }
  14535. 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 }) {
  14536. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  14537. const factoryVariable = compact ? 'f' : 'factory';
  14538. const globalVariable = compact ? 'g' : 'global';
  14539. if (hasExports && !name) {
  14540. return error(errorMissingNameOptionForUmdExport());
  14541. }
  14542. warnOnBuiltins(onwarn, dependencies);
  14543. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  14544. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  14545. const trimmedImports = trimEmptyImports(dependencies);
  14546. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  14547. const factoryParameters = trimmedImports.map(m => m.name);
  14548. if (namedExportsMode && (hasExports || noConflict)) {
  14549. amdDeps.unshift(`'exports'`);
  14550. cjsDeps.unshift(`exports`);
  14551. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
  14552. factoryParameters.unshift('exports');
  14553. }
  14554. const completeAmdId = getCompleteAmdId(amd, id);
  14555. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  14556. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  14557. const define = amd.define;
  14558. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  14559. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  14560. let iifeExport;
  14561. if (noConflict) {
  14562. const noConflictExportsVariable = compact ? 'e' : 'exports';
  14563. let factory;
  14564. if (!namedExportsMode && hasExports) {
  14565. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets)};`;
  14566. }
  14567. else {
  14568. const module = globalDeps.shift();
  14569. factory =
  14570. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  14571. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  14572. }
  14573. iifeExport =
  14574. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  14575. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  14576. `${t}${t}${factory}${n}` +
  14577. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  14578. isAsync: false,
  14579. name: null
  14580. })}{${_}` +
  14581. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  14582. `${t}})()`;
  14583. }
  14584. else {
  14585. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  14586. if (!namedExportsMode && hasExports) {
  14587. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets);
  14588. }
  14589. }
  14590. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  14591. const wrapperParameters = [factoryVariable];
  14592. if (iifeNeedsGlobal) {
  14593. wrapperParameters.unshift(globalVariable);
  14594. }
  14595. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  14596. const iifeStart = iifeNeedsGlobal
  14597. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  14598. : '';
  14599. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  14600. const cjsIntro = iifeNeedsGlobal
  14601. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  14602. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  14603. : '';
  14604. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  14605. cjsIntro +
  14606. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  14607. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  14608. // factory function should be wrapped by parentheses to avoid lazy parsing,
  14609. // cf. https://v8.dev/blog/preparser#pife
  14610. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  14611. isAsync: false,
  14612. name: null
  14613. })}{${useStrict}${n}`;
  14614. const wrapperOutro = n + n + '}));';
  14615. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  14616. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  14617. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets);
  14618. if (namespaceMarkers) {
  14619. namespaceMarkers = n + n + namespaceMarkers;
  14620. }
  14621. magicString
  14622. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  14623. .trim()
  14624. .indent(t)
  14625. .append(wrapperOutro)
  14626. .prepend(wrapperIntro);
  14627. }
  14628. const finalisers = { amd, cjs, es, iife, system, umd };
  14629. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  14630. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  14631. async function createAddons(options, outputPluginDriver, chunk) {
  14632. try {
  14633. let [banner, footer, intro, outro] = await Promise.all([
  14634. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  14635. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  14636. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  14637. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  14638. ]);
  14639. if (intro)
  14640. intro += '\n\n';
  14641. if (outro)
  14642. outro = `\n\n${outro}`;
  14643. if (banner)
  14644. banner += '\n';
  14645. if (footer)
  14646. footer = '\n' + footer;
  14647. return { banner, footer, intro, outro };
  14648. }
  14649. catch (error_) {
  14650. return error(errorAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  14651. }
  14652. }
  14653. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  14654. amd: deconflictImportsOther,
  14655. cjs: deconflictImportsOther,
  14656. es: deconflictImportsEsmOrSystem,
  14657. iife: deconflictImportsOther,
  14658. system: deconflictImportsEsmOrSystem,
  14659. umd: deconflictImportsOther
  14660. };
  14661. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  14662. const reversedModules = [...modules].reverse();
  14663. for (const module of reversedModules) {
  14664. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  14665. }
  14666. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  14667. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  14668. for (const module of reversedModules) {
  14669. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  14670. }
  14671. }
  14672. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  14673. // This is needed for namespace reexports
  14674. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  14675. if (preserveModules || dependency instanceof ExternalChunk) {
  14676. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  14677. }
  14678. }
  14679. for (const variable of imports) {
  14680. const module = variable.module;
  14681. const name = variable.name;
  14682. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  14683. variable.setRenderNames(null, (module instanceof ExternalModule
  14684. ? externalChunkByModule.get(module)
  14685. : chunkByModule.get(module)).variableName);
  14686. }
  14687. else if (module instanceof ExternalModule && name === 'default') {
  14688. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  14689. ? module.suggestedVariableName + '__default'
  14690. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  14691. }
  14692. else {
  14693. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  14694. }
  14695. }
  14696. for (const variable of syntheticExports) {
  14697. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  14698. }
  14699. }
  14700. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  14701. for (const chunk of dependencies) {
  14702. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  14703. }
  14704. for (const chunk of deconflictedNamespace) {
  14705. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  14706. }
  14707. for (const externalModule of deconflictedDefault) {
  14708. externalModule.defaultVariableName =
  14709. deconflictedNamespace.has(externalModule) &&
  14710. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  14711. ? externalModule.namespaceVariableName
  14712. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  14713. }
  14714. for (const variable of imports) {
  14715. const module = variable.module;
  14716. if (module instanceof ExternalModule) {
  14717. const chunk = externalChunkByModule.get(module);
  14718. const name = variable.name;
  14719. if (name === 'default') {
  14720. const moduleInterop = interop(module.id);
  14721. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  14722. ? chunk.defaultVariableName
  14723. : chunk.variableName;
  14724. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  14725. variable.setRenderNames(variableName, 'default');
  14726. }
  14727. else {
  14728. variable.setRenderNames(null, variableName);
  14729. }
  14730. }
  14731. else if (name === '*') {
  14732. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  14733. ? chunk.namespaceVariableName
  14734. : chunk.variableName);
  14735. }
  14736. else {
  14737. // if the second parameter is `null`, it uses its "name" for the property name
  14738. variable.setRenderNames(chunk.variableName, null);
  14739. }
  14740. }
  14741. else {
  14742. const chunk = chunkByModule.get(module);
  14743. if (preserveModules && variable.isNamespace) {
  14744. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  14745. }
  14746. else if (chunk.exportMode === 'default') {
  14747. variable.setRenderNames(null, chunk.variableName);
  14748. }
  14749. else {
  14750. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  14751. }
  14752. }
  14753. }
  14754. }
  14755. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  14756. for (const module of modules) {
  14757. for (const variable of module.scope.variables.values()) {
  14758. if (variable.included &&
  14759. // this will only happen for exports in some formats
  14760. !(variable.renderBaseName ||
  14761. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  14762. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  14763. }
  14764. }
  14765. if (includedNamespaces.has(module)) {
  14766. const namespace = module.namespace;
  14767. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  14768. }
  14769. }
  14770. }
  14771. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  14772. let nameIndex = 0;
  14773. for (const variable of exports) {
  14774. let [exportName] = variable.name;
  14775. if (exportsByName.has(exportName)) {
  14776. do {
  14777. exportName = toBase64(++nameIndex);
  14778. // skip past leading number identifiers
  14779. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  14780. nameIndex += 9 * 64 ** (exportName.length - 1);
  14781. exportName = toBase64(nameIndex);
  14782. }
  14783. } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
  14784. }
  14785. exportsByName.set(exportName, variable);
  14786. exportNamesByVariable.set(variable, [exportName]);
  14787. }
  14788. }
  14789. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  14790. for (const variable of exports) {
  14791. let nameIndex = 0;
  14792. let exportName = variable.name;
  14793. while (exportsByName.has(exportName)) {
  14794. exportName = variable.name + '$' + ++nameIndex;
  14795. }
  14796. exportsByName.set(exportName, variable);
  14797. exportNamesByVariable.set(variable, [exportName]);
  14798. }
  14799. }
  14800. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, warn) {
  14801. const exportKeys = chunk.getExportNames();
  14802. if (exportMode === 'default') {
  14803. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  14804. return error(errorIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  14805. }
  14806. }
  14807. else if (exportMode === 'none' && exportKeys.length > 0) {
  14808. return error(errorIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  14809. }
  14810. if (exportMode === 'auto') {
  14811. if (exportKeys.length === 0) {
  14812. exportMode = 'none';
  14813. }
  14814. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  14815. exportMode = 'default';
  14816. }
  14817. else {
  14818. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  14819. warn(errorMixedExport(facadeModuleId, name));
  14820. }
  14821. exportMode = 'named';
  14822. }
  14823. }
  14824. return exportMode;
  14825. }
  14826. function guessIndentString(code) {
  14827. const lines = code.split('\n');
  14828. const tabbed = lines.filter(line => /^\t+/.test(line));
  14829. const spaced = lines.filter(line => /^ {2,}/.test(line));
  14830. if (tabbed.length === 0 && spaced.length === 0) {
  14831. return null;
  14832. }
  14833. // More lines tabbed than spaced? Assume tabs, and
  14834. // default to tabs in the case of a tie (or nothing
  14835. // to go on)
  14836. if (tabbed.length >= spaced.length) {
  14837. return '\t';
  14838. }
  14839. // Otherwise, we need to guess the multiple
  14840. const min = spaced.reduce((previous, current) => {
  14841. const numberSpaces = /^ +/.exec(current)[0].length;
  14842. return Math.min(numberSpaces, previous);
  14843. }, Infinity);
  14844. return ' '.repeat(min);
  14845. }
  14846. function getIndentString(modules, options) {
  14847. if (options.indent !== true)
  14848. return options.indent;
  14849. for (const module of modules) {
  14850. const indent = guessIndentString(module.originalCode);
  14851. if (indent !== null)
  14852. return indent;
  14853. }
  14854. return '\t';
  14855. }
  14856. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  14857. const staticDependencyBlocks = [];
  14858. const handledDependencies = new Set();
  14859. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  14860. const module = orderedModules[modulePos];
  14861. if (!handledDependencies.has(module)) {
  14862. const staticDependencies = [];
  14863. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  14864. staticDependencyBlocks.unshift(staticDependencies);
  14865. }
  14866. }
  14867. const dependencies = new Set();
  14868. for (const block of staticDependencyBlocks) {
  14869. for (const dependency of block) {
  14870. dependencies.add(dependency);
  14871. }
  14872. }
  14873. return dependencies;
  14874. }
  14875. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  14876. const dependencies = module.getDependenciesToBeIncluded();
  14877. for (const dependency of dependencies) {
  14878. if (dependency instanceof ExternalModule) {
  14879. staticDependencies.push(externalChunkByModule.get(dependency));
  14880. continue;
  14881. }
  14882. const dependencyChunk = chunkByModule.get(dependency);
  14883. if (dependencyChunk !== chunk) {
  14884. staticDependencies.push(dependencyChunk);
  14885. continue;
  14886. }
  14887. if (!handledModules.has(dependency)) {
  14888. handledModules.add(dependency);
  14889. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  14890. }
  14891. }
  14892. }
  14893. // Four random characters from the private use area to minimize risk of conflicts
  14894. const hashPlaceholderLeft = '!~{';
  14895. const hashPlaceholderRight = '}~';
  14896. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  14897. // This is the size of a sha256
  14898. const maxHashSize = 64;
  14899. const defaultHashSize = 8;
  14900. const getHashPlaceholderGenerator = () => {
  14901. let nextIndex = 0;
  14902. return (optionName, hashSize = defaultHashSize) => {
  14903. if (hashSize > maxHashSize) {
  14904. return error(errorFailedValidation(`Hashes cannot be longer than ${maxHashSize} characters, received ${hashSize}. Check the "${optionName}" option.`));
  14905. }
  14906. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  14907. if (placeholder.length > hashSize) {
  14908. 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.`));
  14909. }
  14910. return placeholder;
  14911. };
  14912. };
  14913. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${maxHashSize - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  14914. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  14915. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  14916. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  14917. const containedPlaceholders = new Set();
  14918. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  14919. if (placeholders.has(placeholder)) {
  14920. containedPlaceholders.add(placeholder);
  14921. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  14922. }
  14923. return placeholder;
  14924. });
  14925. return { containedPlaceholders, transformedCode };
  14926. };
  14927. const lowercaseBundleKeys = Symbol('bundleKeys');
  14928. const FILE_PLACEHOLDER = {
  14929. type: 'placeholder'
  14930. };
  14931. const getOutputBundle = (outputBundleBase) => {
  14932. const reservedLowercaseBundleKeys = new Set();
  14933. return new Proxy(outputBundleBase, {
  14934. deleteProperty(target, key) {
  14935. if (typeof key === 'string') {
  14936. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  14937. }
  14938. return Reflect.deleteProperty(target, key);
  14939. },
  14940. get(target, key) {
  14941. if (key === lowercaseBundleKeys) {
  14942. return reservedLowercaseBundleKeys;
  14943. }
  14944. return Reflect.get(target, key);
  14945. },
  14946. set(target, key, value) {
  14947. if (typeof key === 'string') {
  14948. reservedLowercaseBundleKeys.add(key.toLowerCase());
  14949. }
  14950. return Reflect.set(target, key, value);
  14951. }
  14952. });
  14953. };
  14954. const removeUnreferencedAssets = (outputBundle) => {
  14955. const unreferencedAssets = new Set();
  14956. const bundleEntries = Object.values(outputBundle);
  14957. for (const asset of bundleEntries) {
  14958. asset.type === 'asset' && asset.needsCodeReference && unreferencedAssets.add(asset.fileName);
  14959. }
  14960. for (const chunk of bundleEntries) {
  14961. if (chunk.type === 'chunk') {
  14962. for (const referencedFile of chunk.referencedFiles) {
  14963. unreferencedAssets.has(referencedFile) && unreferencedAssets.delete(referencedFile);
  14964. }
  14965. }
  14966. }
  14967. for (const file of unreferencedAssets) {
  14968. delete outputBundle[file];
  14969. }
  14970. };
  14971. function renderNamePattern(pattern, patternName, replacements) {
  14972. if (isPathFragment(pattern))
  14973. 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.`));
  14974. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  14975. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  14976. return error(errorFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  14977. }
  14978. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  14979. if (isPathFragment(replacement))
  14980. return error(errorFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  14981. return replacement;
  14982. });
  14983. }
  14984. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  14985. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  14986. return name;
  14987. const extension = node_path.extname(name);
  14988. name = name.slice(0, Math.max(0, name.length - extension.length));
  14989. let uniqueName, uniqueIndex = 1;
  14990. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  14991. ;
  14992. return uniqueName;
  14993. }
  14994. const NON_ASSET_EXTENSIONS = new Set([
  14995. '.js',
  14996. '.jsx',
  14997. '.ts',
  14998. '.tsx',
  14999. '.mjs',
  15000. '.mts',
  15001. '.cjs',
  15002. '.cts'
  15003. ]);
  15004. function getGlobalName(chunk, globals, hasExports, warn) {
  15005. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  15006. if (globalName) {
  15007. return globalName;
  15008. }
  15009. if (hasExports) {
  15010. warn(errorMissingGlobalName(chunk.id, chunk.variableName));
  15011. return chunk.variableName;
  15012. }
  15013. }
  15014. class Chunk {
  15015. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  15016. this.orderedModules = orderedModules;
  15017. this.inputOptions = inputOptions;
  15018. this.outputOptions = outputOptions;
  15019. this.unsetOptions = unsetOptions;
  15020. this.pluginDriver = pluginDriver;
  15021. this.modulesById = modulesById;
  15022. this.chunkByModule = chunkByModule;
  15023. this.externalChunkByModule = externalChunkByModule;
  15024. this.facadeChunkByModule = facadeChunkByModule;
  15025. this.includedNamespaces = includedNamespaces;
  15026. this.manualChunkAlias = manualChunkAlias;
  15027. this.getPlaceholder = getPlaceholder;
  15028. this.bundle = bundle;
  15029. this.inputBase = inputBase;
  15030. this.snippets = snippets;
  15031. this.entryModules = [];
  15032. this.exportMode = 'named';
  15033. this.facadeModule = null;
  15034. this.namespaceVariableName = '';
  15035. this.variableName = '';
  15036. this.accessedGlobalsByScope = new Map();
  15037. this.dependencies = new Set();
  15038. this.dynamicEntryModules = [];
  15039. this.dynamicName = null;
  15040. this.exportNamesByVariable = new Map();
  15041. this.exports = new Set();
  15042. this.exportsByName = new Map();
  15043. this.fileName = null;
  15044. this.implicitEntryModules = [];
  15045. this.implicitlyLoadedBefore = new Set();
  15046. this.imports = new Set();
  15047. this.includedDynamicImports = null;
  15048. this.includedReexportsByModule = new Map();
  15049. // This may be updated in the constructor
  15050. this.isEmpty = true;
  15051. this.name = null;
  15052. this.needsExportsShim = false;
  15053. this.preRenderedChunkInfo = null;
  15054. this.preliminaryFileName = null;
  15055. this.renderedChunkInfo = null;
  15056. this.renderedDependencies = null;
  15057. this.renderedModules = Object.create(null);
  15058. this.sortedExportNames = null;
  15059. this.strictFacade = false;
  15060. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  15061. const chunkModules = new Set(orderedModules);
  15062. for (const module of orderedModules) {
  15063. chunkByModule.set(module, this);
  15064. if (module.namespace.included && !outputOptions.preserveModules) {
  15065. includedNamespaces.add(module);
  15066. }
  15067. if (this.isEmpty && module.isIncluded()) {
  15068. this.isEmpty = false;
  15069. }
  15070. if (module.info.isEntry || outputOptions.preserveModules) {
  15071. this.entryModules.push(module);
  15072. }
  15073. for (const importer of module.includedDynamicImporters) {
  15074. if (!chunkModules.has(importer)) {
  15075. this.dynamicEntryModules.push(module);
  15076. // Modules with synthetic exports need an artificial namespace for dynamic imports
  15077. if (module.info.syntheticNamedExports) {
  15078. includedNamespaces.add(module);
  15079. this.exports.add(module.namespace);
  15080. }
  15081. }
  15082. }
  15083. if (module.implicitlyLoadedAfter.size > 0) {
  15084. this.implicitEntryModules.push(module);
  15085. }
  15086. }
  15087. this.suggestedVariableName = makeLegal(this.generateVariableName());
  15088. }
  15089. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  15090. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  15091. chunk.assignFacadeName(facadeName, facadedModule);
  15092. if (!facadeChunkByModule.has(facadedModule)) {
  15093. facadeChunkByModule.set(facadedModule, chunk);
  15094. }
  15095. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  15096. chunk.dependencies.add(dependency instanceof Module
  15097. ? chunkByModule.get(dependency)
  15098. : externalChunkByModule.get(dependency));
  15099. }
  15100. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  15101. facadedModule.info.moduleSideEffects &&
  15102. facadedModule.hasEffects()) {
  15103. chunk.dependencies.add(chunkByModule.get(facadedModule));
  15104. }
  15105. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  15106. chunk.facadeModule = facadedModule;
  15107. chunk.strictFacade = true;
  15108. return chunk;
  15109. }
  15110. canModuleBeFacade(module, exposedVariables) {
  15111. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  15112. // All exports of this chunk need to be exposed by the candidate module
  15113. for (const exposedVariable of this.exports) {
  15114. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  15115. return false;
  15116. }
  15117. }
  15118. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  15119. for (const exposedVariable of exposedVariables) {
  15120. if (!(exposedVariable.module === module ||
  15121. moduleExportNamesByVariable.has(exposedVariable) ||
  15122. (exposedVariable instanceof SyntheticNamedExportVariable &&
  15123. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  15124. return false;
  15125. }
  15126. }
  15127. return true;
  15128. }
  15129. finalizeChunk(code, map, hashesByPlaceholder) {
  15130. const renderedChunkInfo = this.getRenderedChunkInfo();
  15131. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  15132. const fileName = (this.fileName = finalize(renderedChunkInfo.fileName));
  15133. return {
  15134. ...renderedChunkInfo,
  15135. code,
  15136. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  15137. fileName,
  15138. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  15139. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  15140. finalize(fileName),
  15141. bindings
  15142. ])),
  15143. imports: renderedChunkInfo.imports.map(finalize),
  15144. map,
  15145. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize)
  15146. };
  15147. }
  15148. generateExports() {
  15149. this.sortedExportNames = null;
  15150. const remainingExports = new Set(this.exports);
  15151. if (this.facadeModule !== null &&
  15152. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  15153. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  15154. for (const [variable, exportNames] of exportNamesByVariable) {
  15155. this.exportNamesByVariable.set(variable, [...exportNames]);
  15156. for (const exportName of exportNames) {
  15157. this.exportsByName.set(exportName, variable);
  15158. }
  15159. remainingExports.delete(variable);
  15160. }
  15161. }
  15162. if (this.outputOptions.minifyInternalExports) {
  15163. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  15164. }
  15165. else {
  15166. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  15167. }
  15168. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  15169. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onwarn);
  15170. }
  15171. generateFacades() {
  15172. const facades = [];
  15173. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  15174. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  15175. for (const module of entryModules) {
  15176. if (module.preserveSignature) {
  15177. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  15178. // We need to expose all entry exports from this chunk
  15179. if (this.chunkByModule.get(exportedVariable.module) === this) {
  15180. exposedVariables.add(exportedVariable);
  15181. }
  15182. }
  15183. }
  15184. }
  15185. for (const module of entryModules) {
  15186. // eslint-disable-next-line unicorn/prefer-spread
  15187. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  15188. // mapping must run after Set 'name' dedupe
  15189. name => ({
  15190. name
  15191. }));
  15192. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  15193. requiredFacades.push({});
  15194. }
  15195. // eslint-disable-next-line unicorn/prefer-spread
  15196. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  15197. if (requiredFacades.length === 0) {
  15198. requiredFacades.push({});
  15199. }
  15200. if (!this.facadeModule) {
  15201. const needsStrictFacade = !this.outputOptions.preserveModules &&
  15202. (module.preserveSignature === 'strict' ||
  15203. (module.preserveSignature === 'exports-only' &&
  15204. module.getExportNamesByVariable().size > 0));
  15205. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  15206. this.facadeModule = module;
  15207. this.facadeChunkByModule.set(module, this);
  15208. if (module.preserveSignature) {
  15209. this.strictFacade = needsStrictFacade;
  15210. }
  15211. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  15212. }
  15213. }
  15214. for (const facadeName of requiredFacades) {
  15215. 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));
  15216. }
  15217. }
  15218. for (const module of this.dynamicEntryModules) {
  15219. if (module.info.syntheticNamedExports)
  15220. continue;
  15221. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  15222. this.facadeModule = module;
  15223. this.facadeChunkByModule.set(module, this);
  15224. this.strictFacade = true;
  15225. this.dynamicName = getChunkNameFromModule(module);
  15226. }
  15227. else if (this.facadeModule === module &&
  15228. !this.strictFacade &&
  15229. this.canModuleBeFacade(module, exposedVariables)) {
  15230. this.strictFacade = true;
  15231. }
  15232. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  15233. this.includedNamespaces.add(module);
  15234. this.exports.add(module.namespace);
  15235. }
  15236. }
  15237. if (!this.outputOptions.preserveModules) {
  15238. this.addNecessaryImportsForFacades();
  15239. }
  15240. return facades;
  15241. }
  15242. getChunkName() {
  15243. return (this.name ?? (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  15244. }
  15245. getExportNames() {
  15246. return (this.sortedExportNames ?? (this.sortedExportNames = [...this.exportsByName.keys()].sort()));
  15247. }
  15248. getFileName() {
  15249. return this.fileName || this.getPreliminaryFileName().fileName;
  15250. }
  15251. getImportPath(importer) {
  15252. return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  15253. }
  15254. getPreliminaryFileName() {
  15255. if (this.preliminaryFileName) {
  15256. return this.preliminaryFileName;
  15257. }
  15258. let fileName;
  15259. let hashPlaceholder = null;
  15260. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  15261. if (file) {
  15262. fileName = node_path.basename(file);
  15263. }
  15264. else if (this.fileName === null) {
  15265. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  15266. ? [entryFileNames, 'output.entryFileNames']
  15267. : [chunkFileNames, 'output.chunkFileNames'];
  15268. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  15269. format: () => format,
  15270. hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)),
  15271. name: () => this.getChunkName()
  15272. });
  15273. if (!hashPlaceholder) {
  15274. fileName = makeUnique(fileName, this.bundle);
  15275. }
  15276. }
  15277. else {
  15278. fileName = this.fileName;
  15279. }
  15280. if (!hashPlaceholder) {
  15281. this.bundle[fileName] = FILE_PLACEHOLDER;
  15282. }
  15283. // Caching is essential to not conflict with the file name reservation above
  15284. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  15285. }
  15286. getRenderedChunkInfo() {
  15287. if (this.renderedChunkInfo) {
  15288. return this.renderedChunkInfo;
  15289. }
  15290. return (this.renderedChunkInfo = {
  15291. ...this.getPreRenderedChunkInfo(),
  15292. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  15293. fileName: this.getFileName(),
  15294. // eslint-disable-next-line unicorn/prefer-spread
  15295. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  15296. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  15297. // eslint-disable-next-line unicorn/prefer-spread
  15298. imports: Array.from(this.dependencies, resolveFileName),
  15299. modules: this.renderedModules,
  15300. referencedFiles: this.getReferencedFiles()
  15301. });
  15302. }
  15303. getVariableExportName(variable) {
  15304. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  15305. return '*';
  15306. }
  15307. return this.exportNamesByVariable.get(variable)[0];
  15308. }
  15309. link() {
  15310. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  15311. for (const module of this.orderedModules) {
  15312. this.addImplicitlyLoadedBeforeFromModule(module);
  15313. this.setUpChunkImportsAndExportsForModule(module);
  15314. }
  15315. }
  15316. async render() {
  15317. const { dependencies, exportMode, facadeModule, inputOptions: { onwarn }, outputOptions, pluginDriver, snippets } = this;
  15318. const { format, hoistTransitiveImports, preserveModules } = outputOptions;
  15319. // for static and dynamic entry points, add transitive dependencies to this
  15320. // chunk's dependencies to avoid loading latency
  15321. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  15322. for (const dep of dependencies) {
  15323. if (dep instanceof Chunk)
  15324. this.inlineChunkDependencies(dep);
  15325. }
  15326. }
  15327. const preliminaryFileName = this.getPreliminaryFileName();
  15328. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  15329. const renderedDependencies = [...this.getRenderedDependencies().values()];
  15330. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  15331. let hasExports = renderedExports.length > 0;
  15332. let hasDefaultExport = false;
  15333. for (const renderedDependence of renderedDependencies) {
  15334. const { reexports } = renderedDependence;
  15335. if (reexports?.length) {
  15336. hasExports = true;
  15337. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  15338. hasDefaultExport = true;
  15339. }
  15340. if (format === 'es') {
  15341. renderedDependence.reexports = reexports.filter(
  15342. // eslint-disable-next-line unicorn/prefer-array-some
  15343. ({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  15344. }
  15345. }
  15346. }
  15347. if (!hasDefaultExport) {
  15348. for (const { exported } of renderedExports) {
  15349. if (exported === 'default') {
  15350. hasDefaultExport = true;
  15351. break;
  15352. }
  15353. }
  15354. }
  15355. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  15356. finalisers[format](renderedSource, {
  15357. accessedGlobals,
  15358. dependencies: renderedDependencies,
  15359. exports: renderedExports,
  15360. hasDefaultExport,
  15361. hasExports,
  15362. id: preliminaryFileName.fileName,
  15363. indent,
  15364. intro,
  15365. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  15366. isModuleFacade: facadeModule !== null,
  15367. namedExportsMode: exportMode !== 'default',
  15368. onwarn,
  15369. outro,
  15370. snippets,
  15371. usesTopLevelAwait
  15372. }, outputOptions);
  15373. if (banner)
  15374. magicString.prepend(banner);
  15375. if (footer)
  15376. magicString.append(footer);
  15377. return {
  15378. chunk: this,
  15379. magicString,
  15380. preliminaryFileName,
  15381. usedModules
  15382. };
  15383. }
  15384. addImplicitlyLoadedBeforeFromModule(baseModule) {
  15385. const { chunkByModule, implicitlyLoadedBefore } = this;
  15386. for (const module of baseModule.implicitlyLoadedBefore) {
  15387. const chunk = chunkByModule.get(module);
  15388. if (chunk && chunk !== this) {
  15389. implicitlyLoadedBefore.add(chunk);
  15390. }
  15391. }
  15392. }
  15393. addNecessaryImportsForFacades() {
  15394. for (const [module, variables] of this.includedReexportsByModule) {
  15395. if (this.includedNamespaces.has(module)) {
  15396. for (const variable of variables) {
  15397. this.imports.add(variable);
  15398. }
  15399. }
  15400. }
  15401. }
  15402. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  15403. if (fileName) {
  15404. this.fileName = fileName;
  15405. }
  15406. else {
  15407. this.name = this.outputOptions.sanitizeFileName(name ||
  15408. (preservePath
  15409. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  15410. : getChunkNameFromModule(facadedModule)));
  15411. }
  15412. }
  15413. checkCircularDependencyImport(variable, importingModule) {
  15414. const variableModule = variable.module;
  15415. if (variableModule instanceof Module) {
  15416. const exportChunk = this.chunkByModule.get(variableModule);
  15417. let alternativeReexportModule;
  15418. do {
  15419. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  15420. if (alternativeReexportModule) {
  15421. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  15422. if (exportingChunk !== exportChunk) {
  15423. this.inputOptions.onwarn(errorCyclicCrossChunkReexport(
  15424. // Namespaces do not have an export name
  15425. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  15426. }
  15427. importingModule = alternativeReexportModule;
  15428. }
  15429. } while (alternativeReexportModule);
  15430. }
  15431. }
  15432. ensureReexportsAreAvailableForModule(module) {
  15433. const includedReexports = [];
  15434. const map = module.getExportNamesByVariable();
  15435. for (const exportedVariable of map.keys()) {
  15436. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  15437. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  15438. this.checkCircularDependencyImport(importedVariable, module);
  15439. // When preserving modules, we do not create namespace objects but directly
  15440. // use the actual namespaces, which would be broken by this logic.
  15441. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  15442. const exportingModule = importedVariable.module;
  15443. if (exportingModule instanceof Module) {
  15444. const chunk = this.chunkByModule.get(exportingModule);
  15445. if (chunk && chunk !== this) {
  15446. chunk.exports.add(importedVariable);
  15447. includedReexports.push(importedVariable);
  15448. if (isSynthetic) {
  15449. this.imports.add(importedVariable);
  15450. }
  15451. }
  15452. }
  15453. }
  15454. }
  15455. if (includedReexports.length > 0) {
  15456. this.includedReexportsByModule.set(module, includedReexports);
  15457. }
  15458. }
  15459. generateVariableName() {
  15460. if (this.manualChunkAlias) {
  15461. return this.manualChunkAlias;
  15462. }
  15463. const moduleForNaming = this.entryModules[0] ||
  15464. this.implicitEntryModules[0] ||
  15465. this.dynamicEntryModules[0] ||
  15466. this.orderedModules[this.orderedModules.length - 1];
  15467. if (moduleForNaming) {
  15468. return getChunkNameFromModule(moduleForNaming);
  15469. }
  15470. return 'chunk';
  15471. }
  15472. getChunkExportDeclarations(format) {
  15473. const exports = [];
  15474. for (const exportName of this.getExportNames()) {
  15475. if (exportName[0] === '*')
  15476. continue;
  15477. const variable = this.exportsByName.get(exportName);
  15478. if (!(variable instanceof SyntheticNamedExportVariable)) {
  15479. const module = variable.module;
  15480. if (module) {
  15481. const chunk = this.chunkByModule.get(module);
  15482. if (chunk !== this) {
  15483. if (!chunk || format !== 'es') {
  15484. continue;
  15485. }
  15486. const chunkDep = this.renderedDependencies.get(chunk);
  15487. if (!chunkDep) {
  15488. continue;
  15489. }
  15490. const { imports, reexports } = chunkDep;
  15491. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  15492. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  15493. if (!isImported) {
  15494. continue;
  15495. }
  15496. }
  15497. }
  15498. }
  15499. let expression = null;
  15500. let hoisted = false;
  15501. let local = variable.getName(this.snippets.getPropertyAccess);
  15502. if (variable instanceof LocalVariable) {
  15503. for (const declaration of variable.declarations) {
  15504. if (declaration.parent instanceof FunctionDeclaration ||
  15505. (declaration instanceof ExportDefaultDeclaration &&
  15506. declaration.declaration instanceof FunctionDeclaration)) {
  15507. hoisted = true;
  15508. break;
  15509. }
  15510. }
  15511. }
  15512. else if (variable instanceof SyntheticNamedExportVariable) {
  15513. expression = local;
  15514. if (format === 'es') {
  15515. local = variable.renderName;
  15516. }
  15517. }
  15518. exports.push({
  15519. exported: exportName,
  15520. expression,
  15521. hoisted,
  15522. local
  15523. });
  15524. }
  15525. return exports;
  15526. }
  15527. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  15528. const dependencies = new Set();
  15529. const deconflictedDefault = new Set();
  15530. const deconflictedNamespace = new Set();
  15531. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  15532. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  15533. const module = variable.module;
  15534. if (module instanceof ExternalModule) {
  15535. const chunk = this.externalChunkByModule.get(module);
  15536. dependencies.add(chunk);
  15537. if (addNonNamespacesAndInteropHelpers) {
  15538. if (variable.name === 'default') {
  15539. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  15540. deconflictedDefault.add(chunk);
  15541. }
  15542. }
  15543. else if (variable.name === '*' &&
  15544. namespaceInteropHelpersByInteropType[interop(module.id)]) {
  15545. deconflictedNamespace.add(chunk);
  15546. }
  15547. }
  15548. }
  15549. else {
  15550. const chunk = this.chunkByModule.get(module);
  15551. if (chunk !== this) {
  15552. dependencies.add(chunk);
  15553. if (addNonNamespacesAndInteropHelpers &&
  15554. chunk.exportMode === 'default' &&
  15555. variable.isNamespace) {
  15556. deconflictedNamespace.add(chunk);
  15557. }
  15558. }
  15559. }
  15560. }
  15561. }
  15562. if (addDependenciesWithoutBindings) {
  15563. for (const dependency of this.dependencies) {
  15564. dependencies.add(dependency);
  15565. }
  15566. }
  15567. return { deconflictedDefault, deconflictedNamespace, dependencies };
  15568. }
  15569. getDynamicDependencies() {
  15570. return this.getIncludedDynamicImports()
  15571. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  15572. resolvedDynamicImport.chunk ||
  15573. resolvedDynamicImport.externalChunk ||
  15574. resolvedDynamicImport.resolution)
  15575. .filter((resolution) => resolution !== this &&
  15576. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  15577. }
  15578. getDynamicImportStringAndAssertions(resolution, fileName) {
  15579. if (resolution instanceof ExternalModule) {
  15580. const chunk = this.externalChunkByModule.get(resolution);
  15581. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAssertions(this.snippets)];
  15582. }
  15583. return [
  15584. resolution || '',
  15585. (this.outputOptions.format === 'es' && this.outputOptions.externalImportAssertions) || null
  15586. ];
  15587. }
  15588. getFallbackChunkName() {
  15589. if (this.manualChunkAlias) {
  15590. return this.manualChunkAlias;
  15591. }
  15592. if (this.dynamicName) {
  15593. return this.dynamicName;
  15594. }
  15595. if (this.fileName) {
  15596. return getAliasName(this.fileName);
  15597. }
  15598. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  15599. }
  15600. getImportSpecifiers() {
  15601. const { interop } = this.outputOptions;
  15602. const importsByDependency = new Map();
  15603. for (const variable of this.imports) {
  15604. const module = variable.module;
  15605. let dependency;
  15606. let imported;
  15607. if (module instanceof ExternalModule) {
  15608. dependency = this.externalChunkByModule.get(module);
  15609. imported = variable.name;
  15610. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  15611. return error(errorUnexpectedNamedImport(module.id, imported, false));
  15612. }
  15613. }
  15614. else {
  15615. dependency = this.chunkByModule.get(module);
  15616. imported = dependency.getVariableExportName(variable);
  15617. }
  15618. getOrCreate(importsByDependency, dependency, getNewArray).push({
  15619. imported,
  15620. local: variable.getName(this.snippets.getPropertyAccess)
  15621. });
  15622. }
  15623. return importsByDependency;
  15624. }
  15625. getIncludedDynamicImports() {
  15626. if (this.includedDynamicImports) {
  15627. return this.includedDynamicImports;
  15628. }
  15629. const includedDynamicImports = [];
  15630. for (const module of this.orderedModules) {
  15631. for (const { node, resolution } of module.dynamicImports) {
  15632. if (!node.included) {
  15633. continue;
  15634. }
  15635. includedDynamicImports.push(resolution instanceof Module
  15636. ? {
  15637. chunk: this.chunkByModule.get(resolution),
  15638. externalChunk: null,
  15639. facadeChunk: this.facadeChunkByModule.get(resolution),
  15640. node,
  15641. resolution
  15642. }
  15643. : resolution instanceof ExternalModule
  15644. ? {
  15645. chunk: null,
  15646. externalChunk: this.externalChunkByModule.get(resolution),
  15647. facadeChunk: null,
  15648. node,
  15649. resolution
  15650. }
  15651. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  15652. }
  15653. }
  15654. return (this.includedDynamicImports = includedDynamicImports);
  15655. }
  15656. getPreRenderedChunkInfo() {
  15657. if (this.preRenderedChunkInfo) {
  15658. return this.preRenderedChunkInfo;
  15659. }
  15660. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  15661. return (this.preRenderedChunkInfo = {
  15662. exports: this.getExportNames(),
  15663. facadeModuleId: facadeModule && facadeModule.id,
  15664. isDynamicEntry: dynamicEntryModules.length > 0,
  15665. isEntry: !!facadeModule?.info.isEntry,
  15666. isImplicitEntry: implicitEntryModules.length > 0,
  15667. moduleIds: orderedModules.map(({ id }) => id),
  15668. name: this.getChunkName(),
  15669. type: 'chunk'
  15670. });
  15671. }
  15672. getPreserveModulesChunkNameFromModule(module) {
  15673. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  15674. if (predefinedChunkName)
  15675. return predefinedChunkName;
  15676. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  15677. const sanitizedId = sanitizeFileName(normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  15678. const extensionName = node_path.extname(sanitizedId);
  15679. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  15680. ? sanitizedId.slice(0, -extensionName.length)
  15681. : sanitizedId;
  15682. if (isAbsolute(idWithoutExtension)) {
  15683. return preserveModulesRoot && node_path.resolve(idWithoutExtension).startsWith(preserveModulesRoot)
  15684. ? idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '')
  15685. : relative(this.inputBase, idWithoutExtension);
  15686. }
  15687. else {
  15688. return `_virtual/${node_path.basename(idWithoutExtension)}`;
  15689. }
  15690. }
  15691. getReexportSpecifiers() {
  15692. const { externalLiveBindings, interop } = this.outputOptions;
  15693. const reexportSpecifiers = new Map();
  15694. for (let exportName of this.getExportNames()) {
  15695. let dependency;
  15696. let imported;
  15697. let needsLiveBinding = false;
  15698. if (exportName[0] === '*') {
  15699. const id = exportName.slice(1);
  15700. if (interop(id) === 'defaultOnly') {
  15701. this.inputOptions.onwarn(errorUnexpectedNamespaceReexport(id));
  15702. }
  15703. needsLiveBinding = externalLiveBindings;
  15704. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  15705. imported = exportName = '*';
  15706. }
  15707. else {
  15708. const variable = this.exportsByName.get(exportName);
  15709. if (variable instanceof SyntheticNamedExportVariable)
  15710. continue;
  15711. const module = variable.module;
  15712. if (module instanceof Module) {
  15713. dependency = this.chunkByModule.get(module);
  15714. if (dependency === this)
  15715. continue;
  15716. imported = dependency.getVariableExportName(variable);
  15717. needsLiveBinding = variable.isReassigned;
  15718. }
  15719. else {
  15720. dependency = this.externalChunkByModule.get(module);
  15721. imported = variable.name;
  15722. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  15723. return error(errorUnexpectedNamedImport(module.id, imported, true));
  15724. }
  15725. needsLiveBinding =
  15726. externalLiveBindings &&
  15727. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  15728. }
  15729. }
  15730. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  15731. imported,
  15732. needsLiveBinding,
  15733. reexported: exportName
  15734. });
  15735. }
  15736. return reexportSpecifiers;
  15737. }
  15738. getReferencedFiles() {
  15739. const referencedFiles = new Set();
  15740. for (const module of this.orderedModules) {
  15741. for (const meta of module.importMetas) {
  15742. const fileName = meta.getReferencedFileName(this.pluginDriver);
  15743. if (fileName) {
  15744. referencedFiles.add(fileName);
  15745. }
  15746. }
  15747. }
  15748. return [...referencedFiles];
  15749. }
  15750. getRenderedDependencies() {
  15751. if (this.renderedDependencies) {
  15752. return this.renderedDependencies;
  15753. }
  15754. const importSpecifiers = this.getImportSpecifiers();
  15755. const reexportSpecifiers = this.getReexportSpecifiers();
  15756. const renderedDependencies = new Map();
  15757. const fileName = this.getFileName();
  15758. for (const dep of this.dependencies) {
  15759. const imports = importSpecifiers.get(dep) || null;
  15760. const reexports = reexportSpecifiers.get(dep) || null;
  15761. const namedExportsMode = dep instanceof ExternalChunk || dep.exportMode !== 'default';
  15762. const importPath = dep.getImportPath(fileName);
  15763. renderedDependencies.set(dep, {
  15764. assertions: dep instanceof ExternalChunk ? dep.getImportAssertions(this.snippets) : null,
  15765. defaultVariableName: dep.defaultVariableName,
  15766. globalName: dep instanceof ExternalChunk &&
  15767. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  15768. getGlobalName(dep, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onwarn),
  15769. importPath,
  15770. imports,
  15771. isChunk: dep instanceof Chunk,
  15772. name: dep.variableName,
  15773. namedExportsMode,
  15774. namespaceVariableName: dep.namespaceVariableName,
  15775. reexports
  15776. });
  15777. }
  15778. return (this.renderedDependencies = renderedDependencies);
  15779. }
  15780. inlineChunkDependencies(chunk) {
  15781. for (const dep of chunk.dependencies) {
  15782. if (this.dependencies.has(dep))
  15783. continue;
  15784. this.dependencies.add(dep);
  15785. if (dep instanceof Chunk) {
  15786. this.inlineChunkDependencies(dep);
  15787. }
  15788. }
  15789. }
  15790. // This method changes properties on the AST before rendering and must not be async
  15791. renderModules(fileName) {
  15792. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onwarn }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  15793. const { compact, dynamicImportFunction, format, freeze, namespaceToStringTag } = outputOptions;
  15794. const { _, cnst, n } = snippets;
  15795. this.setDynamicImportResolutions(fileName);
  15796. this.setImportMetaResolutions(fileName);
  15797. this.setIdentifierRenderResolutions();
  15798. const magicString = new Bundle$1({ separator: `${n}${n}` });
  15799. const indent = getIndentString(orderedModules, outputOptions);
  15800. const usedModules = [];
  15801. let hoistedSource = '';
  15802. const accessedGlobals = new Set();
  15803. const renderedModuleSources = new Map();
  15804. const renderOptions = {
  15805. dynamicImportFunction,
  15806. exportNamesByVariable,
  15807. format,
  15808. freeze,
  15809. indent,
  15810. namespaceToStringTag,
  15811. pluginDriver,
  15812. snippets,
  15813. useOriginalName: null
  15814. };
  15815. let usesTopLevelAwait = false;
  15816. for (const module of orderedModules) {
  15817. let renderedLength = 0;
  15818. let source;
  15819. if (module.isIncluded() || includedNamespaces.has(module)) {
  15820. const rendered = module.render(renderOptions);
  15821. ({ source } = rendered);
  15822. usesTopLevelAwait || (usesTopLevelAwait = rendered.usesTopLevelAwait);
  15823. renderedLength = source.length();
  15824. if (renderedLength) {
  15825. if (compact && source.lastLine().includes('//'))
  15826. source.append('\n');
  15827. renderedModuleSources.set(module, source);
  15828. magicString.addSource(source);
  15829. usedModules.push(module);
  15830. }
  15831. const namespace = module.namespace;
  15832. if (includedNamespaces.has(module)) {
  15833. const rendered = namespace.renderBlock(renderOptions);
  15834. if (namespace.renderFirst())
  15835. hoistedSource += n + rendered;
  15836. else
  15837. magicString.addSource(new MagicString(rendered));
  15838. }
  15839. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  15840. if (accessedGlobalVariables) {
  15841. for (const name of accessedGlobalVariables) {
  15842. accessedGlobals.add(name);
  15843. }
  15844. }
  15845. }
  15846. const { renderedExports, removedExports } = module.getRenderedExports();
  15847. renderedModules[module.id] = {
  15848. get code() {
  15849. return source?.toString() ?? null;
  15850. },
  15851. originalLength: module.originalCode.length,
  15852. removedExports,
  15853. renderedExports,
  15854. renderedLength
  15855. };
  15856. }
  15857. if (hoistedSource)
  15858. magicString.prepend(hoistedSource + n + n);
  15859. // eslint-disable-next-line unicorn/consistent-destructuring
  15860. if (this.needsExportsShim) {
  15861. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  15862. }
  15863. const renderedSource = compact ? magicString : magicString.trim();
  15864. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  15865. onwarn(errorEmptyChunk(this.getChunkName()));
  15866. }
  15867. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  15868. }
  15869. setDynamicImportResolutions(fileName) {
  15870. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  15871. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  15872. if (resolvedDynamicImport.chunk) {
  15873. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  15874. if (chunk === this) {
  15875. node.setInternalResolution(resolution.namespace);
  15876. }
  15877. else {
  15878. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null);
  15879. }
  15880. }
  15881. else {
  15882. const { node, resolution } = resolvedDynamicImport;
  15883. const [resolutionString, assertions] = this.getDynamicImportStringAndAssertions(resolution, fileName);
  15884. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, assertions);
  15885. }
  15886. }
  15887. }
  15888. setIdentifierRenderResolutions() {
  15889. const { format, interop, namespaceToStringTag, preserveModules, externalLiveBindings } = this.outputOptions;
  15890. const syntheticExports = new Set();
  15891. for (const exportName of this.getExportNames()) {
  15892. const exportVariable = this.exportsByName.get(exportName);
  15893. if (format !== 'es' &&
  15894. format !== 'system' &&
  15895. exportVariable.isReassigned &&
  15896. !exportVariable.isId) {
  15897. exportVariable.setRenderNames('exports', exportName);
  15898. }
  15899. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  15900. syntheticExports.add(exportVariable);
  15901. }
  15902. else {
  15903. exportVariable.setRenderNames(null, null);
  15904. }
  15905. }
  15906. for (const module of this.orderedModules) {
  15907. if (module.needsExportShim) {
  15908. this.needsExportsShim = true;
  15909. break;
  15910. }
  15911. }
  15912. const usedNames = new Set(['Object', 'Promise']);
  15913. if (this.needsExportsShim) {
  15914. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  15915. }
  15916. if (namespaceToStringTag) {
  15917. usedNames.add('Symbol');
  15918. }
  15919. switch (format) {
  15920. case 'system': {
  15921. usedNames.add('module').add('exports');
  15922. break;
  15923. }
  15924. case 'es': {
  15925. break;
  15926. }
  15927. case 'cjs': {
  15928. usedNames.add('module').add('require').add('__filename').add('__dirname');
  15929. }
  15930. // fallthrough
  15931. default: {
  15932. usedNames.add('exports');
  15933. for (const helper of HELPER_NAMES) {
  15934. usedNames.add(helper);
  15935. }
  15936. }
  15937. }
  15938. 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);
  15939. }
  15940. setImportMetaResolutions(fileName) {
  15941. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  15942. for (const module of orderedModules) {
  15943. for (const importMeta of module.importMetas) {
  15944. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  15945. }
  15946. if (includedNamespaces.has(module)) {
  15947. module.namespace.prepare(accessedGlobalsByScope);
  15948. }
  15949. }
  15950. }
  15951. setUpChunkImportsAndExportsForModule(module) {
  15952. const moduleImports = new Set(module.includedImports);
  15953. // when we are not preserving modules, we need to make all namespace variables available for
  15954. // rendering the namespace object
  15955. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  15956. const memberVariables = module.namespace.getMemberVariables();
  15957. for (const variable of Object.values(memberVariables)) {
  15958. moduleImports.add(variable);
  15959. }
  15960. }
  15961. for (let variable of moduleImports) {
  15962. if (variable instanceof ExportDefaultVariable) {
  15963. variable = variable.getOriginalVariable();
  15964. }
  15965. if (variable instanceof SyntheticNamedExportVariable) {
  15966. variable = variable.getBaseVariable();
  15967. }
  15968. const chunk = this.chunkByModule.get(variable.module);
  15969. if (chunk !== this) {
  15970. this.imports.add(variable);
  15971. if (variable.module instanceof Module) {
  15972. this.checkCircularDependencyImport(variable, module);
  15973. // When preserving modules, we do not create namespace objects but directly
  15974. // use the actual namespaces, which would be broken by this logic.
  15975. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  15976. chunk.exports.add(variable);
  15977. }
  15978. }
  15979. }
  15980. }
  15981. if (this.includedNamespaces.has(module) ||
  15982. (module.info.isEntry && module.preserveSignature !== false) ||
  15983. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  15984. this.ensureReexportsAreAvailableForModule(module);
  15985. }
  15986. for (const { node, resolution } of module.dynamicImports) {
  15987. if (node.included &&
  15988. resolution instanceof Module &&
  15989. this.chunkByModule.get(resolution) === this &&
  15990. !this.includedNamespaces.has(resolution)) {
  15991. this.includedNamespaces.add(resolution);
  15992. this.ensureReexportsAreAvailableForModule(resolution);
  15993. }
  15994. }
  15995. }
  15996. }
  15997. function getChunkNameFromModule(module) {
  15998. return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id);
  15999. }
  16000. function getPredefinedChunkNameFromModule(module) {
  16001. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  16002. }
  16003. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  16004. const importedBindingsPerDependency = {};
  16005. for (const [dependency, declaration] of renderedDependencies) {
  16006. const specifiers = new Set();
  16007. if (declaration.imports) {
  16008. for (const { imported } of declaration.imports) {
  16009. specifiers.add(imported);
  16010. }
  16011. }
  16012. if (declaration.reexports) {
  16013. for (const { imported } of declaration.reexports) {
  16014. specifiers.add(imported);
  16015. }
  16016. }
  16017. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  16018. }
  16019. return importedBindingsPerDependency;
  16020. }
  16021. const QUERY_HASH_REGEX = /[#?]/;
  16022. const resolveFileName = (dependency) => dependency.getFileName();
  16023. /**
  16024. * Concatenate a number of iterables to a new iterable without fully evaluating
  16025. * their iterators. Useful when e.g. working with large sets or lists and when
  16026. * there is a chance that the iterators will not be fully exhausted.
  16027. */
  16028. function* concatLazy(iterables) {
  16029. for (const iterable of iterables) {
  16030. yield* iterable;
  16031. }
  16032. }
  16033. /**
  16034. * At its core, the algorithm first starts from each static or dynamic entry
  16035. * point and then assigns that entry point to all modules than can be reached
  16036. * via static imports. We call this the *dependent entry points* of that
  16037. * module.
  16038. *
  16039. * Then we group all modules with the same dependent entry points into chunks
  16040. * as those modules will always be loaded together.
  16041. *
  16042. * One non-trivial optimization we can apply is that dynamic entries are
  16043. * different from static entries in so far as when a dynamic import occurs,
  16044. * some
  16045. * modules are already in memory. If some of these modules are also
  16046. * dependencies
  16047. * of the dynamic entry, then it does not make sense to create a separate chunk
  16048. * for them. Instead, the dynamic import target can load them from the
  16049. * importing
  16050. * chunk.
  16051. *
  16052. * With regard to chunking, if B is implicitly loaded after A, then this can be
  16053. * handled the same way as if there was a dynamic import A => B.
  16054. *
  16055. * Example:
  16056. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  16057. * Then the initial algorithm would assign A into the A chunk, C into the C
  16058. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  16059. * points
  16060. * A and C.
  16061. * However we know that C can only be loaded from A, so A and its dependency B
  16062. * must already be in memory when C is loaded. So it is enough to create only
  16063. * two chunks A containing [AB] and C containing [C].
  16064. *
  16065. * So we do not assign the dynamic entry C as dependent entry point to modules
  16066. * that are already loaded.
  16067. *
  16068. * In a more complex example, let us assume that we have entry points X and Y.
  16069. * Further, let us assume
  16070. * X -> A, X -> B, X -> C,
  16071. * Y -> A, Y -> B,
  16072. * A => D,
  16073. * D -> B, D -> C
  16074. * So without dynamic import optimization, the dependent entry points are
  16075. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y,
  16076. * so we would for now create six chunks.
  16077. *
  16078. * Now D is loaded only after A is loaded. But A is loaded if either X is
  16079. * loaded
  16080. * or Y is loaded. So the modules that are already in memory when D is loaded
  16081. * are the intersection of all modules that X depends on with all modules that
  16082. * Y
  16083. * depends on, which in this case are the modules A and B.
  16084. * We could also say they are all modules that have both X and Y as dependent
  16085. * entry points.
  16086. *
  16087. * So we can remove D as dependent entry point from A and B, which means they
  16088. * both now have only XY as dependent entry points and can be merged into the
  16089. * same chunk.
  16090. *
  16091. * Now let us extend this to the most general case where we have several
  16092. * dynamic
  16093. * importers for one dynamic entry point.
  16094. *
  16095. * In the most general form, it works like this:
  16096. * For each dynamic entry point, we have a number of dynamic importers, which
  16097. * are the modules importing it. Using the previous ideas, we can determine
  16098. * the modules already in memory for each dynamic importer by looking for all
  16099. * modules that have all the dependent entry points of the dynamic importer as
  16100. * dependent entry points.
  16101. * So the modules that are guaranteed to be in memory when the dynamic entry
  16102. * point is loaded are the intersection of the modules already in memory for
  16103. * each dynamic importer.
  16104. *
  16105. * Assuming that A => D and B => D and A has dependent entry points XY and B
  16106. * has
  16107. * dependent entry points YZ, then the modules guaranteed to be in memory are
  16108. * all modules that have at least XYZ as dependent entry points.
  16109. * We call XYZ the *dynamically dependent entry points* of D.
  16110. *
  16111. * Now there is one last case to consider: If one of the dynamically dependent
  16112. * entries is itself a dynamic entry, then any module is in memory that either
  16113. * is a dependency of that dynamic entry or again has the dynamic dependent
  16114. * entries of that dynamic entry as dependent entry points.
  16115. *
  16116. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  16117. * complexity with regard to dynamic entries that blew up for very large
  16118. * projects.
  16119. *
  16120. * If we have an efficient way to do Set operations, an alternative approach
  16121. * would be to instead collect already loaded modules per dynamic entry. And as
  16122. * all chunks from the initial grouping would behave the same, we can instead
  16123. * collect already loaded chunks for a performance improvement.
  16124. *
  16125. * To do that efficiently, need
  16126. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  16127. * imports that can be triggered by a dynamic entry
  16128. * - a Map of static dependencies per entry
  16129. * - a Map of already loaded chunks per entry that we initially populate with
  16130. * empty Sets for static entries and Sets containing all entries for dynamic
  16131. * entries
  16132. *
  16133. * For efficient operations, we assign each entry a numerical index and
  16134. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  16135. * bit index. Then thw last two maps can be represented as arrays of BigInt
  16136. * values.
  16137. *
  16138. * Then we iterate through each dynamic entry. We set the already loaded modules
  16139. * to the intersection of the previously already loaded modules with the union
  16140. * of the already loaded modules of that chunk with its static dependencies.
  16141. *
  16142. * If the already loaded modules changed, then we use the Map of dynamic imports
  16143. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  16144. * them back into the iteration. As an additional optimization, we note for
  16145. * each dynamic entry which dynamic dependent entries have changed and only
  16146. * intersect those entries again on subsequent interations.
  16147. *
  16148. * Then we remove the dynamic entries from the list of dependent entries for
  16149. * those chunks that are already loaded for that dynamic entry and create
  16150. * another round of chunks.
  16151. */
  16152. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize) {
  16153. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  16154. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry } = analyzeModuleGraph(entries);
  16155. // Each chunk is identified by its position in this array
  16156. const initialChunks = getChunksFromDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  16157. // This mutates initialChunks but also clears
  16158. // dynamicallyDependentEntriesByDynamicEntry as side effect
  16159. removeUnnecessaryDependentEntries(initialChunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  16160. chunkDefinitions.push(...getOptimizedChunks(getChunksFromDependentEntries(initialChunks), allEntries.length, minChunkSize).map(({ modules }) => ({
  16161. alias: null,
  16162. modules
  16163. })));
  16164. return chunkDefinitions;
  16165. }
  16166. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  16167. const chunkDefinitions = [];
  16168. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  16169. const manualChunkModulesByAlias = Object.create(null);
  16170. for (const [entry, alias] of manualChunkAliasByEntry) {
  16171. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] || (manualChunkModulesByAlias[alias] = [])), modulesInManualChunks);
  16172. }
  16173. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  16174. chunkDefinitions.push({ alias, modules });
  16175. }
  16176. return { chunkDefinitions, modulesInManualChunks };
  16177. }
  16178. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  16179. const modulesToHandle = new Set([entry]);
  16180. for (const module of modulesToHandle) {
  16181. modulesInManualChunks.add(module);
  16182. manualChunkModules.push(module);
  16183. for (const dependency of module.dependencies) {
  16184. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  16185. modulesToHandle.add(dependency);
  16186. }
  16187. }
  16188. }
  16189. }
  16190. function analyzeModuleGraph(entries) {
  16191. const dynamicEntryModules = new Set();
  16192. const dependentEntriesByModule = new Map();
  16193. const dynamicImportModulesByEntry = [];
  16194. const allEntriesSet = new Set(entries);
  16195. let entryIndex = 0;
  16196. for (const currentEntry of allEntriesSet) {
  16197. const dynamicImportsForCurrentEntry = new Set();
  16198. dynamicImportModulesByEntry.push(dynamicImportsForCurrentEntry);
  16199. const modulesToHandle = new Set([currentEntry]);
  16200. for (const module of modulesToHandle) {
  16201. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  16202. for (const dependency of module.getDependenciesToBeIncluded()) {
  16203. if (!(dependency instanceof ExternalModule)) {
  16204. modulesToHandle.add(dependency);
  16205. }
  16206. }
  16207. for (const { resolution } of module.dynamicImports) {
  16208. if (resolution instanceof Module &&
  16209. resolution.includedDynamicImporters.length > 0 &&
  16210. !allEntriesSet.has(resolution)) {
  16211. dynamicEntryModules.add(resolution);
  16212. allEntriesSet.add(resolution);
  16213. dynamicImportsForCurrentEntry.add(resolution);
  16214. }
  16215. }
  16216. for (const dependency of module.implicitlyLoadedBefore) {
  16217. if (!allEntriesSet.has(dependency)) {
  16218. dynamicEntryModules.add(dependency);
  16219. allEntriesSet.add(dependency);
  16220. }
  16221. }
  16222. }
  16223. entryIndex++;
  16224. }
  16225. const allEntries = [...allEntriesSet];
  16226. const { dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry);
  16227. return {
  16228. allEntries,
  16229. dependentEntriesByModule,
  16230. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries),
  16231. dynamicImportsByEntry
  16232. };
  16233. }
  16234. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry) {
  16235. const entryIndexByModule = new Map();
  16236. const dynamicEntries = new Set();
  16237. for (const [entryIndex, entry] of allEntries.entries()) {
  16238. entryIndexByModule.set(entry, entryIndex);
  16239. if (dynamicEntryModules.has(entry)) {
  16240. dynamicEntries.add(entryIndex);
  16241. }
  16242. }
  16243. const dynamicImportsByEntry = [];
  16244. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  16245. const dynamicImports = new Set();
  16246. for (const dynamicEntry of dynamicImportModules) {
  16247. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  16248. }
  16249. dynamicImportsByEntry.push(dynamicImports);
  16250. }
  16251. return { dynamicEntries, dynamicImportsByEntry };
  16252. }
  16253. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries) {
  16254. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  16255. for (const dynamicEntryIndex of dynamicEntries) {
  16256. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  16257. const dynamicEntry = allEntries[dynamicEntryIndex];
  16258. for (const importer of concatLazy([
  16259. dynamicEntry.includedDynamicImporters,
  16260. dynamicEntry.implicitlyLoadedAfter
  16261. ])) {
  16262. for (const entry of dependentEntriesByModule.get(importer)) {
  16263. dynamicallyDependentEntries.add(entry);
  16264. }
  16265. }
  16266. }
  16267. return dynamicallyDependentEntriesByDynamicEntry;
  16268. }
  16269. function getChunksFromDependentEntries(modulesWithDependentEntries) {
  16270. var _a;
  16271. const chunkModules = Object.create(null);
  16272. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  16273. let chunkSignature = 0n;
  16274. for (const entryIndex of dependentEntries) {
  16275. chunkSignature |= 1n << BigInt(entryIndex);
  16276. }
  16277. (chunkModules[_a = String(chunkSignature)] || (chunkModules[_a] = {
  16278. dependentEntries: new Set(dependentEntries),
  16279. modules: []
  16280. })).modules.push(...modules);
  16281. }
  16282. return Object.values(chunkModules);
  16283. }
  16284. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  16285. for (const [module, dependentEntries] of dependentEntriesByModule) {
  16286. if (!modulesInManualChunks.has(module)) {
  16287. yield { dependentEntries, modules: [module] };
  16288. }
  16289. }
  16290. }
  16291. /**
  16292. * This removes all unnecessary dynamic entries from the dependenEntries in its
  16293. * first argument. It will also consume its second argument, so if
  16294. * dynamicallyDependentEntriesByDynamicEntry is ever needed after this, we
  16295. * should make a copy.
  16296. */
  16297. function removeUnnecessaryDependentEntries(chunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  16298. // The indices correspond to the indices in allEntries. The chunks correspond
  16299. // to bits in the bigint values where chunk 0 is the lowest bit.
  16300. const staticDependenciesPerEntry = allEntries.map(() => 0n);
  16301. const alreadyLoadedChunksPerEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  16302. // This toggles the bits for each chunk that is a dependency of an entry
  16303. let chunkMask = 1n;
  16304. for (const { dependentEntries } of chunks) {
  16305. for (const entryIndex of dependentEntries) {
  16306. staticDependenciesPerEntry[entryIndex] |= chunkMask;
  16307. }
  16308. chunkMask <<= 1n;
  16309. }
  16310. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  16311. // If we no longer want this, we should make a copy here.
  16312. const updatedDynamicallyDependentEntriesByDynamicEntry = dynamicallyDependentEntriesByDynamicEntry;
  16313. for (const [dynamicEntryIndex, updatedDynamicallyDependentEntries] of updatedDynamicallyDependentEntriesByDynamicEntry) {
  16314. updatedDynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  16315. const previousLoadedModules = alreadyLoadedChunksPerEntry[dynamicEntryIndex];
  16316. let newLoadedModules = previousLoadedModules;
  16317. for (const entryIndex of updatedDynamicallyDependentEntries) {
  16318. newLoadedModules &=
  16319. staticDependenciesPerEntry[entryIndex] | alreadyLoadedChunksPerEntry[entryIndex];
  16320. }
  16321. if (newLoadedModules !== previousLoadedModules) {
  16322. alreadyLoadedChunksPerEntry[dynamicEntryIndex] = newLoadedModules;
  16323. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  16324. getOrCreate(updatedDynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  16325. }
  16326. }
  16327. }
  16328. // Remove entries from dependent entries if a chunk is already loaded without
  16329. // that entry.
  16330. chunkMask = 1n;
  16331. for (const { dependentEntries } of chunks) {
  16332. for (const entryIndex of dependentEntries) {
  16333. if ((alreadyLoadedChunksPerEntry[entryIndex] & chunkMask) === chunkMask) {
  16334. dependentEntries.delete(entryIndex);
  16335. }
  16336. }
  16337. chunkMask <<= 1n;
  16338. }
  16339. }
  16340. /**
  16341. * This function tries to get rid of small chunks by merging them with other
  16342. * chunks.
  16343. *
  16344. * We can only merge chunks safely if after the merge, loading any entry point
  16345. * in any allowed order will not trigger side effects that should not have been
  16346. * triggered. While side effects are usually things like global function calls,
  16347. * global variable mutations or potentially thrown errors, details do not
  16348. * matter here, and we just discern chunks without side effects (pure chunks)
  16349. * from other chunks.
  16350. *
  16351. * As a first step, we assign each pre-generated chunk with side effects a
  16352. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  16353. *
  16354. * Now to determine the side effects of loading a chunk, one also has to take
  16355. * the side effects of its dependencies into account. So if A depends on B
  16356. * (A -> B) and both have side effects, loading A triggers effects AB.
  16357. *
  16358. * Now from the previous step we know that each chunk is uniquely determine by
  16359. * the entry points that depend on it and cause it to load, which we will call
  16360. * its dependent entry points.
  16361. *
  16362. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  16363. * Starting from that idea, we can determine a set of chunks—and thus a set
  16364. * of side effects—that must have been triggered if a certain chunk has been
  16365. * loaded. Basically, it is the intersection of all chunks loaded by the
  16366. * dependent entry points of a given chunk. We call the corresponding side
  16367. * effects the correlated side effects of that chunk.
  16368. *
  16369. * Example:
  16370. * X -> ABC, Y -> ADE, A-> F, B -> D
  16371. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  16372. * The intersection is ADF. So we know that when A is loaded, D and F must also
  16373. * be in memory even though neither D nor A is a dependency of the other.
  16374. * If all have side effects, we call ADF the correlated side effects of A. The
  16375. * correlated side effects need to remain constant when merging chunks.
  16376. *
  16377. * In contrast, we have the dependency side effects of A, which represents
  16378. * the side effects we trigger if we directly load A. In this example, the
  16379. * dependency side effects are AF.
  16380. * For entry chunks, dependency and correlated side effects are the same.
  16381. *
  16382. * With these concepts, merging chunks is allowed if the correlated side
  16383. * effects of each entry do not change. Thus, we are allowed to merge two
  16384. * chunks if
  16385. *
  16386. * a) the dependency side effects of each chunk are a subset of the correlated
  16387. * side effects of the other chunk, so no additional side effects are
  16388. * triggered for any entry, or
  16389. * b) The dependent entry points of chunk A are a subset of the dependent entry
  16390. * points of chunk B while the dependency side effects of A are a subset of
  16391. * the correlated side effects of B. Because in that scenario, whenever A is
  16392. * loaded, B is loaded as well. But there are cases when B is loaded where A
  16393. * is not loaded. So if we merge the chunks, all dependency side effects of
  16394. * A will be added to the correlated side effects of B, and as the latter is
  16395. * not allowed to change, the former need to be a subset of the latter.
  16396. *
  16397. * Another consideration when merging small chunks into other chunks is to
  16398. * avoid
  16399. * that too much additional code is loaded. This is achieved when the dependent
  16400. * entries of the small chunk are a subset of the dependent entries of the
  16401. * other
  16402. * chunk. Because then when the small chunk is loaded, the other chunk was
  16403. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  16404. * additional size of the small chunk is loaded unnecessarily.
  16405. *
  16406. * So the algorithm performs merges in two passes:
  16407. *
  16408. * 1. First we try to merge small chunks A only into other chunks B if the
  16409. * dependent entries of A are a subset of the dependent entries of B and the
  16410. * dependency side effects of A are a subset of the correlated side effects
  16411. * of B.
  16412. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  16413. * following the rule (a), starting with the smallest chunks to look for
  16414. * possible merge targets.
  16415. */
  16416. function getOptimizedChunks(initialChunks, numberOfEntries, minChunkSize) {
  16417. timeStart('optimize chunks', 3);
  16418. const chunkPartition = getPartitionedChunks(initialChunks, numberOfEntries, minChunkSize);
  16419. if (!chunkPartition) {
  16420. timeEnd('optimize chunks', 3);
  16421. return initialChunks; // the actual modules
  16422. }
  16423. minChunkSize > 1 &&
  16424. console.log('Before eliminating small chunks, there were\n', initialChunks.length, 'chunks, of which\n', chunkPartition.small.size, 'were below minChunkSize.');
  16425. mergeChunks(chunkPartition, minChunkSize);
  16426. minChunkSize > 1 &&
  16427. console.log('After merging chunks,\n', chunkPartition.small.size + chunkPartition.big.size, 'chunks remain, of which\n', chunkPartition.small.size, 'are below minChunkSize.');
  16428. timeEnd('optimize chunks', 3);
  16429. return [...chunkPartition.small, ...chunkPartition.big];
  16430. }
  16431. function getPartitionedChunks(initialChunks, numberOfEntries, minChunkSize) {
  16432. const smallChunks = [];
  16433. const bigChunks = [];
  16434. const chunkByModule = new Map();
  16435. const sizeByAtom = [];
  16436. let sideEffectAtoms = 0n;
  16437. let containedAtoms = 1n;
  16438. for (const { dependentEntries, modules } of initialChunks) {
  16439. const chunkDescription = {
  16440. containedAtoms,
  16441. correlatedAtoms: 0n,
  16442. dependencies: new Set(),
  16443. dependentChunks: new Set(),
  16444. dependentEntries,
  16445. modules,
  16446. pure: true,
  16447. size: 0
  16448. };
  16449. let size = 0;
  16450. let pure = true;
  16451. for (const module of modules) {
  16452. chunkByModule.set(module, chunkDescription);
  16453. // Unfortunately, we cannot take tree-shaking into account here because
  16454. // rendering did not happen yet, but we can detect empty modules
  16455. if (module.isIncluded()) {
  16456. pure && (pure = !module.hasEffects());
  16457. // we use a trivial size for the default minChunkSize to improve
  16458. // performance
  16459. size += minChunkSize > 1 ? module.estimateSize() : 1;
  16460. }
  16461. }
  16462. chunkDescription.pure = pure;
  16463. chunkDescription.size = size;
  16464. sizeByAtom.push(size);
  16465. if (!pure) {
  16466. sideEffectAtoms |= containedAtoms;
  16467. }
  16468. (size < minChunkSize ? smallChunks : bigChunks).push(chunkDescription);
  16469. containedAtoms <<= 1n;
  16470. }
  16471. // If there are no small chunks, we will not optimize
  16472. if (smallChunks.length === 0) {
  16473. return null;
  16474. }
  16475. sideEffectAtoms |= addChunkDependenciesAndAtomsAndGetSideEffectAtoms([bigChunks, smallChunks], chunkByModule, numberOfEntries, containedAtoms);
  16476. return {
  16477. big: new Set(bigChunks),
  16478. sideEffectAtoms,
  16479. sizeByAtom,
  16480. small: new Set(smallChunks)
  16481. };
  16482. }
  16483. function mergeChunks(chunkPartition, minChunkSize) {
  16484. const { small } = chunkPartition;
  16485. for (const mergedChunk of small) {
  16486. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition,
  16487. // In the default case, we do not accept size increases
  16488. minChunkSize <= 1 ? 1 : Infinity);
  16489. if (bestTargetChunk) {
  16490. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  16491. small.delete(mergedChunk);
  16492. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  16493. bestTargetChunk.modules.push(...modules);
  16494. bestTargetChunk.size += size;
  16495. bestTargetChunk.pure && (bestTargetChunk.pure = pure);
  16496. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  16497. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  16498. bestTargetChunk.containedAtoms |= containedAtoms;
  16499. for (const entry of mergedChunk.dependentEntries) {
  16500. dependentEntries.add(entry);
  16501. }
  16502. for (const dependency of mergedChunk.dependencies) {
  16503. dependencies.add(dependency);
  16504. dependency.dependentChunks.delete(mergedChunk);
  16505. dependency.dependentChunks.add(bestTargetChunk);
  16506. }
  16507. for (const dependentChunk of mergedChunk.dependentChunks) {
  16508. dependentChunks.add(dependentChunk);
  16509. dependentChunk.dependencies.delete(mergedChunk);
  16510. dependentChunk.dependencies.add(bestTargetChunk);
  16511. }
  16512. dependencies.delete(bestTargetChunk);
  16513. dependentChunks.delete(bestTargetChunk);
  16514. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  16515. }
  16516. }
  16517. }
  16518. function addChunkDependenciesAndAtomsAndGetSideEffectAtoms(chunkLists, chunkByModule, numberOfEntries, nextAtomSignature) {
  16519. const signatureByExternalModule = new Map();
  16520. let sideEffectAtoms = 0n;
  16521. const atomsByEntry = [];
  16522. for (let index = 0; index < numberOfEntries; index++) {
  16523. atomsByEntry.push(0n);
  16524. }
  16525. for (const chunks of chunkLists) {
  16526. chunks.sort(compareChunkSize);
  16527. for (const chunk of chunks) {
  16528. const { dependencies, dependentEntries, modules } = chunk;
  16529. for (const module of modules) {
  16530. for (const dependency of module.getDependenciesToBeIncluded()) {
  16531. if (dependency instanceof ExternalModule) {
  16532. if (dependency.info.moduleSideEffects) {
  16533. chunk.containedAtoms |= getOrCreate(signatureByExternalModule, dependency, () => {
  16534. const signature = nextAtomSignature;
  16535. nextAtomSignature <<= 1n;
  16536. sideEffectAtoms |= signature;
  16537. return signature;
  16538. });
  16539. }
  16540. }
  16541. else {
  16542. const dependencyChunk = chunkByModule.get(dependency);
  16543. if (dependencyChunk && dependencyChunk !== chunk) {
  16544. dependencies.add(dependencyChunk);
  16545. dependencyChunk.dependentChunks.add(chunk);
  16546. }
  16547. }
  16548. }
  16549. }
  16550. const { containedAtoms } = chunk;
  16551. for (const entryIndex of dependentEntries) {
  16552. atomsByEntry[entryIndex] |= containedAtoms;
  16553. }
  16554. }
  16555. }
  16556. for (const chunks of chunkLists) {
  16557. for (const chunk of chunks) {
  16558. const { dependentEntries } = chunk;
  16559. // Correlated atoms are the intersection of all entry atoms
  16560. chunk.correlatedAtoms = -1n;
  16561. for (const entryIndex of dependentEntries) {
  16562. chunk.correlatedAtoms &= atomsByEntry[entryIndex];
  16563. }
  16564. }
  16565. }
  16566. return sideEffectAtoms;
  16567. }
  16568. function findBestMergeTarget(mergedChunk, { big, sideEffectAtoms, sizeByAtom, small }, smallestAdditionalSize) {
  16569. let bestTargetChunk = null;
  16570. // In the default case, we do not accept size increases
  16571. for (const targetChunk of concatLazy([small, big])) {
  16572. if (mergedChunk === targetChunk)
  16573. continue;
  16574. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  16575. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  16576. bestTargetChunk = targetChunk;
  16577. if (additionalSizeAfterMerge === 0)
  16578. break;
  16579. smallestAdditionalSize = additionalSizeAfterMerge;
  16580. }
  16581. }
  16582. return bestTargetChunk;
  16583. }
  16584. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  16585. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  16586. }
  16587. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  16588. return sizeA - sizeB;
  16589. }
  16590. /**
  16591. * Determine the additional unused code size that would be added by merging the
  16592. * two chunks. This is not an exact measurement but rather an upper bound. If
  16593. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  16594. * is returned.
  16595. * Merging will not produce cycles if none of the direct non-merged
  16596. * dependencies of a chunk have the other chunk as a transitive dependency.
  16597. */
  16598. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  16599. // The maximum additional unused code size allowed to be added by the merge,
  16600. // taking dependencies into account, needs to be below this number
  16601. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  16602. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  16603. return firstSize < currentAdditionalSize
  16604. ? firstSize +
  16605. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  16606. : Infinity;
  16607. }
  16608. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  16609. const { correlatedAtoms } = dependencyChunk;
  16610. let dependencyAtoms = dependentChunk.containedAtoms;
  16611. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  16612. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  16613. return Infinity;
  16614. }
  16615. const chunksToCheck = new Set(dependentChunk.dependencies);
  16616. for (const { dependencies, containedAtoms } of chunksToCheck) {
  16617. dependencyAtoms |= containedAtoms;
  16618. const containedSideEffects = containedAtoms & sideEffectAtoms;
  16619. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  16620. return Infinity;
  16621. }
  16622. for (const dependency of dependencies) {
  16623. if (dependency === dependencyChunk) {
  16624. return Infinity;
  16625. }
  16626. chunksToCheck.add(dependency);
  16627. }
  16628. }
  16629. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  16630. }
  16631. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  16632. let size = 0;
  16633. let atomIndex = 0;
  16634. let atomSignature = 1n;
  16635. const { length } = sizeByAtom;
  16636. for (; atomIndex < length; atomIndex++) {
  16637. if ((atoms & atomSignature) === atomSignature) {
  16638. size += sizeByAtom[atomIndex];
  16639. }
  16640. atomSignature <<= 1n;
  16641. if (size >= currentAdditionalSize) {
  16642. return Infinity;
  16643. }
  16644. }
  16645. return size;
  16646. }
  16647. // ported from https://github.com/substack/node-commondir
  16648. function commondir(files) {
  16649. if (files.length === 0)
  16650. return '/';
  16651. if (files.length === 1)
  16652. return node_path.dirname(files[0]);
  16653. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  16654. const pathSegements = file.split(/\/+|\\+/);
  16655. let index;
  16656. for (index = 0; commonSegments[index] === pathSegements[index] &&
  16657. index < Math.min(commonSegments.length, pathSegements.length); index++)
  16658. ;
  16659. return commonSegments.slice(0, index);
  16660. }, files[0].split(/\/+|\\+/));
  16661. // Windows correctly handles paths with forward-slashes
  16662. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  16663. }
  16664. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  16665. function sortByExecutionOrder(units) {
  16666. units.sort(compareExecIndex);
  16667. }
  16668. function analyseModuleExecution(entryModules) {
  16669. let nextExecIndex = 0;
  16670. const cyclePaths = [];
  16671. const analysedModules = new Set();
  16672. const dynamicImports = new Set();
  16673. const parents = new Map();
  16674. const orderedModules = [];
  16675. const analyseModule = (module) => {
  16676. if (module instanceof Module) {
  16677. for (const dependency of module.dependencies) {
  16678. if (parents.has(dependency)) {
  16679. if (!analysedModules.has(dependency)) {
  16680. cyclePaths.push(getCyclePath(dependency, module, parents));
  16681. }
  16682. continue;
  16683. }
  16684. parents.set(dependency, module);
  16685. analyseModule(dependency);
  16686. }
  16687. for (const dependency of module.implicitlyLoadedBefore) {
  16688. dynamicImports.add(dependency);
  16689. }
  16690. for (const { resolution } of module.dynamicImports) {
  16691. if (resolution instanceof Module) {
  16692. dynamicImports.add(resolution);
  16693. }
  16694. }
  16695. orderedModules.push(module);
  16696. }
  16697. module.execIndex = nextExecIndex++;
  16698. analysedModules.add(module);
  16699. };
  16700. for (const currentEntry of entryModules) {
  16701. if (!parents.has(currentEntry)) {
  16702. parents.set(currentEntry, null);
  16703. analyseModule(currentEntry);
  16704. }
  16705. }
  16706. for (const currentEntry of dynamicImports) {
  16707. if (!parents.has(currentEntry)) {
  16708. parents.set(currentEntry, null);
  16709. analyseModule(currentEntry);
  16710. }
  16711. }
  16712. return { cyclePaths, orderedModules };
  16713. }
  16714. function getCyclePath(module, parent, parents) {
  16715. const cycleSymbol = Symbol(module.id);
  16716. const path = [module.id];
  16717. let nextModule = parent;
  16718. module.cycles.add(cycleSymbol);
  16719. while (nextModule !== module) {
  16720. nextModule.cycles.add(cycleSymbol);
  16721. path.push(nextModule.id);
  16722. nextModule = parents.get(nextModule);
  16723. }
  16724. path.push(path[0]);
  16725. path.reverse();
  16726. return path;
  16727. }
  16728. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  16729. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  16730. const cnst = constBindings ? 'const' : 'var';
  16731. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  16732. const getFunctionIntro = arrowFunctions
  16733. ? (parameters, { isAsync, name }) => {
  16734. const singleParameter = parameters.length === 1;
  16735. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  16736. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  16737. }
  16738. : getNonArrowFunctionIntro;
  16739. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  16740. `${getFunctionIntro(parameters, {
  16741. isAsync: false,
  16742. name
  16743. })}${arrowFunctions
  16744. ? lineBreakIndent
  16745. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  16746. : ''
  16747. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  16748. arrowFunctions
  16749. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  16750. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  16751. ];
  16752. const isValidPropertyName = reservedNamesAsProps
  16753. ? (name) => validPropertyName.test(name)
  16754. : (name) => !RESERVED_NAMES$1.has(name) && validPropertyName.test(name);
  16755. return {
  16756. _,
  16757. cnst,
  16758. getDirectReturnFunction,
  16759. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  16760. const [left, right] = getDirectReturnFunction(parameters, {
  16761. functionReturn: true,
  16762. lineBreakIndent: null,
  16763. name: null
  16764. });
  16765. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  16766. },
  16767. getFunctionIntro,
  16768. getNonArrowFunctionIntro,
  16769. getObject(fields, { lineBreakIndent }) {
  16770. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  16771. return `{${fields
  16772. .map(([key, value]) => {
  16773. if (key === null)
  16774. return `${prefix}${value}`;
  16775. const needsQuotes = !isValidPropertyName(key);
  16776. return key === value && objectShorthand && !needsQuotes
  16777. ? prefix + key
  16778. : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
  16779. })
  16780. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  16781. },
  16782. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  16783. n,
  16784. s
  16785. };
  16786. }
  16787. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  16788. const validPropertyName = /^(?!\d)[\w$]+$/;
  16789. class Source {
  16790. constructor(filename, content) {
  16791. this.isOriginal = true;
  16792. this.filename = filename;
  16793. this.content = content;
  16794. }
  16795. traceSegment(line, column, name) {
  16796. return { column, line, name, source: this };
  16797. }
  16798. }
  16799. class Link {
  16800. constructor(map, sources) {
  16801. this.sources = sources;
  16802. this.names = map.names;
  16803. this.mappings = map.mappings;
  16804. }
  16805. traceMappings() {
  16806. const sources = [];
  16807. const sourceIndexMap = new Map();
  16808. const sourcesContent = [];
  16809. const names = [];
  16810. const nameIndexMap = new Map();
  16811. const mappings = [];
  16812. for (const line of this.mappings) {
  16813. const tracedLine = [];
  16814. for (const segment of line) {
  16815. if (segment.length === 1)
  16816. continue;
  16817. const source = this.sources[segment[1]];
  16818. if (!source)
  16819. continue;
  16820. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  16821. if (traced) {
  16822. const { column, line, name, source: { content, filename } } = traced;
  16823. let sourceIndex = sourceIndexMap.get(filename);
  16824. if (sourceIndex === undefined) {
  16825. sourceIndex = sources.length;
  16826. sources.push(filename);
  16827. sourceIndexMap.set(filename, sourceIndex);
  16828. sourcesContent[sourceIndex] = content;
  16829. }
  16830. else if (sourcesContent[sourceIndex] == null) {
  16831. sourcesContent[sourceIndex] = content;
  16832. }
  16833. else if (content != null && sourcesContent[sourceIndex] !== content) {
  16834. return error(errorConflictingSourcemapSources(filename));
  16835. }
  16836. const tracedSegment = [segment[0], sourceIndex, line, column];
  16837. if (name) {
  16838. let nameIndex = nameIndexMap.get(name);
  16839. if (nameIndex === undefined) {
  16840. nameIndex = names.length;
  16841. names.push(name);
  16842. nameIndexMap.set(name, nameIndex);
  16843. }
  16844. tracedSegment[4] = nameIndex;
  16845. }
  16846. tracedLine.push(tracedSegment);
  16847. }
  16848. }
  16849. mappings.push(tracedLine);
  16850. }
  16851. return { mappings, names, sources, sourcesContent };
  16852. }
  16853. traceSegment(line, column, name) {
  16854. const segments = this.mappings[line];
  16855. if (!segments)
  16856. return null;
  16857. // binary search through segments for the given column
  16858. let searchStart = 0;
  16859. let searchEnd = segments.length - 1;
  16860. while (searchStart <= searchEnd) {
  16861. const m = (searchStart + searchEnd) >> 1;
  16862. const segment = segments[m];
  16863. // If a sourcemap does not have sufficient resolution to contain a
  16864. // necessary mapping, e.g. because it only contains line information, we
  16865. // use the best approximation we could find
  16866. if (segment[0] === column || searchStart === searchEnd) {
  16867. if (segment.length == 1)
  16868. return null;
  16869. const source = this.sources[segment[1]];
  16870. if (!source)
  16871. return null;
  16872. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  16873. }
  16874. if (segment[0] > column) {
  16875. searchEnd = m - 1;
  16876. }
  16877. else {
  16878. searchStart = m + 1;
  16879. }
  16880. }
  16881. return null;
  16882. }
  16883. }
  16884. function getLinkMap(warn) {
  16885. return function linkMap(source, map) {
  16886. if (map.mappings) {
  16887. return new Link(map, [source]);
  16888. }
  16889. warn(errorSourcemapBroken(map.plugin));
  16890. return new Link({
  16891. mappings: [],
  16892. names: []
  16893. }, [source]);
  16894. };
  16895. }
  16896. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  16897. let source;
  16898. if (originalSourcemap) {
  16899. const sources = originalSourcemap.sources;
  16900. const sourcesContent = originalSourcemap.sourcesContent || [];
  16901. const directory = node_path.dirname(id) || '.';
  16902. const sourceRoot = originalSourcemap.sourceRoot || '.';
  16903. const baseSources = sources.map((source, index) => new Source(node_path.resolve(directory, sourceRoot, source), sourcesContent[index]));
  16904. source = new Link(originalSourcemap, baseSources);
  16905. }
  16906. else {
  16907. source = new Source(id, originalCode);
  16908. }
  16909. return sourcemapChain.reduce(linkMap, source);
  16910. }
  16911. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  16912. const linkMap = getLinkMap(warn);
  16913. const moduleSources = modules
  16914. .filter(module => !module.excludeFromSourcemap)
  16915. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  16916. const link = new Link(map, moduleSources);
  16917. const source = bundleSourcemapChain.reduce(linkMap, link);
  16918. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  16919. if (file) {
  16920. const directory = node_path.dirname(file);
  16921. sources = sources.map((source) => node_path.relative(directory, source));
  16922. file = node_path.basename(file);
  16923. }
  16924. sourcesContent = (excludeContent ? null : sourcesContent);
  16925. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  16926. }
  16927. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  16928. if (sourcemapChain.length === 0) {
  16929. return originalSourcemap;
  16930. }
  16931. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  16932. const map = source.traceMappings();
  16933. return { version: 3, ...map };
  16934. }
  16935. const createHash = () => node_crypto.createHash('sha256');
  16936. function decodedSourcemap(map) {
  16937. if (!map)
  16938. return null;
  16939. if (typeof map === 'string') {
  16940. map = JSON.parse(map);
  16941. }
  16942. if (map.mappings === '') {
  16943. return {
  16944. mappings: [],
  16945. names: [],
  16946. sources: [],
  16947. version: 3
  16948. };
  16949. }
  16950. const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
  16951. return { ...map, mappings };
  16952. }
  16953. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, onwarn) {
  16954. timeStart('render chunks', 2);
  16955. reserveEntryChunksInBundle(chunks);
  16956. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  16957. timeEnd('render chunks', 2);
  16958. timeStart('transform chunks', 2);
  16959. const chunkGraph = getChunkGraph(chunks);
  16960. const { nonHashedChunksWithPlaceholders, renderedChunksByPlaceholder, hashDependenciesByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, onwarn);
  16961. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, bundle);
  16962. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  16963. timeEnd('transform chunks', 2);
  16964. }
  16965. function reserveEntryChunksInBundle(chunks) {
  16966. for (const chunk of chunks) {
  16967. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  16968. // reserves name in bundle as side effect if it does not contain a hash
  16969. chunk.getPreliminaryFileName();
  16970. }
  16971. }
  16972. }
  16973. function getChunkGraph(chunks) {
  16974. return Object.fromEntries(chunks.map(chunk => {
  16975. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  16976. return [renderedChunkInfo.fileName, renderedChunkInfo];
  16977. }));
  16978. }
  16979. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, onwarn) {
  16980. let map = null;
  16981. const sourcemapChain = [];
  16982. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  16983. if (result == null)
  16984. return code;
  16985. if (typeof result === 'string')
  16986. result = {
  16987. code: result,
  16988. map: undefined
  16989. };
  16990. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  16991. if (result.map !== null) {
  16992. const map = decodedSourcemap(result.map);
  16993. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  16994. }
  16995. return result.code;
  16996. });
  16997. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  16998. if (!compact && code[code.length - 1] !== '\n')
  16999. code += '\n';
  17000. if (sourcemap) {
  17001. timeStart('sourcemaps', 3);
  17002. let resultingFile;
  17003. if (file)
  17004. resultingFile = node_path.resolve(sourcemapFile || file);
  17005. else if (dir)
  17006. resultingFile = node_path.resolve(dir, fileName);
  17007. else
  17008. resultingFile = node_path.resolve(fileName);
  17009. const decodedMap = magicString.generateDecodedMap({});
  17010. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, onwarn);
  17011. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  17012. let sourcePath = map.sources[sourcesIndex];
  17013. const sourcemapPath = `${resultingFile}.map`;
  17014. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  17015. if (typeof ignoreList !== 'boolean') {
  17016. error(errorFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  17017. }
  17018. if (ignoreList) {
  17019. if (map.x_google_ignoreList === undefined) {
  17020. map.x_google_ignoreList = [];
  17021. }
  17022. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  17023. map.x_google_ignoreList.push(sourcesIndex);
  17024. }
  17025. }
  17026. if (sourcemapPathTransform) {
  17027. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  17028. if (typeof sourcePath !== 'string') {
  17029. error(errorFailedValidation(`sourcemapPathTransform function must return a string.`));
  17030. }
  17031. }
  17032. map.sources[sourcesIndex] = normalize(sourcePath);
  17033. }
  17034. timeEnd('sourcemaps', 3);
  17035. }
  17036. return {
  17037. code,
  17038. map
  17039. };
  17040. }
  17041. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, onwarn) {
  17042. const nonHashedChunksWithPlaceholders = [];
  17043. const renderedChunksByPlaceholder = new Map();
  17044. const hashDependenciesByPlaceholder = new Map();
  17045. const placeholders = new Set();
  17046. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  17047. if (hashPlaceholder)
  17048. placeholders.add(hashPlaceholder);
  17049. }
  17050. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, magicString, usedModules }) => {
  17051. const transformedChunk = {
  17052. chunk,
  17053. fileName,
  17054. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, onwarn))
  17055. };
  17056. const { code } = transformedChunk;
  17057. if (hashPlaceholder) {
  17058. // To create a reproducible content-only hash, all placeholders are
  17059. // replaced with the same value before hashing
  17060. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  17061. const hash = createHash().update(transformedCode);
  17062. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  17063. if (pluginHash) {
  17064. augmentation += pluginHash;
  17065. }
  17066. return augmentation;
  17067. });
  17068. if (hashAugmentation) {
  17069. hash.update(hashAugmentation);
  17070. }
  17071. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  17072. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  17073. containedPlaceholders,
  17074. contentHash: hash.digest('hex')
  17075. });
  17076. }
  17077. else {
  17078. nonHashedChunksWithPlaceholders.push(transformedChunk);
  17079. }
  17080. }));
  17081. return {
  17082. hashDependenciesByPlaceholder,
  17083. nonHashedChunksWithPlaceholders,
  17084. renderedChunksByPlaceholder
  17085. };
  17086. }
  17087. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, bundle) {
  17088. const hashesByPlaceholder = new Map();
  17089. for (const [placeholder, { fileName }] of renderedChunksByPlaceholder) {
  17090. let hash = createHash();
  17091. const hashDependencyPlaceholders = new Set([placeholder]);
  17092. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  17093. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  17094. hash.update(contentHash);
  17095. for (const containedPlaceholder of containedPlaceholders) {
  17096. // When looping over a map, setting an entry only causes a new iteration if the key is new
  17097. hashDependencyPlaceholders.add(containedPlaceholder);
  17098. }
  17099. }
  17100. let finalFileName;
  17101. let finalHash;
  17102. do {
  17103. // In case of a hash collision, create a hash of the hash
  17104. if (finalHash) {
  17105. hash = createHash().update(finalHash);
  17106. }
  17107. finalHash = hash.digest('hex').slice(0, placeholder.length);
  17108. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  17109. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  17110. bundle[finalFileName] = FILE_PLACEHOLDER;
  17111. hashesByPlaceholder.set(placeholder, finalHash);
  17112. }
  17113. return hashesByPlaceholder;
  17114. }
  17115. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  17116. for (const { chunk, code, fileName, map } of renderedChunksByPlaceholder.values()) {
  17117. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  17118. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  17119. if (map) {
  17120. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  17121. updatedCode += emitSourceMapAndGetComment(finalFileName, map, pluginDriver, options);
  17122. }
  17123. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, hashesByPlaceholder);
  17124. }
  17125. for (const { chunk, code, fileName, map } of nonHashedChunksWithPlaceholders) {
  17126. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  17127. if (map) {
  17128. updatedCode += emitSourceMapAndGetComment(fileName, map, pluginDriver, options);
  17129. }
  17130. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, hashesByPlaceholder);
  17131. }
  17132. }
  17133. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  17134. let url;
  17135. if (sourcemap === 'inline') {
  17136. url = map.toUrl();
  17137. }
  17138. else {
  17139. const sourcemapFileName = `${node_path.basename(fileName)}.map`;
  17140. url = sourcemapBaseUrl
  17141. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  17142. : sourcemapFileName;
  17143. pluginDriver.emitFile({ fileName: `${fileName}.map`, source: map.toString(), type: 'asset' });
  17144. }
  17145. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  17146. }
  17147. class Bundle {
  17148. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  17149. this.outputOptions = outputOptions;
  17150. this.unsetOptions = unsetOptions;
  17151. this.inputOptions = inputOptions;
  17152. this.pluginDriver = pluginDriver;
  17153. this.graph = graph;
  17154. this.facadeChunkByModule = new Map();
  17155. this.includedNamespaces = new Set();
  17156. }
  17157. async generate(isWrite) {
  17158. timeStart('GENERATE', 1);
  17159. const outputBundleBase = Object.create(null);
  17160. const outputBundle = getOutputBundle(outputBundleBase);
  17161. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  17162. try {
  17163. timeStart('initialize render', 2);
  17164. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  17165. timeEnd('initialize render', 2);
  17166. timeStart('generate chunks', 2);
  17167. const getHashPlaceholder = getHashPlaceholderGenerator();
  17168. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  17169. if (chunks.length > 1) {
  17170. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
  17171. }
  17172. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  17173. for (const chunk of chunks) {
  17174. chunk.generateExports();
  17175. }
  17176. timeEnd('generate chunks', 2);
  17177. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onwarn);
  17178. }
  17179. catch (error_) {
  17180. await this.pluginDriver.hookParallel('renderError', [error_]);
  17181. throw error_;
  17182. }
  17183. removeUnreferencedAssets(outputBundle);
  17184. timeStart('generate bundle', 2);
  17185. await this.pluginDriver.hookSeq('generateBundle', [
  17186. this.outputOptions,
  17187. outputBundle,
  17188. isWrite
  17189. ]);
  17190. this.finaliseAssets(outputBundle);
  17191. timeEnd('generate bundle', 2);
  17192. timeEnd('GENERATE', 1);
  17193. return outputBundleBase;
  17194. }
  17195. async addManualChunks(manualChunks) {
  17196. const manualChunkAliasByEntry = new Map();
  17197. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  17198. alias,
  17199. entries: await this.graph.moduleLoader.addAdditionalModules(files)
  17200. })));
  17201. for (const { alias, entries } of chunkEntries) {
  17202. for (const entry of entries) {
  17203. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  17204. }
  17205. }
  17206. return manualChunkAliasByEntry;
  17207. }
  17208. assignManualChunks(getManualChunk) {
  17209. // eslint-disable-next-line unicorn/prefer-module
  17210. const manualChunkAliasesWithEntry = [];
  17211. const manualChunksApi = {
  17212. getModuleIds: () => this.graph.modulesById.keys(),
  17213. getModuleInfo: this.graph.getModuleInfo
  17214. };
  17215. for (const module of this.graph.modulesById.values()) {
  17216. if (module instanceof Module) {
  17217. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  17218. if (typeof manualChunkAlias === 'string') {
  17219. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  17220. }
  17221. }
  17222. }
  17223. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  17224. const manualChunkAliasByEntry = new Map();
  17225. for (const [alias, module] of manualChunkAliasesWithEntry) {
  17226. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  17227. }
  17228. return manualChunkAliasByEntry;
  17229. }
  17230. finaliseAssets(bundle) {
  17231. if (this.outputOptions.validate) {
  17232. for (const file of Object.values(bundle)) {
  17233. if ('code' in file) {
  17234. try {
  17235. this.graph.contextParse(file.code, {
  17236. ecmaVersion: 'latest'
  17237. });
  17238. }
  17239. catch (error_) {
  17240. this.inputOptions.onwarn(errorChunkInvalid(file, error_));
  17241. }
  17242. }
  17243. }
  17244. }
  17245. this.pluginDriver.finaliseAssets();
  17246. }
  17247. async generateChunks(bundle, getHashPlaceholder) {
  17248. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  17249. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  17250. ? await this.addManualChunks(manualChunks)
  17251. : this.assignManualChunks(manualChunks);
  17252. const snippets = getGenerateCodeSnippets(this.outputOptions);
  17253. const includedModules = getIncludedModules(this.graph.modulesById);
  17254. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  17255. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  17256. const chunks = [];
  17257. const chunkByModule = new Map();
  17258. for (const { alias, modules } of inlineDynamicImports
  17259. ? [{ alias: null, modules: includedModules }]
  17260. : preserveModules
  17261. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  17262. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize)) {
  17263. sortByExecutionOrder(modules);
  17264. 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);
  17265. chunks.push(chunk);
  17266. }
  17267. for (const chunk of chunks) {
  17268. chunk.link();
  17269. }
  17270. const facades = [];
  17271. for (const chunk of chunks) {
  17272. facades.push(...chunk.generateFacades());
  17273. }
  17274. return [...chunks, ...facades];
  17275. }
  17276. }
  17277. function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
  17278. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  17279. return error(errorInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  17280. if (typeof outputOptions.file === 'string')
  17281. 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'));
  17282. if (outputOptions.sourcemapFile)
  17283. return error(errorInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  17284. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  17285. 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'));
  17286. }
  17287. function getIncludedModules(modulesById) {
  17288. const includedModules = [];
  17289. for (const module of modulesById.values()) {
  17290. if (module instanceof Module &&
  17291. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  17292. includedModules.push(module);
  17293. }
  17294. }
  17295. return includedModules;
  17296. }
  17297. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  17298. const absoluteEntryModulePaths = [];
  17299. for (const module of includedModules) {
  17300. if ((module.info.isEntry || preserveModules) && isAbsolute(module.id)) {
  17301. absoluteEntryModulePaths.push(module.id);
  17302. }
  17303. }
  17304. return absoluteEntryModulePaths;
  17305. }
  17306. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  17307. const externalChunkByModule = new Map();
  17308. for (const module of modulesById.values()) {
  17309. if (module instanceof ExternalModule) {
  17310. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  17311. }
  17312. }
  17313. return externalChunkByModule;
  17314. }
  17315. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  17316. const existingAlias = manualChunkAliasByEntry.get(module);
  17317. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  17318. return error(errorCannotAssignModuleToChunk(module.id, alias, existingAlias));
  17319. }
  17320. manualChunkAliasByEntry.set(module, alias);
  17321. }
  17322. // This file was generated. Do not modify manually!
  17323. 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, 81, 2, 71, 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, 3, 0, 158, 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, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 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, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  17324. // This file was generated. Do not modify manually!
  17325. 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, 20, 1, 64, 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, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 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, 16, 0, 30, 2, 3, 0, 15, 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, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 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, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191];
  17326. // This file was generated. Do not modify manually!
  17327. 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\u0cf3\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-\u0ece\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";
  17328. // This file was generated. Do not modify manually!
  17329. 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";
  17330. // These are a run-length and offset encoded representation of the
  17331. // Reserved word lists for various dialects of the language
  17332. var reservedWords = {
  17333. 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",
  17334. 5: "class enum extends super const export import",
  17335. 6: "enum",
  17336. strict: "implements interface let package private protected public static yield",
  17337. strictBind: "eval arguments"
  17338. };
  17339. // And the keywords
  17340. 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";
  17341. var keywords$1 = {
  17342. 5: ecma5AndLessKeywords,
  17343. "5module": ecma5AndLessKeywords + " export import",
  17344. 6: ecma5AndLessKeywords + " const class extends export import super"
  17345. };
  17346. var keywordRelationalOperator = /^in(stanceof)?$/;
  17347. // ## Character categories
  17348. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  17349. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  17350. // This has a complexity linear to the value of the code. The
  17351. // assumption is that looking up astral identifier characters is
  17352. // rare.
  17353. function isInAstralSet(code, set) {
  17354. var pos = 0x10000;
  17355. for (var i = 0; i < set.length; i += 2) {
  17356. pos += set[i];
  17357. if (pos > code) { return false }
  17358. pos += set[i + 1];
  17359. if (pos >= code) { return true }
  17360. }
  17361. return false
  17362. }
  17363. // Test whether a given character code starts an identifier.
  17364. function isIdentifierStart(code, astral) {
  17365. if (code < 65) { return code === 36 }
  17366. if (code < 91) { return true }
  17367. if (code < 97) { return code === 95 }
  17368. if (code < 123) { return true }
  17369. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  17370. if (astral === false) { return false }
  17371. return isInAstralSet(code, astralIdentifierStartCodes)
  17372. }
  17373. // Test whether a given character is part of an identifier.
  17374. function isIdentifierChar(code, astral) {
  17375. if (code < 48) { return code === 36 }
  17376. if (code < 58) { return true }
  17377. if (code < 65) { return false }
  17378. if (code < 91) { return true }
  17379. if (code < 97) { return code === 95 }
  17380. if (code < 123) { return true }
  17381. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  17382. if (astral === false) { return false }
  17383. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  17384. }
  17385. // ## Token types
  17386. // The assignment of fine-grained, information-carrying type objects
  17387. // allows the tokenizer to store the information it has about a
  17388. // token in a way that is very cheap for the parser to look up.
  17389. // All token type variables start with an underscore, to make them
  17390. // easy to recognize.
  17391. // The `beforeExpr` property is used to disambiguate between regular
  17392. // expressions and divisions. It is set on all token types that can
  17393. // be followed by an expression (thus, a slash after them would be a
  17394. // regular expression).
  17395. //
  17396. // The `startsExpr` property is used to check if the token ends a
  17397. // `yield` expression. It is set on all token types that either can
  17398. // directly start an expression (like a quotation mark) or can
  17399. // continue an expression (like the body of a string).
  17400. //
  17401. // `isLoop` marks a keyword as starting a loop, which is important
  17402. // to know when parsing a label, in order to allow or disallow
  17403. // continue jumps to that label.
  17404. var TokenType = function TokenType(label, conf) {
  17405. if ( conf === void 0 ) conf = {};
  17406. this.label = label;
  17407. this.keyword = conf.keyword;
  17408. this.beforeExpr = !!conf.beforeExpr;
  17409. this.startsExpr = !!conf.startsExpr;
  17410. this.isLoop = !!conf.isLoop;
  17411. this.isAssign = !!conf.isAssign;
  17412. this.prefix = !!conf.prefix;
  17413. this.postfix = !!conf.postfix;
  17414. this.binop = conf.binop || null;
  17415. this.updateContext = null;
  17416. };
  17417. function binop(name, prec) {
  17418. return new TokenType(name, {beforeExpr: true, binop: prec})
  17419. }
  17420. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  17421. // Map keyword names to token types.
  17422. var keywords = {};
  17423. // Succinct definitions of keyword token types
  17424. function kw(name, options) {
  17425. if ( options === void 0 ) options = {};
  17426. options.keyword = name;
  17427. return keywords[name] = new TokenType(name, options)
  17428. }
  17429. var types$1 = {
  17430. num: new TokenType("num", startsExpr),
  17431. regexp: new TokenType("regexp", startsExpr),
  17432. string: new TokenType("string", startsExpr),
  17433. name: new TokenType("name", startsExpr),
  17434. privateId: new TokenType("privateId", startsExpr),
  17435. eof: new TokenType("eof"),
  17436. // Punctuation token types.
  17437. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  17438. bracketR: new TokenType("]"),
  17439. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  17440. braceR: new TokenType("}"),
  17441. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  17442. parenR: new TokenType(")"),
  17443. comma: new TokenType(",", beforeExpr),
  17444. semi: new TokenType(";", beforeExpr),
  17445. colon: new TokenType(":", beforeExpr),
  17446. dot: new TokenType("."),
  17447. question: new TokenType("?", beforeExpr),
  17448. questionDot: new TokenType("?."),
  17449. arrow: new TokenType("=>", beforeExpr),
  17450. template: new TokenType("template"),
  17451. invalidTemplate: new TokenType("invalidTemplate"),
  17452. ellipsis: new TokenType("...", beforeExpr),
  17453. backQuote: new TokenType("`", startsExpr),
  17454. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  17455. // Operators. These carry several kinds of properties to help the
  17456. // parser use them properly (the presence of these properties is
  17457. // what categorizes them as operators).
  17458. //
  17459. // `binop`, when present, specifies that this operator is a binary
  17460. // operator, and will refer to its precedence.
  17461. //
  17462. // `prefix` and `postfix` mark the operator as a prefix or postfix
  17463. // unary operator.
  17464. //
  17465. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  17466. // binary operators with a very low precedence, that should result
  17467. // in AssignmentExpression nodes.
  17468. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  17469. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  17470. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  17471. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  17472. logicalOR: binop("||", 1),
  17473. logicalAND: binop("&&", 2),
  17474. bitwiseOR: binop("|", 3),
  17475. bitwiseXOR: binop("^", 4),
  17476. bitwiseAND: binop("&", 5),
  17477. equality: binop("==/!=/===/!==", 6),
  17478. relational: binop("</>/<=/>=", 7),
  17479. bitShift: binop("<</>>/>>>", 8),
  17480. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  17481. modulo: binop("%", 10),
  17482. star: binop("*", 10),
  17483. slash: binop("/", 10),
  17484. starstar: new TokenType("**", {beforeExpr: true}),
  17485. coalesce: binop("??", 1),
  17486. // Keyword token types.
  17487. _break: kw("break"),
  17488. _case: kw("case", beforeExpr),
  17489. _catch: kw("catch"),
  17490. _continue: kw("continue"),
  17491. _debugger: kw("debugger"),
  17492. _default: kw("default", beforeExpr),
  17493. _do: kw("do", {isLoop: true, beforeExpr: true}),
  17494. _else: kw("else", beforeExpr),
  17495. _finally: kw("finally"),
  17496. _for: kw("for", {isLoop: true}),
  17497. _function: kw("function", startsExpr),
  17498. _if: kw("if"),
  17499. _return: kw("return", beforeExpr),
  17500. _switch: kw("switch"),
  17501. _throw: kw("throw", beforeExpr),
  17502. _try: kw("try"),
  17503. _var: kw("var"),
  17504. _const: kw("const"),
  17505. _while: kw("while", {isLoop: true}),
  17506. _with: kw("with"),
  17507. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  17508. _this: kw("this", startsExpr),
  17509. _super: kw("super", startsExpr),
  17510. _class: kw("class", startsExpr),
  17511. _extends: kw("extends", beforeExpr),
  17512. _export: kw("export"),
  17513. _import: kw("import", startsExpr),
  17514. _null: kw("null", startsExpr),
  17515. _true: kw("true", startsExpr),
  17516. _false: kw("false", startsExpr),
  17517. _in: kw("in", {beforeExpr: true, binop: 7}),
  17518. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  17519. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  17520. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  17521. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  17522. };
  17523. // Matches a whole line break (where CRLF is considered a single
  17524. // line break). Used to count lines.
  17525. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  17526. var lineBreakG = new RegExp(lineBreak.source, "g");
  17527. function isNewLine(code) {
  17528. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  17529. }
  17530. function nextLineBreak(code, from, end) {
  17531. if ( end === void 0 ) end = code.length;
  17532. for (var i = from; i < end; i++) {
  17533. var next = code.charCodeAt(i);
  17534. if (isNewLine(next))
  17535. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  17536. }
  17537. return -1
  17538. }
  17539. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  17540. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  17541. var ref = Object.prototype;
  17542. var hasOwnProperty = ref.hasOwnProperty;
  17543. var toString = ref.toString;
  17544. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  17545. hasOwnProperty.call(obj, propName)
  17546. ); });
  17547. var isArray = Array.isArray || (function (obj) { return (
  17548. toString.call(obj) === "[object Array]"
  17549. ); });
  17550. function wordsRegexp(words) {
  17551. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  17552. }
  17553. function codePointToString(code) {
  17554. // UTF-16 Decoding
  17555. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  17556. code -= 0x10000;
  17557. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  17558. }
  17559. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  17560. // These are used when `options.locations` is on, for the
  17561. // `startLoc` and `endLoc` properties.
  17562. var Position = function Position(line, col) {
  17563. this.line = line;
  17564. this.column = col;
  17565. };
  17566. Position.prototype.offset = function offset (n) {
  17567. return new Position(this.line, this.column + n)
  17568. };
  17569. var SourceLocation = function SourceLocation(p, start, end) {
  17570. this.start = start;
  17571. this.end = end;
  17572. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  17573. };
  17574. // The `getLineInfo` function is mostly useful when the
  17575. // `locations` option is off (for performance reasons) and you
  17576. // want to find the line/column position for a given character
  17577. // offset. `input` should be the code string that the offset refers
  17578. // into.
  17579. function getLineInfo(input, offset) {
  17580. for (var line = 1, cur = 0;;) {
  17581. var nextBreak = nextLineBreak(input, cur, offset);
  17582. if (nextBreak < 0) { return new Position(line, offset - cur) }
  17583. ++line;
  17584. cur = nextBreak;
  17585. }
  17586. }
  17587. // A second argument must be given to configure the parser process.
  17588. // These options are recognized (only `ecmaVersion` is required):
  17589. var defaultOptions = {
  17590. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  17591. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  17592. // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
  17593. // (the latest version the library supports). This influences
  17594. // support for strict mode, the set of reserved words, and support
  17595. // for new syntax features.
  17596. ecmaVersion: null,
  17597. // `sourceType` indicates the mode the code should be parsed in.
  17598. // Can be either `"script"` or `"module"`. This influences global
  17599. // strict mode and parsing of `import` and `export` declarations.
  17600. sourceType: "script",
  17601. // `onInsertedSemicolon` can be a callback that will be called
  17602. // when a semicolon is automatically inserted. It will be passed
  17603. // the position of the comma as an offset, and if `locations` is
  17604. // enabled, it is given the location as a `{line, column}` object
  17605. // as second argument.
  17606. onInsertedSemicolon: null,
  17607. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  17608. // trailing commas.
  17609. onTrailingComma: null,
  17610. // By default, reserved words are only enforced if ecmaVersion >= 5.
  17611. // Set `allowReserved` to a boolean value to explicitly turn this on
  17612. // an off. When this option has the value "never", reserved words
  17613. // and keywords can also not be used as property names.
  17614. allowReserved: null,
  17615. // When enabled, a return at the top level is not considered an
  17616. // error.
  17617. allowReturnOutsideFunction: false,
  17618. // When enabled, import/export statements are not constrained to
  17619. // appearing at the top of the program, and an import.meta expression
  17620. // in a script isn't considered an error.
  17621. allowImportExportEverywhere: false,
  17622. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  17623. // When enabled, await identifiers are allowed to appear at the top-level scope,
  17624. // but they are still not allowed in non-async functions.
  17625. allowAwaitOutsideFunction: null,
  17626. // When enabled, super identifiers are not constrained to
  17627. // appearing in methods and do not raise an error when they appear elsewhere.
  17628. allowSuperOutsideMethod: null,
  17629. // When enabled, hashbang directive in the beginning of file is
  17630. // allowed and treated as a line comment. Enabled by default when
  17631. // `ecmaVersion` >= 2023.
  17632. allowHashBang: false,
  17633. // When `locations` is on, `loc` properties holding objects with
  17634. // `start` and `end` properties in `{line, column}` form (with
  17635. // line being 1-based and column 0-based) will be attached to the
  17636. // nodes.
  17637. locations: false,
  17638. // A function can be passed as `onToken` option, which will
  17639. // cause Acorn to call that function with object in the same
  17640. // format as tokens returned from `tokenizer().getToken()`. Note
  17641. // that you are not allowed to call the parser from the
  17642. // callback—that will corrupt its internal state.
  17643. onToken: null,
  17644. // A function can be passed as `onComment` option, which will
  17645. // cause Acorn to call that function with `(block, text, start,
  17646. // end)` parameters whenever a comment is skipped. `block` is a
  17647. // boolean indicating whether this is a block (`/* */`) comment,
  17648. // `text` is the content of the comment, and `start` and `end` are
  17649. // character offsets that denote the start and end of the comment.
  17650. // When the `locations` option is on, two more parameters are
  17651. // passed, the full `{line, column}` locations of the start and
  17652. // end of the comments. Note that you are not allowed to call the
  17653. // parser from the callback—that will corrupt its internal state.
  17654. onComment: null,
  17655. // Nodes have their start and end characters offsets recorded in
  17656. // `start` and `end` properties (directly on the node, rather than
  17657. // the `loc` object, which holds line/column data. To also add a
  17658. // [semi-standardized][range] `range` property holding a `[start,
  17659. // end]` array with the same numbers, set the `ranges` option to
  17660. // `true`.
  17661. //
  17662. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  17663. ranges: false,
  17664. // It is possible to parse multiple files into a single AST by
  17665. // passing the tree produced by parsing the first file as
  17666. // `program` option in subsequent parses. This will add the
  17667. // toplevel forms of the parsed file to the `Program` (top) node
  17668. // of an existing parse tree.
  17669. program: null,
  17670. // When `locations` is on, you can pass this to record the source
  17671. // file in every node's `loc` object.
  17672. sourceFile: null,
  17673. // This value, if given, is stored in every node, whether
  17674. // `locations` is on or off.
  17675. directSourceFile: null,
  17676. // When enabled, parenthesized expressions are represented by
  17677. // (non-standard) ParenthesizedExpression nodes
  17678. preserveParens: false
  17679. };
  17680. // Interpret and default an options object
  17681. var warnedAboutEcmaVersion = false;
  17682. function getOptions(opts) {
  17683. var options = {};
  17684. for (var opt in defaultOptions)
  17685. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  17686. if (options.ecmaVersion === "latest") {
  17687. options.ecmaVersion = 1e8;
  17688. } else if (options.ecmaVersion == null) {
  17689. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  17690. warnedAboutEcmaVersion = true;
  17691. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  17692. }
  17693. options.ecmaVersion = 11;
  17694. } else if (options.ecmaVersion >= 2015) {
  17695. options.ecmaVersion -= 2009;
  17696. }
  17697. if (options.allowReserved == null)
  17698. { options.allowReserved = options.ecmaVersion < 5; }
  17699. if (!opts || opts.allowHashBang == null)
  17700. { options.allowHashBang = options.ecmaVersion >= 14; }
  17701. if (isArray(options.onToken)) {
  17702. var tokens = options.onToken;
  17703. options.onToken = function (token) { return tokens.push(token); };
  17704. }
  17705. if (isArray(options.onComment))
  17706. { options.onComment = pushComment(options, options.onComment); }
  17707. return options
  17708. }
  17709. function pushComment(options, array) {
  17710. return function(block, text, start, end, startLoc, endLoc) {
  17711. var comment = {
  17712. type: block ? "Block" : "Line",
  17713. value: text,
  17714. start: start,
  17715. end: end
  17716. };
  17717. if (options.locations)
  17718. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  17719. if (options.ranges)
  17720. { comment.range = [start, end]; }
  17721. array.push(comment);
  17722. }
  17723. }
  17724. // Each scope gets a bitset that may contain these flags
  17725. var
  17726. SCOPE_TOP = 1,
  17727. SCOPE_FUNCTION = 2,
  17728. SCOPE_ASYNC = 4,
  17729. SCOPE_GENERATOR = 8,
  17730. SCOPE_ARROW = 16,
  17731. SCOPE_SIMPLE_CATCH = 32,
  17732. SCOPE_SUPER = 64,
  17733. SCOPE_DIRECT_SUPER = 128,
  17734. SCOPE_CLASS_STATIC_BLOCK = 256,
  17735. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  17736. function functionFlags(async, generator) {
  17737. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  17738. }
  17739. // Used in checkLVal* and declareName to determine the type of a binding
  17740. var
  17741. BIND_NONE = 0, // Not a binding
  17742. BIND_VAR = 1, // Var-style binding
  17743. BIND_LEXICAL = 2, // Let- or const-style binding
  17744. BIND_FUNCTION = 3, // Function declaration
  17745. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  17746. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  17747. var Parser = function Parser(options, input, startPos) {
  17748. this.options = options = getOptions(options);
  17749. this.sourceFile = options.sourceFile;
  17750. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  17751. var reserved = "";
  17752. if (options.allowReserved !== true) {
  17753. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  17754. if (options.sourceType === "module") { reserved += " await"; }
  17755. }
  17756. this.reservedWords = wordsRegexp(reserved);
  17757. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  17758. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  17759. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  17760. this.input = String(input);
  17761. // Used to signal to callers of `readWord1` whether the word
  17762. // contained any escape sequences. This is needed because words with
  17763. // escape sequences must not be interpreted as keywords.
  17764. this.containsEsc = false;
  17765. // Set up token state
  17766. // The current position of the tokenizer in the input.
  17767. if (startPos) {
  17768. this.pos = startPos;
  17769. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  17770. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  17771. } else {
  17772. this.pos = this.lineStart = 0;
  17773. this.curLine = 1;
  17774. }
  17775. // Properties of the current token:
  17776. // Its type
  17777. this.type = types$1.eof;
  17778. // For tokens that include more information than their type, the value
  17779. this.value = null;
  17780. // Its start and end offset
  17781. this.start = this.end = this.pos;
  17782. // And, if locations are used, the {line, column} object
  17783. // corresponding to those offsets
  17784. this.startLoc = this.endLoc = this.curPosition();
  17785. // Position information for the previous token
  17786. this.lastTokEndLoc = this.lastTokStartLoc = null;
  17787. this.lastTokStart = this.lastTokEnd = this.pos;
  17788. // The context stack is used to superficially track syntactic
  17789. // context to predict whether a regular expression is allowed in a
  17790. // given position.
  17791. this.context = this.initialContext();
  17792. this.exprAllowed = true;
  17793. // Figure out if it's a module code.
  17794. this.inModule = options.sourceType === "module";
  17795. this.strict = this.inModule || this.strictDirective(this.pos);
  17796. // Used to signify the start of a potential arrow function
  17797. this.potentialArrowAt = -1;
  17798. this.potentialArrowInForAwait = false;
  17799. // Positions to delayed-check that yield/await does not exist in default parameters.
  17800. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  17801. // Labels in scope.
  17802. this.labels = [];
  17803. // Thus-far undefined exports.
  17804. this.undefinedExports = Object.create(null);
  17805. // If enabled, skip leading hashbang line.
  17806. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  17807. { this.skipLineComment(2); }
  17808. // Scope tracking for duplicate variable names (see scope.js)
  17809. this.scopeStack = [];
  17810. this.enterScope(SCOPE_TOP);
  17811. // For RegExp validation
  17812. this.regexpState = null;
  17813. // The stack of private names.
  17814. // Each element has two properties: 'declared' and 'used'.
  17815. // When it exited from the outermost class definition, all used private names must be declared.
  17816. this.privateNameStack = [];
  17817. };
  17818. 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 } };
  17819. Parser.prototype.parse = function parse () {
  17820. var node = this.options.program || this.startNode();
  17821. this.nextToken();
  17822. return this.parseTopLevel(node)
  17823. };
  17824. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  17825. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  17826. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  17827. prototypeAccessors.canAwait.get = function () {
  17828. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  17829. var scope = this.scopeStack[i];
  17830. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  17831. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  17832. }
  17833. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  17834. };
  17835. prototypeAccessors.allowSuper.get = function () {
  17836. var ref = this.currentThisScope();
  17837. var flags = ref.flags;
  17838. var inClassFieldInit = ref.inClassFieldInit;
  17839. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  17840. };
  17841. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  17842. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  17843. prototypeAccessors.allowNewDotTarget.get = function () {
  17844. var ref = this.currentThisScope();
  17845. var flags = ref.flags;
  17846. var inClassFieldInit = ref.inClassFieldInit;
  17847. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  17848. };
  17849. prototypeAccessors.inClassStaticBlock.get = function () {
  17850. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  17851. };
  17852. Parser.extend = function extend () {
  17853. var plugins = [], len = arguments.length;
  17854. while ( len-- ) plugins[ len ] = arguments[ len ];
  17855. var cls = this;
  17856. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  17857. return cls
  17858. };
  17859. Parser.parse = function parse (input, options) {
  17860. return new this(options, input).parse()
  17861. };
  17862. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  17863. var parser = new this(options, input, pos);
  17864. parser.nextToken();
  17865. return parser.parseExpression()
  17866. };
  17867. Parser.tokenizer = function tokenizer (input, options) {
  17868. return new this(options, input)
  17869. };
  17870. Object.defineProperties( Parser.prototype, prototypeAccessors );
  17871. var pp$9 = Parser.prototype;
  17872. // ## Parser utilities
  17873. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  17874. pp$9.strictDirective = function(start) {
  17875. if (this.options.ecmaVersion < 5) { return false }
  17876. for (;;) {
  17877. // Try to find string literal.
  17878. skipWhiteSpace.lastIndex = start;
  17879. start += skipWhiteSpace.exec(this.input)[0].length;
  17880. var match = literal.exec(this.input.slice(start));
  17881. if (!match) { return false }
  17882. if ((match[1] || match[2]) === "use strict") {
  17883. skipWhiteSpace.lastIndex = start + match[0].length;
  17884. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  17885. var next = this.input.charAt(end);
  17886. return next === ";" || next === "}" ||
  17887. (lineBreak.test(spaceAfter[0]) &&
  17888. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  17889. }
  17890. start += match[0].length;
  17891. // Skip semicolon, if any.
  17892. skipWhiteSpace.lastIndex = start;
  17893. start += skipWhiteSpace.exec(this.input)[0].length;
  17894. if (this.input[start] === ";")
  17895. { start++; }
  17896. }
  17897. };
  17898. // Predicate that tests whether the next token is of the given
  17899. // type, and if yes, consumes it as a side effect.
  17900. pp$9.eat = function(type) {
  17901. if (this.type === type) {
  17902. this.next();
  17903. return true
  17904. } else {
  17905. return false
  17906. }
  17907. };
  17908. // Tests whether parsed token is a contextual keyword.
  17909. pp$9.isContextual = function(name) {
  17910. return this.type === types$1.name && this.value === name && !this.containsEsc
  17911. };
  17912. // Consumes contextual keyword if possible.
  17913. pp$9.eatContextual = function(name) {
  17914. if (!this.isContextual(name)) { return false }
  17915. this.next();
  17916. return true
  17917. };
  17918. // Asserts that following token is given contextual keyword.
  17919. pp$9.expectContextual = function(name) {
  17920. if (!this.eatContextual(name)) { this.unexpected(); }
  17921. };
  17922. // Test whether a semicolon can be inserted at the current position.
  17923. pp$9.canInsertSemicolon = function() {
  17924. return this.type === types$1.eof ||
  17925. this.type === types$1.braceR ||
  17926. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  17927. };
  17928. pp$9.insertSemicolon = function() {
  17929. if (this.canInsertSemicolon()) {
  17930. if (this.options.onInsertedSemicolon)
  17931. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  17932. return true
  17933. }
  17934. };
  17935. // Consume a semicolon, or, failing that, see if we are allowed to
  17936. // pretend that there is a semicolon at this position.
  17937. pp$9.semicolon = function() {
  17938. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  17939. };
  17940. pp$9.afterTrailingComma = function(tokType, notNext) {
  17941. if (this.type === tokType) {
  17942. if (this.options.onTrailingComma)
  17943. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  17944. if (!notNext)
  17945. { this.next(); }
  17946. return true
  17947. }
  17948. };
  17949. // Expect a token of a given type. If found, consume it, otherwise,
  17950. // raise an unexpected token error.
  17951. pp$9.expect = function(type) {
  17952. this.eat(type) || this.unexpected();
  17953. };
  17954. // Raise an unexpected token error.
  17955. pp$9.unexpected = function(pos) {
  17956. this.raise(pos != null ? pos : this.start, "Unexpected token");
  17957. };
  17958. var DestructuringErrors = function DestructuringErrors() {
  17959. this.shorthandAssign =
  17960. this.trailingComma =
  17961. this.parenthesizedAssign =
  17962. this.parenthesizedBind =
  17963. this.doubleProto =
  17964. -1;
  17965. };
  17966. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  17967. if (!refDestructuringErrors) { return }
  17968. if (refDestructuringErrors.trailingComma > -1)
  17969. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  17970. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  17971. if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
  17972. };
  17973. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  17974. if (!refDestructuringErrors) { return false }
  17975. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  17976. var doubleProto = refDestructuringErrors.doubleProto;
  17977. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  17978. if (shorthandAssign >= 0)
  17979. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  17980. if (doubleProto >= 0)
  17981. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  17982. };
  17983. pp$9.checkYieldAwaitInDefaultParams = function() {
  17984. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  17985. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  17986. if (this.awaitPos)
  17987. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  17988. };
  17989. pp$9.isSimpleAssignTarget = function(expr) {
  17990. if (expr.type === "ParenthesizedExpression")
  17991. { return this.isSimpleAssignTarget(expr.expression) }
  17992. return expr.type === "Identifier" || expr.type === "MemberExpression"
  17993. };
  17994. var pp$8 = Parser.prototype;
  17995. // ### Statement parsing
  17996. // Parse a program. Initializes the parser, reads any number of
  17997. // statements, and wraps them in a Program node. Optionally takes a
  17998. // `program` argument. If present, the statements will be appended
  17999. // to its body instead of creating a new node.
  18000. pp$8.parseTopLevel = function(node) {
  18001. var exports = Object.create(null);
  18002. if (!node.body) { node.body = []; }
  18003. while (this.type !== types$1.eof) {
  18004. var stmt = this.parseStatement(null, true, exports);
  18005. node.body.push(stmt);
  18006. }
  18007. if (this.inModule)
  18008. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  18009. {
  18010. var name = list[i];
  18011. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  18012. } }
  18013. this.adaptDirectivePrologue(node.body);
  18014. this.next();
  18015. node.sourceType = this.options.sourceType;
  18016. return this.finishNode(node, "Program")
  18017. };
  18018. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  18019. pp$8.isLet = function(context) {
  18020. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  18021. skipWhiteSpace.lastIndex = this.pos;
  18022. var skip = skipWhiteSpace.exec(this.input);
  18023. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  18024. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  18025. // Statement) is allowed here. If context is not empty then only a Statement
  18026. // is allowed. However, `let [` is an explicit negative lookahead for
  18027. // ExpressionStatement, so special-case it first.
  18028. if (nextCh === 91 || nextCh === 92) { return true } // '[', '/'
  18029. if (context) { return false }
  18030. if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral
  18031. if (isIdentifierStart(nextCh, true)) {
  18032. var pos = next + 1;
  18033. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  18034. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  18035. var ident = this.input.slice(next, pos);
  18036. if (!keywordRelationalOperator.test(ident)) { return true }
  18037. }
  18038. return false
  18039. };
  18040. // check 'async [no LineTerminator here] function'
  18041. // - 'async /*foo*/ function' is OK.
  18042. // - 'async /*\n*/ function' is invalid.
  18043. pp$8.isAsyncFunction = function() {
  18044. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  18045. { return false }
  18046. skipWhiteSpace.lastIndex = this.pos;
  18047. var skip = skipWhiteSpace.exec(this.input);
  18048. var next = this.pos + skip[0].length, after;
  18049. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  18050. this.input.slice(next, next + 8) === "function" &&
  18051. (next + 8 === this.input.length ||
  18052. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  18053. };
  18054. // Parse a single statement.
  18055. //
  18056. // If expecting a statement and finding a slash operator, parse a
  18057. // regular expression literal. This is to handle cases like
  18058. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  18059. // does not help.
  18060. pp$8.parseStatement = function(context, topLevel, exports) {
  18061. var starttype = this.type, node = this.startNode(), kind;
  18062. if (this.isLet(context)) {
  18063. starttype = types$1._var;
  18064. kind = "let";
  18065. }
  18066. // Most types of statements are recognized by the keyword they
  18067. // start with. Many are trivial to parse, some require a bit of
  18068. // complexity.
  18069. switch (starttype) {
  18070. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  18071. case types$1._debugger: return this.parseDebuggerStatement(node)
  18072. case types$1._do: return this.parseDoStatement(node)
  18073. case types$1._for: return this.parseForStatement(node)
  18074. case types$1._function:
  18075. // Function as sole body of either an if statement or a labeled statement
  18076. // works, but not when it is part of a labeled statement that is the sole
  18077. // body of an if statement.
  18078. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  18079. return this.parseFunctionStatement(node, false, !context)
  18080. case types$1._class:
  18081. if (context) { this.unexpected(); }
  18082. return this.parseClass(node, true)
  18083. case types$1._if: return this.parseIfStatement(node)
  18084. case types$1._return: return this.parseReturnStatement(node)
  18085. case types$1._switch: return this.parseSwitchStatement(node)
  18086. case types$1._throw: return this.parseThrowStatement(node)
  18087. case types$1._try: return this.parseTryStatement(node)
  18088. case types$1._const: case types$1._var:
  18089. kind = kind || this.value;
  18090. if (context && kind !== "var") { this.unexpected(); }
  18091. return this.parseVarStatement(node, kind)
  18092. case types$1._while: return this.parseWhileStatement(node)
  18093. case types$1._with: return this.parseWithStatement(node)
  18094. case types$1.braceL: return this.parseBlock(true, node)
  18095. case types$1.semi: return this.parseEmptyStatement(node)
  18096. case types$1._export:
  18097. case types$1._import:
  18098. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  18099. skipWhiteSpace.lastIndex = this.pos;
  18100. var skip = skipWhiteSpace.exec(this.input);
  18101. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  18102. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  18103. { return this.parseExpressionStatement(node, this.parseExpression()) }
  18104. }
  18105. if (!this.options.allowImportExportEverywhere) {
  18106. if (!topLevel)
  18107. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  18108. if (!this.inModule)
  18109. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  18110. }
  18111. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  18112. // If the statement does not start with a statement keyword or a
  18113. // brace, it's an ExpressionStatement or LabeledStatement. We
  18114. // simply start parsing an expression, and afterwards, if the
  18115. // next token is a colon and the expression was a simple
  18116. // Identifier node, we switch to interpreting it as a label.
  18117. default:
  18118. if (this.isAsyncFunction()) {
  18119. if (context) { this.unexpected(); }
  18120. this.next();
  18121. return this.parseFunctionStatement(node, true, !context)
  18122. }
  18123. var maybeName = this.value, expr = this.parseExpression();
  18124. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  18125. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  18126. else { return this.parseExpressionStatement(node, expr) }
  18127. }
  18128. };
  18129. pp$8.parseBreakContinueStatement = function(node, keyword) {
  18130. var isBreak = keyword === "break";
  18131. this.next();
  18132. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  18133. else if (this.type !== types$1.name) { this.unexpected(); }
  18134. else {
  18135. node.label = this.parseIdent();
  18136. this.semicolon();
  18137. }
  18138. // Verify that there is an actual destination to break or
  18139. // continue to.
  18140. var i = 0;
  18141. for (; i < this.labels.length; ++i) {
  18142. var lab = this.labels[i];
  18143. if (node.label == null || lab.name === node.label.name) {
  18144. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  18145. if (node.label && isBreak) { break }
  18146. }
  18147. }
  18148. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  18149. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  18150. };
  18151. pp$8.parseDebuggerStatement = function(node) {
  18152. this.next();
  18153. this.semicolon();
  18154. return this.finishNode(node, "DebuggerStatement")
  18155. };
  18156. pp$8.parseDoStatement = function(node) {
  18157. this.next();
  18158. this.labels.push(loopLabel);
  18159. node.body = this.parseStatement("do");
  18160. this.labels.pop();
  18161. this.expect(types$1._while);
  18162. node.test = this.parseParenExpression();
  18163. if (this.options.ecmaVersion >= 6)
  18164. { this.eat(types$1.semi); }
  18165. else
  18166. { this.semicolon(); }
  18167. return this.finishNode(node, "DoWhileStatement")
  18168. };
  18169. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  18170. // loop is non-trivial. Basically, we have to parse the init `var`
  18171. // statement or expression, disallowing the `in` operator (see
  18172. // the second parameter to `parseExpression`), and then check
  18173. // whether the next token is `in` or `of`. When there is no init
  18174. // part (semicolon immediately after the opening parenthesis), it
  18175. // is a regular `for` loop.
  18176. pp$8.parseForStatement = function(node) {
  18177. this.next();
  18178. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  18179. this.labels.push(loopLabel);
  18180. this.enterScope(0);
  18181. this.expect(types$1.parenL);
  18182. if (this.type === types$1.semi) {
  18183. if (awaitAt > -1) { this.unexpected(awaitAt); }
  18184. return this.parseFor(node, null)
  18185. }
  18186. var isLet = this.isLet();
  18187. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  18188. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  18189. this.next();
  18190. this.parseVar(init$1, true, kind);
  18191. this.finishNode(init$1, "VariableDeclaration");
  18192. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  18193. if (this.options.ecmaVersion >= 9) {
  18194. if (this.type === types$1._in) {
  18195. if (awaitAt > -1) { this.unexpected(awaitAt); }
  18196. } else { node.await = awaitAt > -1; }
  18197. }
  18198. return this.parseForIn(node, init$1)
  18199. }
  18200. if (awaitAt > -1) { this.unexpected(awaitAt); }
  18201. return this.parseFor(node, init$1)
  18202. }
  18203. var startsWithLet = this.isContextual("let"), isForOf = false;
  18204. var refDestructuringErrors = new DestructuringErrors;
  18205. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  18206. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  18207. if (this.options.ecmaVersion >= 9) {
  18208. if (this.type === types$1._in) {
  18209. if (awaitAt > -1) { this.unexpected(awaitAt); }
  18210. } else { node.await = awaitAt > -1; }
  18211. }
  18212. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  18213. this.toAssignable(init, false, refDestructuringErrors);
  18214. this.checkLValPattern(init);
  18215. return this.parseForIn(node, init)
  18216. } else {
  18217. this.checkExpressionErrors(refDestructuringErrors, true);
  18218. }
  18219. if (awaitAt > -1) { this.unexpected(awaitAt); }
  18220. return this.parseFor(node, init)
  18221. };
  18222. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  18223. this.next();
  18224. return this.parseFunction(node, FUNC_STATEMENT$1 | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  18225. };
  18226. pp$8.parseIfStatement = function(node) {
  18227. this.next();
  18228. node.test = this.parseParenExpression();
  18229. // allow function declarations in branches, but only in non-strict mode
  18230. node.consequent = this.parseStatement("if");
  18231. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  18232. return this.finishNode(node, "IfStatement")
  18233. };
  18234. pp$8.parseReturnStatement = function(node) {
  18235. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  18236. { this.raise(this.start, "'return' outside of function"); }
  18237. this.next();
  18238. // In `return` (and `break`/`continue`), the keywords with
  18239. // optional arguments, we eagerly look for a semicolon or the
  18240. // possibility to insert one.
  18241. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  18242. else { node.argument = this.parseExpression(); this.semicolon(); }
  18243. return this.finishNode(node, "ReturnStatement")
  18244. };
  18245. pp$8.parseSwitchStatement = function(node) {
  18246. this.next();
  18247. node.discriminant = this.parseParenExpression();
  18248. node.cases = [];
  18249. this.expect(types$1.braceL);
  18250. this.labels.push(switchLabel);
  18251. this.enterScope(0);
  18252. // Statements under must be grouped (by label) in SwitchCase
  18253. // nodes. `cur` is used to keep the node that we are currently
  18254. // adding statements to.
  18255. var cur;
  18256. for (var sawDefault = false; this.type !== types$1.braceR;) {
  18257. if (this.type === types$1._case || this.type === types$1._default) {
  18258. var isCase = this.type === types$1._case;
  18259. if (cur) { this.finishNode(cur, "SwitchCase"); }
  18260. node.cases.push(cur = this.startNode());
  18261. cur.consequent = [];
  18262. this.next();
  18263. if (isCase) {
  18264. cur.test = this.parseExpression();
  18265. } else {
  18266. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  18267. sawDefault = true;
  18268. cur.test = null;
  18269. }
  18270. this.expect(types$1.colon);
  18271. } else {
  18272. if (!cur) { this.unexpected(); }
  18273. cur.consequent.push(this.parseStatement(null));
  18274. }
  18275. }
  18276. this.exitScope();
  18277. if (cur) { this.finishNode(cur, "SwitchCase"); }
  18278. this.next(); // Closing brace
  18279. this.labels.pop();
  18280. return this.finishNode(node, "SwitchStatement")
  18281. };
  18282. pp$8.parseThrowStatement = function(node) {
  18283. this.next();
  18284. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  18285. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  18286. node.argument = this.parseExpression();
  18287. this.semicolon();
  18288. return this.finishNode(node, "ThrowStatement")
  18289. };
  18290. // Reused empty array added for node fields that are always empty.
  18291. var empty$1 = [];
  18292. pp$8.parseTryStatement = function(node) {
  18293. this.next();
  18294. node.block = this.parseBlock();
  18295. node.handler = null;
  18296. if (this.type === types$1._catch) {
  18297. var clause = this.startNode();
  18298. this.next();
  18299. if (this.eat(types$1.parenL)) {
  18300. clause.param = this.parseBindingAtom();
  18301. var simple = clause.param.type === "Identifier";
  18302. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  18303. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  18304. this.expect(types$1.parenR);
  18305. } else {
  18306. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  18307. clause.param = null;
  18308. this.enterScope(0);
  18309. }
  18310. clause.body = this.parseBlock(false);
  18311. this.exitScope();
  18312. node.handler = this.finishNode(clause, "CatchClause");
  18313. }
  18314. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  18315. if (!node.handler && !node.finalizer)
  18316. { this.raise(node.start, "Missing catch or finally clause"); }
  18317. return this.finishNode(node, "TryStatement")
  18318. };
  18319. pp$8.parseVarStatement = function(node, kind) {
  18320. this.next();
  18321. this.parseVar(node, false, kind);
  18322. this.semicolon();
  18323. return this.finishNode(node, "VariableDeclaration")
  18324. };
  18325. pp$8.parseWhileStatement = function(node) {
  18326. this.next();
  18327. node.test = this.parseParenExpression();
  18328. this.labels.push(loopLabel);
  18329. node.body = this.parseStatement("while");
  18330. this.labels.pop();
  18331. return this.finishNode(node, "WhileStatement")
  18332. };
  18333. pp$8.parseWithStatement = function(node) {
  18334. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  18335. this.next();
  18336. node.object = this.parseParenExpression();
  18337. node.body = this.parseStatement("with");
  18338. return this.finishNode(node, "WithStatement")
  18339. };
  18340. pp$8.parseEmptyStatement = function(node) {
  18341. this.next();
  18342. return this.finishNode(node, "EmptyStatement")
  18343. };
  18344. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  18345. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  18346. {
  18347. var label = list[i$1];
  18348. if (label.name === maybeName)
  18349. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  18350. } }
  18351. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  18352. for (var i = this.labels.length - 1; i >= 0; i--) {
  18353. var label$1 = this.labels[i];
  18354. if (label$1.statementStart === node.start) {
  18355. // Update information about previous labels on this node
  18356. label$1.statementStart = this.start;
  18357. label$1.kind = kind;
  18358. } else { break }
  18359. }
  18360. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  18361. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  18362. this.labels.pop();
  18363. node.label = expr;
  18364. return this.finishNode(node, "LabeledStatement")
  18365. };
  18366. pp$8.parseExpressionStatement = function(node, expr) {
  18367. node.expression = expr;
  18368. this.semicolon();
  18369. return this.finishNode(node, "ExpressionStatement")
  18370. };
  18371. // Parse a semicolon-enclosed block of statements, handling `"use
  18372. // strict"` declarations when `allowStrict` is true (used for
  18373. // function bodies).
  18374. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  18375. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  18376. if ( node === void 0 ) node = this.startNode();
  18377. node.body = [];
  18378. this.expect(types$1.braceL);
  18379. if (createNewLexicalScope) { this.enterScope(0); }
  18380. while (this.type !== types$1.braceR) {
  18381. var stmt = this.parseStatement(null);
  18382. node.body.push(stmt);
  18383. }
  18384. if (exitStrict) { this.strict = false; }
  18385. this.next();
  18386. if (createNewLexicalScope) { this.exitScope(); }
  18387. return this.finishNode(node, "BlockStatement")
  18388. };
  18389. // Parse a regular `for` loop. The disambiguation code in
  18390. // `parseStatement` will already have parsed the init statement or
  18391. // expression.
  18392. pp$8.parseFor = function(node, init) {
  18393. node.init = init;
  18394. this.expect(types$1.semi);
  18395. node.test = this.type === types$1.semi ? null : this.parseExpression();
  18396. this.expect(types$1.semi);
  18397. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  18398. this.expect(types$1.parenR);
  18399. node.body = this.parseStatement("for");
  18400. this.exitScope();
  18401. this.labels.pop();
  18402. return this.finishNode(node, "ForStatement")
  18403. };
  18404. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  18405. // same from parser's perspective.
  18406. pp$8.parseForIn = function(node, init) {
  18407. var isForIn = this.type === types$1._in;
  18408. this.next();
  18409. if (
  18410. init.type === "VariableDeclaration" &&
  18411. init.declarations[0].init != null &&
  18412. (
  18413. !isForIn ||
  18414. this.options.ecmaVersion < 8 ||
  18415. this.strict ||
  18416. init.kind !== "var" ||
  18417. init.declarations[0].id.type !== "Identifier"
  18418. )
  18419. ) {
  18420. this.raise(
  18421. init.start,
  18422. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  18423. );
  18424. }
  18425. node.left = init;
  18426. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  18427. this.expect(types$1.parenR);
  18428. node.body = this.parseStatement("for");
  18429. this.exitScope();
  18430. this.labels.pop();
  18431. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  18432. };
  18433. // Parse a list of variable declarations.
  18434. pp$8.parseVar = function(node, isFor, kind) {
  18435. node.declarations = [];
  18436. node.kind = kind;
  18437. for (;;) {
  18438. var decl = this.startNode();
  18439. this.parseVarId(decl, kind);
  18440. if (this.eat(types$1.eq)) {
  18441. decl.init = this.parseMaybeAssign(isFor);
  18442. } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  18443. this.unexpected();
  18444. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  18445. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  18446. } else {
  18447. decl.init = null;
  18448. }
  18449. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  18450. if (!this.eat(types$1.comma)) { break }
  18451. }
  18452. return node
  18453. };
  18454. pp$8.parseVarId = function(decl, kind) {
  18455. decl.id = this.parseBindingAtom();
  18456. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  18457. };
  18458. var FUNC_STATEMENT$1 = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID$1 = 4;
  18459. // Parse a function declaration or literal (depending on the
  18460. // `statement & FUNC_STATEMENT`).
  18461. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  18462. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  18463. this.initFunction(node);
  18464. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  18465. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  18466. { this.unexpected(); }
  18467. node.generator = this.eat(types$1.star);
  18468. }
  18469. if (this.options.ecmaVersion >= 8)
  18470. { node.async = !!isAsync; }
  18471. if (statement & FUNC_STATEMENT$1) {
  18472. node.id = (statement & FUNC_NULLABLE_ID$1) && this.type !== types$1.name ? null : this.parseIdent();
  18473. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  18474. // If it is a regular function declaration in sloppy mode, then it is
  18475. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  18476. // mode depends on properties of the current scope (see
  18477. // treatFunctionsAsVar).
  18478. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  18479. }
  18480. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  18481. this.yieldPos = 0;
  18482. this.awaitPos = 0;
  18483. this.awaitIdentPos = 0;
  18484. this.enterScope(functionFlags(node.async, node.generator));
  18485. if (!(statement & FUNC_STATEMENT$1))
  18486. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  18487. this.parseFunctionParams(node);
  18488. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  18489. this.yieldPos = oldYieldPos;
  18490. this.awaitPos = oldAwaitPos;
  18491. this.awaitIdentPos = oldAwaitIdentPos;
  18492. return this.finishNode(node, (statement & FUNC_STATEMENT$1) ? "FunctionDeclaration" : "FunctionExpression")
  18493. };
  18494. pp$8.parseFunctionParams = function(node) {
  18495. this.expect(types$1.parenL);
  18496. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  18497. this.checkYieldAwaitInDefaultParams();
  18498. };
  18499. // Parse a class declaration or literal (depending on the
  18500. // `isStatement` parameter).
  18501. pp$8.parseClass = function(node, isStatement) {
  18502. this.next();
  18503. // ecma-262 14.6 Class Definitions
  18504. // A class definition is always strict mode code.
  18505. var oldStrict = this.strict;
  18506. this.strict = true;
  18507. this.parseClassId(node, isStatement);
  18508. this.parseClassSuper(node);
  18509. var privateNameMap = this.enterClassBody();
  18510. var classBody = this.startNode();
  18511. var hadConstructor = false;
  18512. classBody.body = [];
  18513. this.expect(types$1.braceL);
  18514. while (this.type !== types$1.braceR) {
  18515. var element = this.parseClassElement(node.superClass !== null);
  18516. if (element) {
  18517. classBody.body.push(element);
  18518. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  18519. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  18520. hadConstructor = true;
  18521. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  18522. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  18523. }
  18524. }
  18525. }
  18526. this.strict = oldStrict;
  18527. this.next();
  18528. node.body = this.finishNode(classBody, "ClassBody");
  18529. this.exitClassBody();
  18530. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  18531. };
  18532. pp$8.parseClassElement = function(constructorAllowsSuper) {
  18533. if (this.eat(types$1.semi)) { return null }
  18534. var ecmaVersion = this.options.ecmaVersion;
  18535. var node = this.startNode();
  18536. var keyName = "";
  18537. var isGenerator = false;
  18538. var isAsync = false;
  18539. var kind = "method";
  18540. var isStatic = false;
  18541. if (this.eatContextual("static")) {
  18542. // Parse static init block
  18543. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  18544. this.parseClassStaticBlock(node);
  18545. return node
  18546. }
  18547. if (this.isClassElementNameStart() || this.type === types$1.star) {
  18548. isStatic = true;
  18549. } else {
  18550. keyName = "static";
  18551. }
  18552. }
  18553. node.static = isStatic;
  18554. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  18555. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  18556. isAsync = true;
  18557. } else {
  18558. keyName = "async";
  18559. }
  18560. }
  18561. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  18562. isGenerator = true;
  18563. }
  18564. if (!keyName && !isAsync && !isGenerator) {
  18565. var lastValue = this.value;
  18566. if (this.eatContextual("get") || this.eatContextual("set")) {
  18567. if (this.isClassElementNameStart()) {
  18568. kind = lastValue;
  18569. } else {
  18570. keyName = lastValue;
  18571. }
  18572. }
  18573. }
  18574. // Parse element name
  18575. if (keyName) {
  18576. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  18577. // The last token is any of those. Make it the element name.
  18578. node.computed = false;
  18579. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  18580. node.key.name = keyName;
  18581. this.finishNode(node.key, "Identifier");
  18582. } else {
  18583. this.parseClassElementName(node);
  18584. }
  18585. // Parse element value
  18586. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  18587. var isConstructor = !node.static && checkKeyName(node, "constructor");
  18588. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  18589. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  18590. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  18591. node.kind = isConstructor ? "constructor" : kind;
  18592. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  18593. } else {
  18594. this.parseClassField(node);
  18595. }
  18596. return node
  18597. };
  18598. pp$8.isClassElementNameStart = function() {
  18599. return (
  18600. this.type === types$1.name ||
  18601. this.type === types$1.privateId ||
  18602. this.type === types$1.num ||
  18603. this.type === types$1.string ||
  18604. this.type === types$1.bracketL ||
  18605. this.type.keyword
  18606. )
  18607. };
  18608. pp$8.parseClassElementName = function(element) {
  18609. if (this.type === types$1.privateId) {
  18610. if (this.value === "constructor") {
  18611. this.raise(this.start, "Classes can't have an element named '#constructor'");
  18612. }
  18613. element.computed = false;
  18614. element.key = this.parsePrivateIdent();
  18615. } else {
  18616. this.parsePropertyName(element);
  18617. }
  18618. };
  18619. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  18620. // Check key and flags
  18621. var key = method.key;
  18622. if (method.kind === "constructor") {
  18623. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  18624. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  18625. } else if (method.static && checkKeyName(method, "prototype")) {
  18626. this.raise(key.start, "Classes may not have a static property named prototype");
  18627. }
  18628. // Parse value
  18629. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  18630. // Check value
  18631. if (method.kind === "get" && value.params.length !== 0)
  18632. { this.raiseRecoverable(value.start, "getter should have no params"); }
  18633. if (method.kind === "set" && value.params.length !== 1)
  18634. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  18635. if (method.kind === "set" && value.params[0].type === "RestElement")
  18636. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  18637. return this.finishNode(method, "MethodDefinition")
  18638. };
  18639. pp$8.parseClassField = function(field) {
  18640. if (checkKeyName(field, "constructor")) {
  18641. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  18642. } else if (field.static && checkKeyName(field, "prototype")) {
  18643. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  18644. }
  18645. if (this.eat(types$1.eq)) {
  18646. // To raise SyntaxError if 'arguments' exists in the initializer.
  18647. var scope = this.currentThisScope();
  18648. var inClassFieldInit = scope.inClassFieldInit;
  18649. scope.inClassFieldInit = true;
  18650. field.value = this.parseMaybeAssign();
  18651. scope.inClassFieldInit = inClassFieldInit;
  18652. } else {
  18653. field.value = null;
  18654. }
  18655. this.semicolon();
  18656. return this.finishNode(field, "PropertyDefinition")
  18657. };
  18658. pp$8.parseClassStaticBlock = function(node) {
  18659. node.body = [];
  18660. var oldLabels = this.labels;
  18661. this.labels = [];
  18662. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  18663. while (this.type !== types$1.braceR) {
  18664. var stmt = this.parseStatement(null);
  18665. node.body.push(stmt);
  18666. }
  18667. this.next();
  18668. this.exitScope();
  18669. this.labels = oldLabels;
  18670. return this.finishNode(node, "StaticBlock")
  18671. };
  18672. pp$8.parseClassId = function(node, isStatement) {
  18673. if (this.type === types$1.name) {
  18674. node.id = this.parseIdent();
  18675. if (isStatement)
  18676. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  18677. } else {
  18678. if (isStatement === true)
  18679. { this.unexpected(); }
  18680. node.id = null;
  18681. }
  18682. };
  18683. pp$8.parseClassSuper = function(node) {
  18684. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;
  18685. };
  18686. pp$8.enterClassBody = function() {
  18687. var element = {declared: Object.create(null), used: []};
  18688. this.privateNameStack.push(element);
  18689. return element.declared
  18690. };
  18691. pp$8.exitClassBody = function() {
  18692. var ref = this.privateNameStack.pop();
  18693. var declared = ref.declared;
  18694. var used = ref.used;
  18695. var len = this.privateNameStack.length;
  18696. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  18697. for (var i = 0; i < used.length; ++i) {
  18698. var id = used[i];
  18699. if (!hasOwn(declared, id.name)) {
  18700. if (parent) {
  18701. parent.used.push(id);
  18702. } else {
  18703. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  18704. }
  18705. }
  18706. }
  18707. };
  18708. function isPrivateNameConflicted(privateNameMap, element) {
  18709. var name = element.key.name;
  18710. var curr = privateNameMap[name];
  18711. var next = "true";
  18712. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  18713. next = (element.static ? "s" : "i") + element.kind;
  18714. }
  18715. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  18716. if (
  18717. curr === "iget" && next === "iset" ||
  18718. curr === "iset" && next === "iget" ||
  18719. curr === "sget" && next === "sset" ||
  18720. curr === "sset" && next === "sget"
  18721. ) {
  18722. privateNameMap[name] = "true";
  18723. return false
  18724. } else if (!curr) {
  18725. privateNameMap[name] = next;
  18726. return false
  18727. } else {
  18728. return true
  18729. }
  18730. }
  18731. function checkKeyName(node, name) {
  18732. var computed = node.computed;
  18733. var key = node.key;
  18734. return !computed && (
  18735. key.type === "Identifier" && key.name === name ||
  18736. key.type === "Literal" && key.value === name
  18737. )
  18738. }
  18739. // Parses module export declaration.
  18740. pp$8.parseExport = function(node, exports) {
  18741. this.next();
  18742. // export * from '...'
  18743. if (this.eat(types$1.star)) {
  18744. if (this.options.ecmaVersion >= 11) {
  18745. if (this.eatContextual("as")) {
  18746. node.exported = this.parseModuleExportName();
  18747. this.checkExport(exports, node.exported, this.lastTokStart);
  18748. } else {
  18749. node.exported = null;
  18750. }
  18751. }
  18752. this.expectContextual("from");
  18753. if (this.type !== types$1.string) { this.unexpected(); }
  18754. node.source = this.parseExprAtom();
  18755. this.semicolon();
  18756. return this.finishNode(node, "ExportAllDeclaration")
  18757. }
  18758. if (this.eat(types$1._default)) { // export default ...
  18759. this.checkExport(exports, "default", this.lastTokStart);
  18760. var isAsync;
  18761. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  18762. var fNode = this.startNode();
  18763. this.next();
  18764. if (isAsync) { this.next(); }
  18765. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT$1 | FUNC_NULLABLE_ID$1, false, isAsync);
  18766. } else if (this.type === types$1._class) {
  18767. var cNode = this.startNode();
  18768. node.declaration = this.parseClass(cNode, "nullableID");
  18769. } else {
  18770. node.declaration = this.parseMaybeAssign();
  18771. this.semicolon();
  18772. }
  18773. return this.finishNode(node, "ExportDefaultDeclaration")
  18774. }
  18775. // export var|const|let|function|class ...
  18776. if (this.shouldParseExportStatement()) {
  18777. node.declaration = this.parseStatement(null);
  18778. if (node.declaration.type === "VariableDeclaration")
  18779. { this.checkVariableExport(exports, node.declaration.declarations); }
  18780. else
  18781. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  18782. node.specifiers = [];
  18783. node.source = null;
  18784. } else { // export { x, y as z } [from '...']
  18785. node.declaration = null;
  18786. node.specifiers = this.parseExportSpecifiers(exports);
  18787. if (this.eatContextual("from")) {
  18788. if (this.type !== types$1.string) { this.unexpected(); }
  18789. node.source = this.parseExprAtom();
  18790. } else {
  18791. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  18792. // check for keywords used as local names
  18793. var spec = list[i];
  18794. this.checkUnreserved(spec.local);
  18795. // check if export is defined
  18796. this.checkLocalExport(spec.local);
  18797. if (spec.local.type === "Literal") {
  18798. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  18799. }
  18800. }
  18801. node.source = null;
  18802. }
  18803. this.semicolon();
  18804. }
  18805. return this.finishNode(node, "ExportNamedDeclaration")
  18806. };
  18807. pp$8.checkExport = function(exports, name, pos) {
  18808. if (!exports) { return }
  18809. if (typeof name !== "string")
  18810. { name = name.type === "Identifier" ? name.name : name.value; }
  18811. if (hasOwn(exports, name))
  18812. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  18813. exports[name] = true;
  18814. };
  18815. pp$8.checkPatternExport = function(exports, pat) {
  18816. var type = pat.type;
  18817. if (type === "Identifier")
  18818. { this.checkExport(exports, pat, pat.start); }
  18819. else if (type === "ObjectPattern")
  18820. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  18821. {
  18822. var prop = list[i];
  18823. this.checkPatternExport(exports, prop);
  18824. } }
  18825. else if (type === "ArrayPattern")
  18826. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  18827. var elt = list$1[i$1];
  18828. if (elt) { this.checkPatternExport(exports, elt); }
  18829. } }
  18830. else if (type === "Property")
  18831. { this.checkPatternExport(exports, pat.value); }
  18832. else if (type === "AssignmentPattern")
  18833. { this.checkPatternExport(exports, pat.left); }
  18834. else if (type === "RestElement")
  18835. { this.checkPatternExport(exports, pat.argument); }
  18836. else if (type === "ParenthesizedExpression")
  18837. { this.checkPatternExport(exports, pat.expression); }
  18838. };
  18839. pp$8.checkVariableExport = function(exports, decls) {
  18840. if (!exports) { return }
  18841. for (var i = 0, list = decls; i < list.length; i += 1)
  18842. {
  18843. var decl = list[i];
  18844. this.checkPatternExport(exports, decl.id);
  18845. }
  18846. };
  18847. pp$8.shouldParseExportStatement = function() {
  18848. return this.type.keyword === "var" ||
  18849. this.type.keyword === "const" ||
  18850. this.type.keyword === "class" ||
  18851. this.type.keyword === "function" ||
  18852. this.isLet() ||
  18853. this.isAsyncFunction()
  18854. };
  18855. // Parses a comma-separated list of module exports.
  18856. pp$8.parseExportSpecifiers = function(exports) {
  18857. var nodes = [], first = true;
  18858. // export { x, y as z } [from '...']
  18859. this.expect(types$1.braceL);
  18860. while (!this.eat(types$1.braceR)) {
  18861. if (!first) {
  18862. this.expect(types$1.comma);
  18863. if (this.afterTrailingComma(types$1.braceR)) { break }
  18864. } else { first = false; }
  18865. var node = this.startNode();
  18866. node.local = this.parseModuleExportName();
  18867. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  18868. this.checkExport(
  18869. exports,
  18870. node.exported,
  18871. node.exported.start
  18872. );
  18873. nodes.push(this.finishNode(node, "ExportSpecifier"));
  18874. }
  18875. return nodes
  18876. };
  18877. // Parses import declaration.
  18878. pp$8.parseImport = function(node) {
  18879. this.next();
  18880. // import '...'
  18881. if (this.type === types$1.string) {
  18882. node.specifiers = empty$1;
  18883. node.source = this.parseExprAtom();
  18884. } else {
  18885. node.specifiers = this.parseImportSpecifiers();
  18886. this.expectContextual("from");
  18887. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  18888. }
  18889. this.semicolon();
  18890. return this.finishNode(node, "ImportDeclaration")
  18891. };
  18892. // Parses a comma-separated list of module imports.
  18893. pp$8.parseImportSpecifiers = function() {
  18894. var nodes = [], first = true;
  18895. if (this.type === types$1.name) {
  18896. // import defaultObj, { x, y as z } from '...'
  18897. var node = this.startNode();
  18898. node.local = this.parseIdent();
  18899. this.checkLValSimple(node.local, BIND_LEXICAL);
  18900. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  18901. if (!this.eat(types$1.comma)) { return nodes }
  18902. }
  18903. if (this.type === types$1.star) {
  18904. var node$1 = this.startNode();
  18905. this.next();
  18906. this.expectContextual("as");
  18907. node$1.local = this.parseIdent();
  18908. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  18909. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  18910. return nodes
  18911. }
  18912. this.expect(types$1.braceL);
  18913. while (!this.eat(types$1.braceR)) {
  18914. if (!first) {
  18915. this.expect(types$1.comma);
  18916. if (this.afterTrailingComma(types$1.braceR)) { break }
  18917. } else { first = false; }
  18918. var node$2 = this.startNode();
  18919. node$2.imported = this.parseModuleExportName();
  18920. if (this.eatContextual("as")) {
  18921. node$2.local = this.parseIdent();
  18922. } else {
  18923. this.checkUnreserved(node$2.imported);
  18924. node$2.local = node$2.imported;
  18925. }
  18926. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  18927. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  18928. }
  18929. return nodes
  18930. };
  18931. pp$8.parseModuleExportName = function() {
  18932. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  18933. var stringLiteral = this.parseLiteral(this.value);
  18934. if (loneSurrogate.test(stringLiteral.value)) {
  18935. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  18936. }
  18937. return stringLiteral
  18938. }
  18939. return this.parseIdent(true)
  18940. };
  18941. // Set `ExpressionStatement#directive` property for directive prologues.
  18942. pp$8.adaptDirectivePrologue = function(statements) {
  18943. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  18944. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  18945. }
  18946. };
  18947. pp$8.isDirectiveCandidate = function(statement) {
  18948. return (
  18949. this.options.ecmaVersion >= 5 &&
  18950. statement.type === "ExpressionStatement" &&
  18951. statement.expression.type === "Literal" &&
  18952. typeof statement.expression.value === "string" &&
  18953. // Reject parenthesized strings.
  18954. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  18955. )
  18956. };
  18957. var pp$7 = Parser.prototype;
  18958. // Convert existing expression atom to assignable pattern
  18959. // if possible.
  18960. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  18961. if (this.options.ecmaVersion >= 6 && node) {
  18962. switch (node.type) {
  18963. case "Identifier":
  18964. if (this.inAsync && node.name === "await")
  18965. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  18966. break
  18967. case "ObjectPattern":
  18968. case "ArrayPattern":
  18969. case "AssignmentPattern":
  18970. case "RestElement":
  18971. break
  18972. case "ObjectExpression":
  18973. node.type = "ObjectPattern";
  18974. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  18975. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  18976. var prop = list[i];
  18977. this.toAssignable(prop, isBinding);
  18978. // Early error:
  18979. // AssignmentRestProperty[Yield, Await] :
  18980. // `...` DestructuringAssignmentTarget[Yield, Await]
  18981. //
  18982. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  18983. if (
  18984. prop.type === "RestElement" &&
  18985. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  18986. ) {
  18987. this.raise(prop.argument.start, "Unexpected token");
  18988. }
  18989. }
  18990. break
  18991. case "Property":
  18992. // AssignmentProperty has type === "Property"
  18993. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  18994. this.toAssignable(node.value, isBinding);
  18995. break
  18996. case "ArrayExpression":
  18997. node.type = "ArrayPattern";
  18998. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  18999. this.toAssignableList(node.elements, isBinding);
  19000. break
  19001. case "SpreadElement":
  19002. node.type = "RestElement";
  19003. this.toAssignable(node.argument, isBinding);
  19004. if (node.argument.type === "AssignmentPattern")
  19005. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  19006. break
  19007. case "AssignmentExpression":
  19008. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  19009. node.type = "AssignmentPattern";
  19010. delete node.operator;
  19011. this.toAssignable(node.left, isBinding);
  19012. break
  19013. case "ParenthesizedExpression":
  19014. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  19015. break
  19016. case "ChainExpression":
  19017. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  19018. break
  19019. case "MemberExpression":
  19020. if (!isBinding) { break }
  19021. default:
  19022. this.raise(node.start, "Assigning to rvalue");
  19023. }
  19024. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  19025. return node
  19026. };
  19027. // Convert list of expression atoms to binding list.
  19028. pp$7.toAssignableList = function(exprList, isBinding) {
  19029. var end = exprList.length;
  19030. for (var i = 0; i < end; i++) {
  19031. var elt = exprList[i];
  19032. if (elt) { this.toAssignable(elt, isBinding); }
  19033. }
  19034. if (end) {
  19035. var last = exprList[end - 1];
  19036. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  19037. { this.unexpected(last.argument.start); }
  19038. }
  19039. return exprList
  19040. };
  19041. // Parses spread element.
  19042. pp$7.parseSpread = function(refDestructuringErrors) {
  19043. var node = this.startNode();
  19044. this.next();
  19045. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  19046. return this.finishNode(node, "SpreadElement")
  19047. };
  19048. pp$7.parseRestBinding = function() {
  19049. var node = this.startNode();
  19050. this.next();
  19051. // RestElement inside of a function parameter must be an identifier
  19052. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  19053. { this.unexpected(); }
  19054. node.argument = this.parseBindingAtom();
  19055. return this.finishNode(node, "RestElement")
  19056. };
  19057. // Parses lvalue (assignable) atom.
  19058. pp$7.parseBindingAtom = function() {
  19059. if (this.options.ecmaVersion >= 6) {
  19060. switch (this.type) {
  19061. case types$1.bracketL:
  19062. var node = this.startNode();
  19063. this.next();
  19064. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  19065. return this.finishNode(node, "ArrayPattern")
  19066. case types$1.braceL:
  19067. return this.parseObj(true)
  19068. }
  19069. }
  19070. return this.parseIdent()
  19071. };
  19072. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  19073. var elts = [], first = true;
  19074. while (!this.eat(close)) {
  19075. if (first) { first = false; }
  19076. else { this.expect(types$1.comma); }
  19077. if (allowEmpty && this.type === types$1.comma) {
  19078. elts.push(null);
  19079. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  19080. break
  19081. } else if (this.type === types$1.ellipsis) {
  19082. var rest = this.parseRestBinding();
  19083. this.parseBindingListItem(rest);
  19084. elts.push(rest);
  19085. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  19086. this.expect(close);
  19087. break
  19088. } else {
  19089. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  19090. this.parseBindingListItem(elem);
  19091. elts.push(elem);
  19092. }
  19093. }
  19094. return elts
  19095. };
  19096. pp$7.parseBindingListItem = function(param) {
  19097. return param
  19098. };
  19099. // Parses assignment pattern around given atom if possible.
  19100. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  19101. left = left || this.parseBindingAtom();
  19102. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  19103. var node = this.startNodeAt(startPos, startLoc);
  19104. node.left = left;
  19105. node.right = this.parseMaybeAssign();
  19106. return this.finishNode(node, "AssignmentPattern")
  19107. };
  19108. // The following three functions all verify that a node is an lvalue —
  19109. // something that can be bound, or assigned to. In order to do so, they perform
  19110. // a variety of checks:
  19111. //
  19112. // - Check that none of the bound/assigned-to identifiers are reserved words.
  19113. // - Record name declarations for bindings in the appropriate scope.
  19114. // - Check duplicate argument names, if checkClashes is set.
  19115. //
  19116. // If a complex binding pattern is encountered (e.g., object and array
  19117. // destructuring), the entire pattern is recursively checked.
  19118. //
  19119. // There are three versions of checkLVal*() appropriate for different
  19120. // circumstances:
  19121. //
  19122. // - checkLValSimple() shall be used if the syntactic construct supports
  19123. // nothing other than identifiers and member expressions. Parenthesized
  19124. // expressions are also correctly handled. This is generally appropriate for
  19125. // constructs for which the spec says
  19126. //
  19127. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  19128. // > simple.
  19129. //
  19130. // It is also appropriate for checking if an identifier is valid and not
  19131. // defined elsewhere, like import declarations or function/class identifiers.
  19132. //
  19133. // Examples where this is used include:
  19134. // a += …;
  19135. // import a from '…';
  19136. // where a is the node to be checked.
  19137. //
  19138. // - checkLValPattern() shall be used if the syntactic construct supports
  19139. // anything checkLValSimple() supports, as well as object and array
  19140. // destructuring patterns. This is generally appropriate for constructs for
  19141. // which the spec says
  19142. //
  19143. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  19144. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  19145. // > simple.
  19146. //
  19147. // Examples where this is used include:
  19148. // (a = …);
  19149. // const a = …;
  19150. // try { … } catch (a) { … }
  19151. // where a is the node to be checked.
  19152. //
  19153. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  19154. // anything checkLValPattern() supports, as well as default assignment
  19155. // patterns, rest elements, and other constructs that may appear within an
  19156. // object or array destructuring pattern.
  19157. //
  19158. // As a special case, function parameters also use checkLValInnerPattern(),
  19159. // as they also support defaults and rest constructs.
  19160. //
  19161. // These functions deliberately support both assignment and binding constructs,
  19162. // as the logic for both is exceedingly similar. If the node is the target of
  19163. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  19164. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  19165. // BIND_LEXICAL.
  19166. //
  19167. // If the function is called with a non-BIND_NONE bindingType, then
  19168. // additionally a checkClashes object may be specified to allow checking for
  19169. // duplicate argument names. checkClashes is ignored if the provided construct
  19170. // is an assignment (i.e., bindingType is BIND_NONE).
  19171. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  19172. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  19173. var isBind = bindingType !== BIND_NONE;
  19174. switch (expr.type) {
  19175. case "Identifier":
  19176. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  19177. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  19178. if (isBind) {
  19179. if (bindingType === BIND_LEXICAL && expr.name === "let")
  19180. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  19181. if (checkClashes) {
  19182. if (hasOwn(checkClashes, expr.name))
  19183. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  19184. checkClashes[expr.name] = true;
  19185. }
  19186. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  19187. }
  19188. break
  19189. case "ChainExpression":
  19190. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  19191. break
  19192. case "MemberExpression":
  19193. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  19194. break
  19195. case "ParenthesizedExpression":
  19196. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  19197. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  19198. default:
  19199. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  19200. }
  19201. };
  19202. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  19203. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  19204. switch (expr.type) {
  19205. case "ObjectPattern":
  19206. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  19207. var prop = list[i];
  19208. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  19209. }
  19210. break
  19211. case "ArrayPattern":
  19212. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  19213. var elem = list$1[i$1];
  19214. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  19215. }
  19216. break
  19217. default:
  19218. this.checkLValSimple(expr, bindingType, checkClashes);
  19219. }
  19220. };
  19221. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  19222. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  19223. switch (expr.type) {
  19224. case "Property":
  19225. // AssignmentProperty has type === "Property"
  19226. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  19227. break
  19228. case "AssignmentPattern":
  19229. this.checkLValPattern(expr.left, bindingType, checkClashes);
  19230. break
  19231. case "RestElement":
  19232. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  19233. break
  19234. default:
  19235. this.checkLValPattern(expr, bindingType, checkClashes);
  19236. }
  19237. };
  19238. // The algorithm used to determine whether a regexp can appear at a
  19239. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  19240. this.token = token;
  19241. this.isExpr = !!isExpr;
  19242. this.preserveSpace = !!preserveSpace;
  19243. this.override = override;
  19244. this.generator = !!generator;
  19245. };
  19246. var types = {
  19247. b_stat: new TokContext("{", false),
  19248. b_expr: new TokContext("{", true),
  19249. b_tmpl: new TokContext("${", false),
  19250. p_stat: new TokContext("(", false),
  19251. p_expr: new TokContext("(", true),
  19252. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  19253. f_stat: new TokContext("function", false),
  19254. f_expr: new TokContext("function", true),
  19255. f_expr_gen: new TokContext("function", true, false, null, true),
  19256. f_gen: new TokContext("function", false, false, null, true)
  19257. };
  19258. var pp$6 = Parser.prototype;
  19259. pp$6.initialContext = function() {
  19260. return [types.b_stat]
  19261. };
  19262. pp$6.curContext = function() {
  19263. return this.context[this.context.length - 1]
  19264. };
  19265. pp$6.braceIsBlock = function(prevType) {
  19266. var parent = this.curContext();
  19267. if (parent === types.f_expr || parent === types.f_stat)
  19268. { return true }
  19269. if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
  19270. { return !parent.isExpr }
  19271. // The check for `tt.name && exprAllowed` detects whether we are
  19272. // after a `yield` or `of` construct. See the `updateContext` for
  19273. // `tt.name`.
  19274. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  19275. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  19276. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  19277. { return true }
  19278. if (prevType === types$1.braceL)
  19279. { return parent === types.b_stat }
  19280. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  19281. { return false }
  19282. return !this.exprAllowed
  19283. };
  19284. pp$6.inGeneratorContext = function() {
  19285. for (var i = this.context.length - 1; i >= 1; i--) {
  19286. var context = this.context[i];
  19287. if (context.token === "function")
  19288. { return context.generator }
  19289. }
  19290. return false
  19291. };
  19292. pp$6.updateContext = function(prevType) {
  19293. var update, type = this.type;
  19294. if (type.keyword && prevType === types$1.dot)
  19295. { this.exprAllowed = false; }
  19296. else if (update = type.updateContext)
  19297. { update.call(this, prevType); }
  19298. else
  19299. { this.exprAllowed = type.beforeExpr; }
  19300. };
  19301. // Used to handle egde cases when token context could not be inferred correctly during tokenization phase
  19302. pp$6.overrideContext = function(tokenCtx) {
  19303. if (this.curContext() !== tokenCtx) {
  19304. this.context[this.context.length - 1] = tokenCtx;
  19305. }
  19306. };
  19307. // Token-specific context update code
  19308. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  19309. if (this.context.length === 1) {
  19310. this.exprAllowed = true;
  19311. return
  19312. }
  19313. var out = this.context.pop();
  19314. if (out === types.b_stat && this.curContext().token === "function") {
  19315. out = this.context.pop();
  19316. }
  19317. this.exprAllowed = !out.isExpr;
  19318. };
  19319. types$1.braceL.updateContext = function(prevType) {
  19320. this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  19321. this.exprAllowed = true;
  19322. };
  19323. types$1.dollarBraceL.updateContext = function() {
  19324. this.context.push(types.b_tmpl);
  19325. this.exprAllowed = true;
  19326. };
  19327. types$1.parenL.updateContext = function(prevType) {
  19328. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  19329. this.context.push(statementParens ? types.p_stat : types.p_expr);
  19330. this.exprAllowed = true;
  19331. };
  19332. types$1.incDec.updateContext = function() {
  19333. // tokExprAllowed stays unchanged
  19334. };
  19335. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  19336. if (prevType.beforeExpr && prevType !== types$1._else &&
  19337. !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
  19338. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  19339. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
  19340. { this.context.push(types.f_expr); }
  19341. else
  19342. { this.context.push(types.f_stat); }
  19343. this.exprAllowed = false;
  19344. };
  19345. types$1.backQuote.updateContext = function() {
  19346. if (this.curContext() === types.q_tmpl)
  19347. { this.context.pop(); }
  19348. else
  19349. { this.context.push(types.q_tmpl); }
  19350. this.exprAllowed = false;
  19351. };
  19352. types$1.star.updateContext = function(prevType) {
  19353. if (prevType === types$1._function) {
  19354. var index = this.context.length - 1;
  19355. if (this.context[index] === types.f_expr)
  19356. { this.context[index] = types.f_expr_gen; }
  19357. else
  19358. { this.context[index] = types.f_gen; }
  19359. }
  19360. this.exprAllowed = true;
  19361. };
  19362. types$1.name.updateContext = function(prevType) {
  19363. var allowed = false;
  19364. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  19365. if (this.value === "of" && !this.exprAllowed ||
  19366. this.value === "yield" && this.inGeneratorContext())
  19367. { allowed = true; }
  19368. }
  19369. this.exprAllowed = allowed;
  19370. };
  19371. // A recursive descent parser operates by defining functions for all
  19372. var pp$5 = Parser.prototype;
  19373. // Check if property name clashes with already added.
  19374. // Object/class getters and setters are not allowed to clash —
  19375. // either with each other or with an init property — and in
  19376. // strict mode, init properties are also not allowed to be repeated.
  19377. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  19378. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  19379. { return }
  19380. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  19381. { return }
  19382. var key = prop.key;
  19383. var name;
  19384. switch (key.type) {
  19385. case "Identifier": name = key.name; break
  19386. case "Literal": name = String(key.value); break
  19387. default: return
  19388. }
  19389. var kind = prop.kind;
  19390. if (this.options.ecmaVersion >= 6) {
  19391. if (name === "__proto__" && kind === "init") {
  19392. if (propHash.proto) {
  19393. if (refDestructuringErrors) {
  19394. if (refDestructuringErrors.doubleProto < 0) {
  19395. refDestructuringErrors.doubleProto = key.start;
  19396. }
  19397. } else {
  19398. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  19399. }
  19400. }
  19401. propHash.proto = true;
  19402. }
  19403. return
  19404. }
  19405. name = "$" + name;
  19406. var other = propHash[name];
  19407. if (other) {
  19408. var redefinition;
  19409. if (kind === "init") {
  19410. redefinition = this.strict && other.init || other.get || other.set;
  19411. } else {
  19412. redefinition = other.init || other[kind];
  19413. }
  19414. if (redefinition)
  19415. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  19416. } else {
  19417. other = propHash[name] = {
  19418. init: false,
  19419. get: false,
  19420. set: false
  19421. };
  19422. }
  19423. other[kind] = true;
  19424. };
  19425. // ### Expression parsing
  19426. // These nest, from the most general expression type at the top to
  19427. // 'atomic', nondivisible expression types at the bottom. Most of
  19428. // the functions will simply let the function(s) below them parse,
  19429. // and, *if* the syntactic construct they handle is present, wrap
  19430. // the AST node that the inner parser gave them in another node.
  19431. // Parse a full expression. The optional arguments are used to
  19432. // forbid the `in` operator (in for loops initalization expressions)
  19433. // and provide reference for storing '=' operator inside shorthand
  19434. // property assignment in contexts where both object expression
  19435. // and object pattern might appear (so it's possible to raise
  19436. // delayed syntax error at correct position).
  19437. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  19438. var startPos = this.start, startLoc = this.startLoc;
  19439. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  19440. if (this.type === types$1.comma) {
  19441. var node = this.startNodeAt(startPos, startLoc);
  19442. node.expressions = [expr];
  19443. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  19444. return this.finishNode(node, "SequenceExpression")
  19445. }
  19446. return expr
  19447. };
  19448. // Parse an assignment expression. This includes applications of
  19449. // operators like `+=`.
  19450. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  19451. if (this.isContextual("yield")) {
  19452. if (this.inGenerator) { return this.parseYield(forInit) }
  19453. // The tokenizer will assume an expression is allowed after
  19454. // `yield`, but this isn't that kind of yield
  19455. else { this.exprAllowed = false; }
  19456. }
  19457. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  19458. if (refDestructuringErrors) {
  19459. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  19460. oldTrailingComma = refDestructuringErrors.trailingComma;
  19461. oldDoubleProto = refDestructuringErrors.doubleProto;
  19462. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  19463. } else {
  19464. refDestructuringErrors = new DestructuringErrors;
  19465. ownDestructuringErrors = true;
  19466. }
  19467. var startPos = this.start, startLoc = this.startLoc;
  19468. if (this.type === types$1.parenL || this.type === types$1.name) {
  19469. this.potentialArrowAt = this.start;
  19470. this.potentialArrowInForAwait = forInit === "await";
  19471. }
  19472. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  19473. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  19474. if (this.type.isAssign) {
  19475. var node = this.startNodeAt(startPos, startLoc);
  19476. node.operator = this.value;
  19477. if (this.type === types$1.eq)
  19478. { left = this.toAssignable(left, false, refDestructuringErrors); }
  19479. if (!ownDestructuringErrors) {
  19480. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  19481. }
  19482. if (refDestructuringErrors.shorthandAssign >= left.start)
  19483. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  19484. if (this.type === types$1.eq)
  19485. { this.checkLValPattern(left); }
  19486. else
  19487. { this.checkLValSimple(left); }
  19488. node.left = left;
  19489. this.next();
  19490. node.right = this.parseMaybeAssign(forInit);
  19491. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  19492. return this.finishNode(node, "AssignmentExpression")
  19493. } else {
  19494. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  19495. }
  19496. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  19497. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  19498. return left
  19499. };
  19500. // Parse a ternary conditional (`?:`) operator.
  19501. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  19502. var startPos = this.start, startLoc = this.startLoc;
  19503. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  19504. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  19505. if (this.eat(types$1.question)) {
  19506. var node = this.startNodeAt(startPos, startLoc);
  19507. node.test = expr;
  19508. node.consequent = this.parseMaybeAssign();
  19509. this.expect(types$1.colon);
  19510. node.alternate = this.parseMaybeAssign(forInit);
  19511. return this.finishNode(node, "ConditionalExpression")
  19512. }
  19513. return expr
  19514. };
  19515. // Start the precedence parser.
  19516. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  19517. var startPos = this.start, startLoc = this.startLoc;
  19518. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  19519. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  19520. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  19521. };
  19522. // Parse binary operators with the operator precedence parsing
  19523. // algorithm. `left` is the left-hand side of the operator.
  19524. // `minPrec` provides context that allows the function to stop and
  19525. // defer further parser to one of its callers when it encounters an
  19526. // operator that has a lower precedence than the set it is parsing.
  19527. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  19528. var prec = this.type.binop;
  19529. if (prec != null && (!forInit || this.type !== types$1._in)) {
  19530. if (prec > minPrec) {
  19531. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  19532. var coalesce = this.type === types$1.coalesce;
  19533. if (coalesce) {
  19534. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  19535. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  19536. prec = types$1.logicalAND.binop;
  19537. }
  19538. var op = this.value;
  19539. this.next();
  19540. var startPos = this.start, startLoc = this.startLoc;
  19541. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  19542. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  19543. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  19544. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  19545. }
  19546. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  19547. }
  19548. }
  19549. return left
  19550. };
  19551. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  19552. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  19553. var node = this.startNodeAt(startPos, startLoc);
  19554. node.left = left;
  19555. node.operator = op;
  19556. node.right = right;
  19557. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  19558. };
  19559. // Parse unary operators, both prefix and postfix.
  19560. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  19561. var startPos = this.start, startLoc = this.startLoc, expr;
  19562. if (this.isContextual("await") && this.canAwait) {
  19563. expr = this.parseAwait(forInit);
  19564. sawUnary = true;
  19565. } else if (this.type.prefix) {
  19566. var node = this.startNode(), update = this.type === types$1.incDec;
  19567. node.operator = this.value;
  19568. node.prefix = true;
  19569. this.next();
  19570. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  19571. this.checkExpressionErrors(refDestructuringErrors, true);
  19572. if (update) { this.checkLValSimple(node.argument); }
  19573. else if (this.strict && node.operator === "delete" &&
  19574. node.argument.type === "Identifier")
  19575. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  19576. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  19577. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  19578. else { sawUnary = true; }
  19579. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  19580. } else if (!sawUnary && this.type === types$1.privateId) {
  19581. if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
  19582. expr = this.parsePrivateIdent();
  19583. // only could be private fields in 'in', such as #x in obj
  19584. if (this.type !== types$1._in) { this.unexpected(); }
  19585. } else {
  19586. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  19587. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  19588. while (this.type.postfix && !this.canInsertSemicolon()) {
  19589. var node$1 = this.startNodeAt(startPos, startLoc);
  19590. node$1.operator = this.value;
  19591. node$1.prefix = false;
  19592. node$1.argument = expr;
  19593. this.checkLValSimple(expr);
  19594. this.next();
  19595. expr = this.finishNode(node$1, "UpdateExpression");
  19596. }
  19597. }
  19598. if (!incDec && this.eat(types$1.starstar)) {
  19599. if (sawUnary)
  19600. { this.unexpected(this.lastTokStart); }
  19601. else
  19602. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  19603. } else {
  19604. return expr
  19605. }
  19606. };
  19607. function isPrivateFieldAccess(node) {
  19608. return (
  19609. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  19610. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  19611. )
  19612. }
  19613. // Parse call, dot, and `[]`-subscript expressions.
  19614. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  19615. var startPos = this.start, startLoc = this.startLoc;
  19616. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  19617. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  19618. { return expr }
  19619. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  19620. if (refDestructuringErrors && result.type === "MemberExpression") {
  19621. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  19622. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  19623. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  19624. }
  19625. return result
  19626. };
  19627. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  19628. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  19629. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  19630. this.potentialArrowAt === base.start;
  19631. var optionalChained = false;
  19632. while (true) {
  19633. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  19634. if (element.optional) { optionalChained = true; }
  19635. if (element === base || element.type === "ArrowFunctionExpression") {
  19636. if (optionalChained) {
  19637. var chainNode = this.startNodeAt(startPos, startLoc);
  19638. chainNode.expression = element;
  19639. element = this.finishNode(chainNode, "ChainExpression");
  19640. }
  19641. return element
  19642. }
  19643. base = element;
  19644. }
  19645. };
  19646. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  19647. var optionalSupported = this.options.ecmaVersion >= 11;
  19648. var optional = optionalSupported && this.eat(types$1.questionDot);
  19649. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  19650. var computed = this.eat(types$1.bracketL);
  19651. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  19652. var node = this.startNodeAt(startPos, startLoc);
  19653. node.object = base;
  19654. if (computed) {
  19655. node.property = this.parseExpression();
  19656. this.expect(types$1.bracketR);
  19657. } else if (this.type === types$1.privateId && base.type !== "Super") {
  19658. node.property = this.parsePrivateIdent();
  19659. } else {
  19660. node.property = this.parseIdent(this.options.allowReserved !== "never");
  19661. }
  19662. node.computed = !!computed;
  19663. if (optionalSupported) {
  19664. node.optional = optional;
  19665. }
  19666. base = this.finishNode(node, "MemberExpression");
  19667. } else if (!noCalls && this.eat(types$1.parenL)) {
  19668. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  19669. this.yieldPos = 0;
  19670. this.awaitPos = 0;
  19671. this.awaitIdentPos = 0;
  19672. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  19673. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  19674. this.checkPatternErrors(refDestructuringErrors, false);
  19675. this.checkYieldAwaitInDefaultParams();
  19676. if (this.awaitIdentPos > 0)
  19677. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  19678. this.yieldPos = oldYieldPos;
  19679. this.awaitPos = oldAwaitPos;
  19680. this.awaitIdentPos = oldAwaitIdentPos;
  19681. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  19682. }
  19683. this.checkExpressionErrors(refDestructuringErrors, true);
  19684. this.yieldPos = oldYieldPos || this.yieldPos;
  19685. this.awaitPos = oldAwaitPos || this.awaitPos;
  19686. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  19687. var node$1 = this.startNodeAt(startPos, startLoc);
  19688. node$1.callee = base;
  19689. node$1.arguments = exprList;
  19690. if (optionalSupported) {
  19691. node$1.optional = optional;
  19692. }
  19693. base = this.finishNode(node$1, "CallExpression");
  19694. } else if (this.type === types$1.backQuote) {
  19695. if (optional || optionalChained) {
  19696. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  19697. }
  19698. var node$2 = this.startNodeAt(startPos, startLoc);
  19699. node$2.tag = base;
  19700. node$2.quasi = this.parseTemplate({isTagged: true});
  19701. base = this.finishNode(node$2, "TaggedTemplateExpression");
  19702. }
  19703. return base
  19704. };
  19705. // Parse an atomic expression — either a single token that is an
  19706. // expression, an expression started by a keyword like `function` or
  19707. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  19708. // or `{}`.
  19709. pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
  19710. // If a division operator appears in an expression position, the
  19711. // tokenizer got confused, and we force it to read a regexp instead.
  19712. if (this.type === types$1.slash) { this.readRegexp(); }
  19713. var node, canBeArrow = this.potentialArrowAt === this.start;
  19714. switch (this.type) {
  19715. case types$1._super:
  19716. if (!this.allowSuper)
  19717. { this.raise(this.start, "'super' keyword outside a method"); }
  19718. node = this.startNode();
  19719. this.next();
  19720. if (this.type === types$1.parenL && !this.allowDirectSuper)
  19721. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  19722. // The `super` keyword can appear at below:
  19723. // SuperProperty:
  19724. // super [ Expression ]
  19725. // super . IdentifierName
  19726. // SuperCall:
  19727. // super ( Arguments )
  19728. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  19729. { this.unexpected(); }
  19730. return this.finishNode(node, "Super")
  19731. case types$1._this:
  19732. node = this.startNode();
  19733. this.next();
  19734. return this.finishNode(node, "ThisExpression")
  19735. case types$1.name:
  19736. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  19737. var id = this.parseIdent(false);
  19738. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  19739. this.overrideContext(types.f_expr);
  19740. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  19741. }
  19742. if (canBeArrow && !this.canInsertSemicolon()) {
  19743. if (this.eat(types$1.arrow))
  19744. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  19745. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  19746. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  19747. id = this.parseIdent(false);
  19748. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  19749. { this.unexpected(); }
  19750. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  19751. }
  19752. }
  19753. return id
  19754. case types$1.regexp:
  19755. var value = this.value;
  19756. node = this.parseLiteral(value.value);
  19757. node.regex = {pattern: value.pattern, flags: value.flags};
  19758. return node
  19759. case types$1.num: case types$1.string:
  19760. return this.parseLiteral(this.value)
  19761. case types$1._null: case types$1._true: case types$1._false:
  19762. node = this.startNode();
  19763. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  19764. node.raw = this.type.keyword;
  19765. this.next();
  19766. return this.finishNode(node, "Literal")
  19767. case types$1.parenL:
  19768. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  19769. if (refDestructuringErrors) {
  19770. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  19771. { refDestructuringErrors.parenthesizedAssign = start; }
  19772. if (refDestructuringErrors.parenthesizedBind < 0)
  19773. { refDestructuringErrors.parenthesizedBind = start; }
  19774. }
  19775. return expr
  19776. case types$1.bracketL:
  19777. node = this.startNode();
  19778. this.next();
  19779. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  19780. return this.finishNode(node, "ArrayExpression")
  19781. case types$1.braceL:
  19782. this.overrideContext(types.b_expr);
  19783. return this.parseObj(false, refDestructuringErrors)
  19784. case types$1._function:
  19785. node = this.startNode();
  19786. this.next();
  19787. return this.parseFunction(node, 0)
  19788. case types$1._class:
  19789. return this.parseClass(this.startNode(), false)
  19790. case types$1._new:
  19791. return this.parseNew()
  19792. case types$1.backQuote:
  19793. return this.parseTemplate()
  19794. case types$1._import:
  19795. if (this.options.ecmaVersion >= 11) {
  19796. return this.parseExprImport()
  19797. } else {
  19798. return this.unexpected()
  19799. }
  19800. default:
  19801. this.unexpected();
  19802. }
  19803. };
  19804. pp$5.parseExprImport = function() {
  19805. var node = this.startNode();
  19806. // Consume `import` as an identifier for `import.meta`.
  19807. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  19808. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  19809. var meta = this.parseIdent(true);
  19810. switch (this.type) {
  19811. case types$1.parenL:
  19812. return this.parseDynamicImport(node)
  19813. case types$1.dot:
  19814. node.meta = meta;
  19815. return this.parseImportMeta(node)
  19816. default:
  19817. this.unexpected();
  19818. }
  19819. };
  19820. pp$5.parseDynamicImport = function(node) {
  19821. this.next(); // skip `(`
  19822. // Parse node.source.
  19823. node.source = this.parseMaybeAssign();
  19824. // Verify ending.
  19825. if (!this.eat(types$1.parenR)) {
  19826. var errorPos = this.start;
  19827. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  19828. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  19829. } else {
  19830. this.unexpected(errorPos);
  19831. }
  19832. }
  19833. return this.finishNode(node, "ImportExpression")
  19834. };
  19835. pp$5.parseImportMeta = function(node) {
  19836. this.next(); // skip `.`
  19837. var containsEsc = this.containsEsc;
  19838. node.property = this.parseIdent(true);
  19839. if (node.property.name !== "meta")
  19840. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  19841. if (containsEsc)
  19842. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  19843. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  19844. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  19845. return this.finishNode(node, "MetaProperty")
  19846. };
  19847. pp$5.parseLiteral = function(value) {
  19848. var node = this.startNode();
  19849. node.value = value;
  19850. node.raw = this.input.slice(this.start, this.end);
  19851. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  19852. this.next();
  19853. return this.finishNode(node, "Literal")
  19854. };
  19855. pp$5.parseParenExpression = function() {
  19856. this.expect(types$1.parenL);
  19857. var val = this.parseExpression();
  19858. this.expect(types$1.parenR);
  19859. return val
  19860. };
  19861. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  19862. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  19863. if (this.options.ecmaVersion >= 6) {
  19864. this.next();
  19865. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  19866. var exprList = [], first = true, lastIsComma = false;
  19867. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  19868. this.yieldPos = 0;
  19869. this.awaitPos = 0;
  19870. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  19871. while (this.type !== types$1.parenR) {
  19872. first ? first = false : this.expect(types$1.comma);
  19873. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  19874. lastIsComma = true;
  19875. break
  19876. } else if (this.type === types$1.ellipsis) {
  19877. spreadStart = this.start;
  19878. exprList.push(this.parseParenItem(this.parseRestBinding()));
  19879. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  19880. break
  19881. } else {
  19882. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  19883. }
  19884. }
  19885. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  19886. this.expect(types$1.parenR);
  19887. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  19888. this.checkPatternErrors(refDestructuringErrors, false);
  19889. this.checkYieldAwaitInDefaultParams();
  19890. this.yieldPos = oldYieldPos;
  19891. this.awaitPos = oldAwaitPos;
  19892. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  19893. }
  19894. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  19895. if (spreadStart) { this.unexpected(spreadStart); }
  19896. this.checkExpressionErrors(refDestructuringErrors, true);
  19897. this.yieldPos = oldYieldPos || this.yieldPos;
  19898. this.awaitPos = oldAwaitPos || this.awaitPos;
  19899. if (exprList.length > 1) {
  19900. val = this.startNodeAt(innerStartPos, innerStartLoc);
  19901. val.expressions = exprList;
  19902. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  19903. } else {
  19904. val = exprList[0];
  19905. }
  19906. } else {
  19907. val = this.parseParenExpression();
  19908. }
  19909. if (this.options.preserveParens) {
  19910. var par = this.startNodeAt(startPos, startLoc);
  19911. par.expression = val;
  19912. return this.finishNode(par, "ParenthesizedExpression")
  19913. } else {
  19914. return val
  19915. }
  19916. };
  19917. pp$5.parseParenItem = function(item) {
  19918. return item
  19919. };
  19920. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  19921. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  19922. };
  19923. // New's precedence is slightly tricky. It must allow its argument to
  19924. // be a `[]` or dot subscript expression, but not a call — at least,
  19925. // not without wrapping it in parentheses. Thus, it uses the noCalls
  19926. // argument to parseSubscripts to prevent it from consuming the
  19927. // argument list.
  19928. var empty = [];
  19929. pp$5.parseNew = function() {
  19930. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  19931. var node = this.startNode();
  19932. var meta = this.parseIdent(true);
  19933. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  19934. node.meta = meta;
  19935. var containsEsc = this.containsEsc;
  19936. node.property = this.parseIdent(true);
  19937. if (node.property.name !== "target")
  19938. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  19939. if (containsEsc)
  19940. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  19941. if (!this.allowNewDotTarget)
  19942. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  19943. return this.finishNode(node, "MetaProperty")
  19944. }
  19945. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
  19946. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
  19947. if (isImport && node.callee.type === "ImportExpression") {
  19948. this.raise(startPos, "Cannot use new with import()");
  19949. }
  19950. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  19951. else { node.arguments = empty; }
  19952. return this.finishNode(node, "NewExpression")
  19953. };
  19954. // Parse template expression.
  19955. pp$5.parseTemplateElement = function(ref) {
  19956. var isTagged = ref.isTagged;
  19957. var elem = this.startNode();
  19958. if (this.type === types$1.invalidTemplate) {
  19959. if (!isTagged) {
  19960. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  19961. }
  19962. elem.value = {
  19963. raw: this.value,
  19964. cooked: null
  19965. };
  19966. } else {
  19967. elem.value = {
  19968. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  19969. cooked: this.value
  19970. };
  19971. }
  19972. this.next();
  19973. elem.tail = this.type === types$1.backQuote;
  19974. return this.finishNode(elem, "TemplateElement")
  19975. };
  19976. pp$5.parseTemplate = function(ref) {
  19977. if ( ref === void 0 ) ref = {};
  19978. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  19979. var node = this.startNode();
  19980. this.next();
  19981. node.expressions = [];
  19982. var curElt = this.parseTemplateElement({isTagged: isTagged});
  19983. node.quasis = [curElt];
  19984. while (!curElt.tail) {
  19985. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  19986. this.expect(types$1.dollarBraceL);
  19987. node.expressions.push(this.parseExpression());
  19988. this.expect(types$1.braceR);
  19989. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  19990. }
  19991. this.next();
  19992. return this.finishNode(node, "TemplateLiteral")
  19993. };
  19994. pp$5.isAsyncProp = function(prop) {
  19995. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  19996. (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)) &&
  19997. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  19998. };
  19999. // Parse an object literal or binding pattern.
  20000. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  20001. var node = this.startNode(), first = true, propHash = {};
  20002. node.properties = [];
  20003. this.next();
  20004. while (!this.eat(types$1.braceR)) {
  20005. if (!first) {
  20006. this.expect(types$1.comma);
  20007. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  20008. } else { first = false; }
  20009. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  20010. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  20011. node.properties.push(prop);
  20012. }
  20013. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  20014. };
  20015. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  20016. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  20017. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  20018. if (isPattern) {
  20019. prop.argument = this.parseIdent(false);
  20020. if (this.type === types$1.comma) {
  20021. this.raise(this.start, "Comma is not permitted after the rest element");
  20022. }
  20023. return this.finishNode(prop, "RestElement")
  20024. }
  20025. // Parse argument.
  20026. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  20027. // To disallow trailing comma via `this.toAssignable()`.
  20028. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  20029. refDestructuringErrors.trailingComma = this.start;
  20030. }
  20031. // Finish
  20032. return this.finishNode(prop, "SpreadElement")
  20033. }
  20034. if (this.options.ecmaVersion >= 6) {
  20035. prop.method = false;
  20036. prop.shorthand = false;
  20037. if (isPattern || refDestructuringErrors) {
  20038. startPos = this.start;
  20039. startLoc = this.startLoc;
  20040. }
  20041. if (!isPattern)
  20042. { isGenerator = this.eat(types$1.star); }
  20043. }
  20044. var containsEsc = this.containsEsc;
  20045. this.parsePropertyName(prop);
  20046. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  20047. isAsync = true;
  20048. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  20049. this.parsePropertyName(prop);
  20050. } else {
  20051. isAsync = false;
  20052. }
  20053. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  20054. return this.finishNode(prop, "Property")
  20055. };
  20056. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  20057. if ((isGenerator || isAsync) && this.type === types$1.colon)
  20058. { this.unexpected(); }
  20059. if (this.eat(types$1.colon)) {
  20060. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  20061. prop.kind = "init";
  20062. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  20063. if (isPattern) { this.unexpected(); }
  20064. prop.kind = "init";
  20065. prop.method = true;
  20066. prop.value = this.parseMethod(isGenerator, isAsync);
  20067. } else if (!isPattern && !containsEsc &&
  20068. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  20069. (prop.key.name === "get" || prop.key.name === "set") &&
  20070. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  20071. if (isGenerator || isAsync) { this.unexpected(); }
  20072. prop.kind = prop.key.name;
  20073. this.parsePropertyName(prop);
  20074. prop.value = this.parseMethod(false);
  20075. var paramCount = prop.kind === "get" ? 0 : 1;
  20076. if (prop.value.params.length !== paramCount) {
  20077. var start = prop.value.start;
  20078. if (prop.kind === "get")
  20079. { this.raiseRecoverable(start, "getter should have no params"); }
  20080. else
  20081. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  20082. } else {
  20083. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  20084. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  20085. }
  20086. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  20087. if (isGenerator || isAsync) { this.unexpected(); }
  20088. this.checkUnreserved(prop.key);
  20089. if (prop.key.name === "await" && !this.awaitIdentPos)
  20090. { this.awaitIdentPos = startPos; }
  20091. prop.kind = "init";
  20092. if (isPattern) {
  20093. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  20094. } else if (this.type === types$1.eq && refDestructuringErrors) {
  20095. if (refDestructuringErrors.shorthandAssign < 0)
  20096. { refDestructuringErrors.shorthandAssign = this.start; }
  20097. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  20098. } else {
  20099. prop.value = this.copyNode(prop.key);
  20100. }
  20101. prop.shorthand = true;
  20102. } else { this.unexpected(); }
  20103. };
  20104. pp$5.parsePropertyName = function(prop) {
  20105. if (this.options.ecmaVersion >= 6) {
  20106. if (this.eat(types$1.bracketL)) {
  20107. prop.computed = true;
  20108. prop.key = this.parseMaybeAssign();
  20109. this.expect(types$1.bracketR);
  20110. return prop.key
  20111. } else {
  20112. prop.computed = false;
  20113. }
  20114. }
  20115. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  20116. };
  20117. // Initialize empty function node.
  20118. pp$5.initFunction = function(node) {
  20119. node.id = null;
  20120. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  20121. if (this.options.ecmaVersion >= 8) { node.async = false; }
  20122. };
  20123. // Parse object or class method.
  20124. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  20125. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  20126. this.initFunction(node);
  20127. if (this.options.ecmaVersion >= 6)
  20128. { node.generator = isGenerator; }
  20129. if (this.options.ecmaVersion >= 8)
  20130. { node.async = !!isAsync; }
  20131. this.yieldPos = 0;
  20132. this.awaitPos = 0;
  20133. this.awaitIdentPos = 0;
  20134. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  20135. this.expect(types$1.parenL);
  20136. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  20137. this.checkYieldAwaitInDefaultParams();
  20138. this.parseFunctionBody(node, false, true, false);
  20139. this.yieldPos = oldYieldPos;
  20140. this.awaitPos = oldAwaitPos;
  20141. this.awaitIdentPos = oldAwaitIdentPos;
  20142. return this.finishNode(node, "FunctionExpression")
  20143. };
  20144. // Parse arrow function expression with given parameters.
  20145. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  20146. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  20147. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  20148. this.initFunction(node);
  20149. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  20150. this.yieldPos = 0;
  20151. this.awaitPos = 0;
  20152. this.awaitIdentPos = 0;
  20153. node.params = this.toAssignableList(params, true);
  20154. this.parseFunctionBody(node, true, false, forInit);
  20155. this.yieldPos = oldYieldPos;
  20156. this.awaitPos = oldAwaitPos;
  20157. this.awaitIdentPos = oldAwaitIdentPos;
  20158. return this.finishNode(node, "ArrowFunctionExpression")
  20159. };
  20160. // Parse function body and check parameters.
  20161. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  20162. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  20163. var oldStrict = this.strict, useStrict = false;
  20164. if (isExpression) {
  20165. node.body = this.parseMaybeAssign(forInit);
  20166. node.expression = true;
  20167. this.checkParams(node, false);
  20168. } else {
  20169. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  20170. if (!oldStrict || nonSimple) {
  20171. useStrict = this.strictDirective(this.end);
  20172. // If this is a strict mode function, verify that argument names
  20173. // are not repeated, and it does not try to bind the words `eval`
  20174. // or `arguments`.
  20175. if (useStrict && nonSimple)
  20176. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  20177. }
  20178. // Start a new scope with regard to labels and the `inFunction`
  20179. // flag (restore them to their old value afterwards).
  20180. var oldLabels = this.labels;
  20181. this.labels = [];
  20182. if (useStrict) { this.strict = true; }
  20183. // Add the params to varDeclaredNames to ensure that an error is thrown
  20184. // if a let/const declaration in the function clashes with one of the params.
  20185. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  20186. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  20187. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  20188. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  20189. node.expression = false;
  20190. this.adaptDirectivePrologue(node.body.body);
  20191. this.labels = oldLabels;
  20192. }
  20193. this.exitScope();
  20194. };
  20195. pp$5.isSimpleParamList = function(params) {
  20196. for (var i = 0, list = params; i < list.length; i += 1)
  20197. {
  20198. var param = list[i];
  20199. if (param.type !== "Identifier") { return false
  20200. } }
  20201. return true
  20202. };
  20203. // Checks function params for various disallowed patterns such as using "eval"
  20204. // or "arguments" and duplicate parameters.
  20205. pp$5.checkParams = function(node, allowDuplicates) {
  20206. var nameHash = Object.create(null);
  20207. for (var i = 0, list = node.params; i < list.length; i += 1)
  20208. {
  20209. var param = list[i];
  20210. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  20211. }
  20212. };
  20213. // Parses a comma-separated list of expressions, and returns them as
  20214. // an array. `close` is the token type that ends the list, and
  20215. // `allowEmpty` can be turned on to allow subsequent commas with
  20216. // nothing in between them to be parsed as `null` (which is needed
  20217. // for array literals).
  20218. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  20219. var elts = [], first = true;
  20220. while (!this.eat(close)) {
  20221. if (!first) {
  20222. this.expect(types$1.comma);
  20223. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  20224. } else { first = false; }
  20225. var elt = (void 0);
  20226. if (allowEmpty && this.type === types$1.comma)
  20227. { elt = null; }
  20228. else if (this.type === types$1.ellipsis) {
  20229. elt = this.parseSpread(refDestructuringErrors);
  20230. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  20231. { refDestructuringErrors.trailingComma = this.start; }
  20232. } else {
  20233. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  20234. }
  20235. elts.push(elt);
  20236. }
  20237. return elts
  20238. };
  20239. pp$5.checkUnreserved = function(ref) {
  20240. var start = ref.start;
  20241. var end = ref.end;
  20242. var name = ref.name;
  20243. if (this.inGenerator && name === "yield")
  20244. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  20245. if (this.inAsync && name === "await")
  20246. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  20247. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  20248. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  20249. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  20250. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  20251. if (this.keywords.test(name))
  20252. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  20253. if (this.options.ecmaVersion < 6 &&
  20254. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  20255. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  20256. if (re.test(name)) {
  20257. if (!this.inAsync && name === "await")
  20258. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  20259. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  20260. }
  20261. };
  20262. // Parse the next token as an identifier. If `liberal` is true (used
  20263. // when parsing properties), it will also convert keywords into
  20264. // identifiers.
  20265. pp$5.parseIdent = function(liberal) {
  20266. var node = this.startNode();
  20267. if (this.type === types$1.name) {
  20268. node.name = this.value;
  20269. } else if (this.type.keyword) {
  20270. node.name = this.type.keyword;
  20271. // To fix https://github.com/acornjs/acorn/issues/575
  20272. // `class` and `function` keywords push new context into this.context.
  20273. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  20274. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  20275. if ((node.name === "class" || node.name === "function") &&
  20276. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  20277. this.context.pop();
  20278. }
  20279. } else {
  20280. this.unexpected();
  20281. }
  20282. this.next(!!liberal);
  20283. this.finishNode(node, "Identifier");
  20284. if (!liberal) {
  20285. this.checkUnreserved(node);
  20286. if (node.name === "await" && !this.awaitIdentPos)
  20287. { this.awaitIdentPos = node.start; }
  20288. }
  20289. return node
  20290. };
  20291. pp$5.parsePrivateIdent = function() {
  20292. var node = this.startNode();
  20293. if (this.type === types$1.privateId) {
  20294. node.name = this.value;
  20295. } else {
  20296. this.unexpected();
  20297. }
  20298. this.next();
  20299. this.finishNode(node, "PrivateIdentifier");
  20300. // For validating existence
  20301. if (this.privateNameStack.length === 0) {
  20302. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  20303. } else {
  20304. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  20305. }
  20306. return node
  20307. };
  20308. // Parses yield expression inside generator.
  20309. pp$5.parseYield = function(forInit) {
  20310. if (!this.yieldPos) { this.yieldPos = this.start; }
  20311. var node = this.startNode();
  20312. this.next();
  20313. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  20314. node.delegate = false;
  20315. node.argument = null;
  20316. } else {
  20317. node.delegate = this.eat(types$1.star);
  20318. node.argument = this.parseMaybeAssign(forInit);
  20319. }
  20320. return this.finishNode(node, "YieldExpression")
  20321. };
  20322. pp$5.parseAwait = function(forInit) {
  20323. if (!this.awaitPos) { this.awaitPos = this.start; }
  20324. var node = this.startNode();
  20325. this.next();
  20326. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  20327. return this.finishNode(node, "AwaitExpression")
  20328. };
  20329. var pp$4 = Parser.prototype;
  20330. // This function is used to raise exceptions on parse errors. It
  20331. // takes an offset integer (into the current `input`) to indicate
  20332. // the location of the error, attaches the position to the end
  20333. // of the error message, and then raises a `SyntaxError` with that
  20334. // message.
  20335. pp$4.raise = function(pos, message) {
  20336. var loc = getLineInfo(this.input, pos);
  20337. message += " (" + loc.line + ":" + loc.column + ")";
  20338. var err = new SyntaxError(message);
  20339. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  20340. throw err
  20341. };
  20342. pp$4.raiseRecoverable = pp$4.raise;
  20343. pp$4.curPosition = function() {
  20344. if (this.options.locations) {
  20345. return new Position(this.curLine, this.pos - this.lineStart)
  20346. }
  20347. };
  20348. var pp$3 = Parser.prototype;
  20349. var Scope = function Scope(flags) {
  20350. this.flags = flags;
  20351. // A list of var-declared names in the current lexical scope
  20352. this.var = [];
  20353. // A list of lexically-declared names in the current lexical scope
  20354. this.lexical = [];
  20355. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  20356. this.functions = [];
  20357. // A switch to disallow the identifier reference 'arguments'
  20358. this.inClassFieldInit = false;
  20359. };
  20360. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  20361. pp$3.enterScope = function(flags) {
  20362. this.scopeStack.push(new Scope(flags));
  20363. };
  20364. pp$3.exitScope = function() {
  20365. this.scopeStack.pop();
  20366. };
  20367. // The spec says:
  20368. // > At the top level of a function, or script, function declarations are
  20369. // > treated like var declarations rather than like lexical declarations.
  20370. pp$3.treatFunctionsAsVarInScope = function(scope) {
  20371. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  20372. };
  20373. pp$3.declareName = function(name, bindingType, pos) {
  20374. var redeclared = false;
  20375. if (bindingType === BIND_LEXICAL) {
  20376. var scope = this.currentScope();
  20377. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  20378. scope.lexical.push(name);
  20379. if (this.inModule && (scope.flags & SCOPE_TOP))
  20380. { delete this.undefinedExports[name]; }
  20381. } else if (bindingType === BIND_SIMPLE_CATCH) {
  20382. var scope$1 = this.currentScope();
  20383. scope$1.lexical.push(name);
  20384. } else if (bindingType === BIND_FUNCTION) {
  20385. var scope$2 = this.currentScope();
  20386. if (this.treatFunctionsAsVar)
  20387. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  20388. else
  20389. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  20390. scope$2.functions.push(name);
  20391. } else {
  20392. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  20393. var scope$3 = this.scopeStack[i];
  20394. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  20395. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  20396. redeclared = true;
  20397. break
  20398. }
  20399. scope$3.var.push(name);
  20400. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  20401. { delete this.undefinedExports[name]; }
  20402. if (scope$3.flags & SCOPE_VAR) { break }
  20403. }
  20404. }
  20405. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  20406. };
  20407. pp$3.checkLocalExport = function(id) {
  20408. // scope.functions must be empty as Module code is always strict.
  20409. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  20410. this.scopeStack[0].var.indexOf(id.name) === -1) {
  20411. this.undefinedExports[id.name] = id;
  20412. }
  20413. };
  20414. pp$3.currentScope = function() {
  20415. return this.scopeStack[this.scopeStack.length - 1]
  20416. };
  20417. pp$3.currentVarScope = function() {
  20418. for (var i = this.scopeStack.length - 1;; i--) {
  20419. var scope = this.scopeStack[i];
  20420. if (scope.flags & SCOPE_VAR) { return scope }
  20421. }
  20422. };
  20423. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  20424. pp$3.currentThisScope = function() {
  20425. for (var i = this.scopeStack.length - 1;; i--) {
  20426. var scope = this.scopeStack[i];
  20427. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  20428. }
  20429. };
  20430. var Node = function Node(parser, pos, loc) {
  20431. this.type = "";
  20432. this.start = pos;
  20433. this.end = 0;
  20434. if (parser.options.locations)
  20435. { this.loc = new SourceLocation(parser, loc); }
  20436. if (parser.options.directSourceFile)
  20437. { this.sourceFile = parser.options.directSourceFile; }
  20438. if (parser.options.ranges)
  20439. { this.range = [pos, 0]; }
  20440. };
  20441. // Start an AST node, attaching a start offset.
  20442. var pp$2 = Parser.prototype;
  20443. pp$2.startNode = function() {
  20444. return new Node(this, this.start, this.startLoc)
  20445. };
  20446. pp$2.startNodeAt = function(pos, loc) {
  20447. return new Node(this, pos, loc)
  20448. };
  20449. // Finish an AST node, adding `type` and `end` properties.
  20450. function finishNodeAt(node, type, pos, loc) {
  20451. node.type = type;
  20452. node.end = pos;
  20453. if (this.options.locations)
  20454. { node.loc.end = loc; }
  20455. if (this.options.ranges)
  20456. { node.range[1] = pos; }
  20457. return node
  20458. }
  20459. pp$2.finishNode = function(node, type) {
  20460. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  20461. };
  20462. // Finish node at given position
  20463. pp$2.finishNodeAt = function(node, type, pos, loc) {
  20464. return finishNodeAt.call(this, node, type, pos, loc)
  20465. };
  20466. pp$2.copyNode = function(node) {
  20467. var newNode = new Node(this, node.start, this.startLoc);
  20468. for (var prop in node) { newNode[prop] = node[prop]; }
  20469. return newNode
  20470. };
  20471. // This file contains Unicode properties extracted from the ECMAScript specification.
  20472. // The lists are extracted like so:
  20473. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  20474. // #table-binary-unicode-properties
  20475. 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";
  20476. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  20477. var ecma11BinaryProperties = ecma10BinaryProperties;
  20478. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  20479. var ecma13BinaryProperties = ecma12BinaryProperties;
  20480. var ecma14BinaryProperties = ecma13BinaryProperties;
  20481. var unicodeBinaryProperties = {
  20482. 9: ecma9BinaryProperties,
  20483. 10: ecma10BinaryProperties,
  20484. 11: ecma11BinaryProperties,
  20485. 12: ecma12BinaryProperties,
  20486. 13: ecma13BinaryProperties,
  20487. 14: ecma14BinaryProperties
  20488. };
  20489. // #table-unicode-general-category-values
  20490. 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";
  20491. // #table-unicode-script-values
  20492. 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";
  20493. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  20494. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  20495. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  20496. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  20497. var ecma14ScriptValues = ecma13ScriptValues + " Kawi Nag_Mundari Nagm";
  20498. var unicodeScriptValues = {
  20499. 9: ecma9ScriptValues,
  20500. 10: ecma10ScriptValues,
  20501. 11: ecma11ScriptValues,
  20502. 12: ecma12ScriptValues,
  20503. 13: ecma13ScriptValues,
  20504. 14: ecma14ScriptValues
  20505. };
  20506. var data = {};
  20507. function buildUnicodeData(ecmaVersion) {
  20508. var d = data[ecmaVersion] = {
  20509. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  20510. nonBinary: {
  20511. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  20512. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  20513. }
  20514. };
  20515. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  20516. d.nonBinary.gc = d.nonBinary.General_Category;
  20517. d.nonBinary.sc = d.nonBinary.Script;
  20518. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  20519. }
  20520. for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) {
  20521. var ecmaVersion = list[i];
  20522. buildUnicodeData(ecmaVersion);
  20523. }
  20524. var pp$1 = Parser.prototype;
  20525. var RegExpValidationState = function RegExpValidationState(parser) {
  20526. this.parser = parser;
  20527. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  20528. this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
  20529. this.source = "";
  20530. this.flags = "";
  20531. this.start = 0;
  20532. this.switchU = false;
  20533. this.switchN = false;
  20534. this.pos = 0;
  20535. this.lastIntValue = 0;
  20536. this.lastStringValue = "";
  20537. this.lastAssertionIsQuantifiable = false;
  20538. this.numCapturingParens = 0;
  20539. this.maxBackReference = 0;
  20540. this.groupNames = [];
  20541. this.backReferenceNames = [];
  20542. };
  20543. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  20544. var unicode = flags.indexOf("u") !== -1;
  20545. this.start = start | 0;
  20546. this.source = pattern + "";
  20547. this.flags = flags;
  20548. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  20549. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  20550. };
  20551. RegExpValidationState.prototype.raise = function raise (message) {
  20552. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  20553. };
  20554. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  20555. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  20556. RegExpValidationState.prototype.at = function at (i, forceU) {
  20557. if ( forceU === void 0 ) forceU = false;
  20558. var s = this.source;
  20559. var l = s.length;
  20560. if (i >= l) {
  20561. return -1
  20562. }
  20563. var c = s.charCodeAt(i);
  20564. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  20565. return c
  20566. }
  20567. var next = s.charCodeAt(i + 1);
  20568. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  20569. };
  20570. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  20571. if ( forceU === void 0 ) forceU = false;
  20572. var s = this.source;
  20573. var l = s.length;
  20574. if (i >= l) {
  20575. return l
  20576. }
  20577. var c = s.charCodeAt(i), next;
  20578. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  20579. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  20580. return i + 1
  20581. }
  20582. return i + 2
  20583. };
  20584. RegExpValidationState.prototype.current = function current (forceU) {
  20585. if ( forceU === void 0 ) forceU = false;
  20586. return this.at(this.pos, forceU)
  20587. };
  20588. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  20589. if ( forceU === void 0 ) forceU = false;
  20590. return this.at(this.nextIndex(this.pos, forceU), forceU)
  20591. };
  20592. RegExpValidationState.prototype.advance = function advance (forceU) {
  20593. if ( forceU === void 0 ) forceU = false;
  20594. this.pos = this.nextIndex(this.pos, forceU);
  20595. };
  20596. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  20597. if ( forceU === void 0 ) forceU = false;
  20598. if (this.current(forceU) === ch) {
  20599. this.advance(forceU);
  20600. return true
  20601. }
  20602. return false
  20603. };
  20604. /**
  20605. * Validate the flags part of a given RegExpLiteral.
  20606. *
  20607. * @param {RegExpValidationState} state The state to validate RegExp.
  20608. * @returns {void}
  20609. */
  20610. pp$1.validateRegExpFlags = function(state) {
  20611. var validFlags = state.validFlags;
  20612. var flags = state.flags;
  20613. for (var i = 0; i < flags.length; i++) {
  20614. var flag = flags.charAt(i);
  20615. if (validFlags.indexOf(flag) === -1) {
  20616. this.raise(state.start, "Invalid regular expression flag");
  20617. }
  20618. if (flags.indexOf(flag, i + 1) > -1) {
  20619. this.raise(state.start, "Duplicate regular expression flag");
  20620. }
  20621. }
  20622. };
  20623. /**
  20624. * Validate the pattern part of a given RegExpLiteral.
  20625. *
  20626. * @param {RegExpValidationState} state The state to validate RegExp.
  20627. * @returns {void}
  20628. */
  20629. pp$1.validateRegExpPattern = function(state) {
  20630. this.regexp_pattern(state);
  20631. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  20632. // parsing contains a |GroupName|, reparse with the goal symbol
  20633. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  20634. // exception if _P_ did not conform to the grammar, if any elements of _P_
  20635. // were not matched by the parse, or if any Early Error conditions exist.
  20636. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  20637. state.switchN = true;
  20638. this.regexp_pattern(state);
  20639. }
  20640. };
  20641. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  20642. pp$1.regexp_pattern = function(state) {
  20643. state.pos = 0;
  20644. state.lastIntValue = 0;
  20645. state.lastStringValue = "";
  20646. state.lastAssertionIsQuantifiable = false;
  20647. state.numCapturingParens = 0;
  20648. state.maxBackReference = 0;
  20649. state.groupNames.length = 0;
  20650. state.backReferenceNames.length = 0;
  20651. this.regexp_disjunction(state);
  20652. if (state.pos !== state.source.length) {
  20653. // Make the same messages as V8.
  20654. if (state.eat(0x29 /* ) */)) {
  20655. state.raise("Unmatched ')'");
  20656. }
  20657. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  20658. state.raise("Lone quantifier brackets");
  20659. }
  20660. }
  20661. if (state.maxBackReference > state.numCapturingParens) {
  20662. state.raise("Invalid escape");
  20663. }
  20664. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  20665. var name = list[i];
  20666. if (state.groupNames.indexOf(name) === -1) {
  20667. state.raise("Invalid named capture referenced");
  20668. }
  20669. }
  20670. };
  20671. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  20672. pp$1.regexp_disjunction = function(state) {
  20673. this.regexp_alternative(state);
  20674. while (state.eat(0x7C /* | */)) {
  20675. this.regexp_alternative(state);
  20676. }
  20677. // Make the same message as V8.
  20678. if (this.regexp_eatQuantifier(state, true)) {
  20679. state.raise("Nothing to repeat");
  20680. }
  20681. if (state.eat(0x7B /* { */)) {
  20682. state.raise("Lone quantifier brackets");
  20683. }
  20684. };
  20685. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  20686. pp$1.regexp_alternative = function(state) {
  20687. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  20688. { }
  20689. };
  20690. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  20691. pp$1.regexp_eatTerm = function(state) {
  20692. if (this.regexp_eatAssertion(state)) {
  20693. // Handle `QuantifiableAssertion Quantifier` alternative.
  20694. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  20695. // is a QuantifiableAssertion.
  20696. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  20697. // Make the same message as V8.
  20698. if (state.switchU) {
  20699. state.raise("Invalid quantifier");
  20700. }
  20701. }
  20702. return true
  20703. }
  20704. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  20705. this.regexp_eatQuantifier(state);
  20706. return true
  20707. }
  20708. return false
  20709. };
  20710. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  20711. pp$1.regexp_eatAssertion = function(state) {
  20712. var start = state.pos;
  20713. state.lastAssertionIsQuantifiable = false;
  20714. // ^, $
  20715. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  20716. return true
  20717. }
  20718. // \b \B
  20719. if (state.eat(0x5C /* \ */)) {
  20720. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  20721. return true
  20722. }
  20723. state.pos = start;
  20724. }
  20725. // Lookahead / Lookbehind
  20726. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  20727. var lookbehind = false;
  20728. if (this.options.ecmaVersion >= 9) {
  20729. lookbehind = state.eat(0x3C /* < */);
  20730. }
  20731. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  20732. this.regexp_disjunction(state);
  20733. if (!state.eat(0x29 /* ) */)) {
  20734. state.raise("Unterminated group");
  20735. }
  20736. state.lastAssertionIsQuantifiable = !lookbehind;
  20737. return true
  20738. }
  20739. }
  20740. state.pos = start;
  20741. return false
  20742. };
  20743. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  20744. pp$1.regexp_eatQuantifier = function(state, noError) {
  20745. if ( noError === void 0 ) noError = false;
  20746. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  20747. state.eat(0x3F /* ? */);
  20748. return true
  20749. }
  20750. return false
  20751. };
  20752. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  20753. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  20754. return (
  20755. state.eat(0x2A /* * */) ||
  20756. state.eat(0x2B /* + */) ||
  20757. state.eat(0x3F /* ? */) ||
  20758. this.regexp_eatBracedQuantifier(state, noError)
  20759. )
  20760. };
  20761. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  20762. var start = state.pos;
  20763. if (state.eat(0x7B /* { */)) {
  20764. var min = 0, max = -1;
  20765. if (this.regexp_eatDecimalDigits(state)) {
  20766. min = state.lastIntValue;
  20767. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  20768. max = state.lastIntValue;
  20769. }
  20770. if (state.eat(0x7D /* } */)) {
  20771. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  20772. if (max !== -1 && max < min && !noError) {
  20773. state.raise("numbers out of order in {} quantifier");
  20774. }
  20775. return true
  20776. }
  20777. }
  20778. if (state.switchU && !noError) {
  20779. state.raise("Incomplete quantifier");
  20780. }
  20781. state.pos = start;
  20782. }
  20783. return false
  20784. };
  20785. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  20786. pp$1.regexp_eatAtom = function(state) {
  20787. return (
  20788. this.regexp_eatPatternCharacters(state) ||
  20789. state.eat(0x2E /* . */) ||
  20790. this.regexp_eatReverseSolidusAtomEscape(state) ||
  20791. this.regexp_eatCharacterClass(state) ||
  20792. this.regexp_eatUncapturingGroup(state) ||
  20793. this.regexp_eatCapturingGroup(state)
  20794. )
  20795. };
  20796. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  20797. var start = state.pos;
  20798. if (state.eat(0x5C /* \ */)) {
  20799. if (this.regexp_eatAtomEscape(state)) {
  20800. return true
  20801. }
  20802. state.pos = start;
  20803. }
  20804. return false
  20805. };
  20806. pp$1.regexp_eatUncapturingGroup = function(state) {
  20807. var start = state.pos;
  20808. if (state.eat(0x28 /* ( */)) {
  20809. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  20810. this.regexp_disjunction(state);
  20811. if (state.eat(0x29 /* ) */)) {
  20812. return true
  20813. }
  20814. state.raise("Unterminated group");
  20815. }
  20816. state.pos = start;
  20817. }
  20818. return false
  20819. };
  20820. pp$1.regexp_eatCapturingGroup = function(state) {
  20821. if (state.eat(0x28 /* ( */)) {
  20822. if (this.options.ecmaVersion >= 9) {
  20823. this.regexp_groupSpecifier(state);
  20824. } else if (state.current() === 0x3F /* ? */) {
  20825. state.raise("Invalid group");
  20826. }
  20827. this.regexp_disjunction(state);
  20828. if (state.eat(0x29 /* ) */)) {
  20829. state.numCapturingParens += 1;
  20830. return true
  20831. }
  20832. state.raise("Unterminated group");
  20833. }
  20834. return false
  20835. };
  20836. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  20837. pp$1.regexp_eatExtendedAtom = function(state) {
  20838. return (
  20839. state.eat(0x2E /* . */) ||
  20840. this.regexp_eatReverseSolidusAtomEscape(state) ||
  20841. this.regexp_eatCharacterClass(state) ||
  20842. this.regexp_eatUncapturingGroup(state) ||
  20843. this.regexp_eatCapturingGroup(state) ||
  20844. this.regexp_eatInvalidBracedQuantifier(state) ||
  20845. this.regexp_eatExtendedPatternCharacter(state)
  20846. )
  20847. };
  20848. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  20849. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  20850. if (this.regexp_eatBracedQuantifier(state, true)) {
  20851. state.raise("Nothing to repeat");
  20852. }
  20853. return false
  20854. };
  20855. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  20856. pp$1.regexp_eatSyntaxCharacter = function(state) {
  20857. var ch = state.current();
  20858. if (isSyntaxCharacter(ch)) {
  20859. state.lastIntValue = ch;
  20860. state.advance();
  20861. return true
  20862. }
  20863. return false
  20864. };
  20865. function isSyntaxCharacter(ch) {
  20866. return (
  20867. ch === 0x24 /* $ */ ||
  20868. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  20869. ch === 0x2E /* . */ ||
  20870. ch === 0x3F /* ? */ ||
  20871. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  20872. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  20873. )
  20874. }
  20875. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  20876. // But eat eager.
  20877. pp$1.regexp_eatPatternCharacters = function(state) {
  20878. var start = state.pos;
  20879. var ch = 0;
  20880. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  20881. state.advance();
  20882. }
  20883. return state.pos !== start
  20884. };
  20885. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  20886. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  20887. var ch = state.current();
  20888. if (
  20889. ch !== -1 &&
  20890. ch !== 0x24 /* $ */ &&
  20891. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  20892. ch !== 0x2E /* . */ &&
  20893. ch !== 0x3F /* ? */ &&
  20894. ch !== 0x5B /* [ */ &&
  20895. ch !== 0x5E /* ^ */ &&
  20896. ch !== 0x7C /* | */
  20897. ) {
  20898. state.advance();
  20899. return true
  20900. }
  20901. return false
  20902. };
  20903. // GroupSpecifier ::
  20904. // [empty]
  20905. // `?` GroupName
  20906. pp$1.regexp_groupSpecifier = function(state) {
  20907. if (state.eat(0x3F /* ? */)) {
  20908. if (this.regexp_eatGroupName(state)) {
  20909. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  20910. state.raise("Duplicate capture group name");
  20911. }
  20912. state.groupNames.push(state.lastStringValue);
  20913. return
  20914. }
  20915. state.raise("Invalid group");
  20916. }
  20917. };
  20918. // GroupName ::
  20919. // `<` RegExpIdentifierName `>`
  20920. // Note: this updates `state.lastStringValue` property with the eaten name.
  20921. pp$1.regexp_eatGroupName = function(state) {
  20922. state.lastStringValue = "";
  20923. if (state.eat(0x3C /* < */)) {
  20924. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  20925. return true
  20926. }
  20927. state.raise("Invalid capture group name");
  20928. }
  20929. return false
  20930. };
  20931. // RegExpIdentifierName ::
  20932. // RegExpIdentifierStart
  20933. // RegExpIdentifierName RegExpIdentifierPart
  20934. // Note: this updates `state.lastStringValue` property with the eaten name.
  20935. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  20936. state.lastStringValue = "";
  20937. if (this.regexp_eatRegExpIdentifierStart(state)) {
  20938. state.lastStringValue += codePointToString(state.lastIntValue);
  20939. while (this.regexp_eatRegExpIdentifierPart(state)) {
  20940. state.lastStringValue += codePointToString(state.lastIntValue);
  20941. }
  20942. return true
  20943. }
  20944. return false
  20945. };
  20946. // RegExpIdentifierStart ::
  20947. // UnicodeIDStart
  20948. // `$`
  20949. // `_`
  20950. // `\` RegExpUnicodeEscapeSequence[+U]
  20951. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  20952. var start = state.pos;
  20953. var forceU = this.options.ecmaVersion >= 11;
  20954. var ch = state.current(forceU);
  20955. state.advance(forceU);
  20956. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  20957. ch = state.lastIntValue;
  20958. }
  20959. if (isRegExpIdentifierStart(ch)) {
  20960. state.lastIntValue = ch;
  20961. return true
  20962. }
  20963. state.pos = start;
  20964. return false
  20965. };
  20966. function isRegExpIdentifierStart(ch) {
  20967. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  20968. }
  20969. // RegExpIdentifierPart ::
  20970. // UnicodeIDContinue
  20971. // `$`
  20972. // `_`
  20973. // `\` RegExpUnicodeEscapeSequence[+U]
  20974. // <ZWNJ>
  20975. // <ZWJ>
  20976. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  20977. var start = state.pos;
  20978. var forceU = this.options.ecmaVersion >= 11;
  20979. var ch = state.current(forceU);
  20980. state.advance(forceU);
  20981. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  20982. ch = state.lastIntValue;
  20983. }
  20984. if (isRegExpIdentifierPart(ch)) {
  20985. state.lastIntValue = ch;
  20986. return true
  20987. }
  20988. state.pos = start;
  20989. return false
  20990. };
  20991. function isRegExpIdentifierPart(ch) {
  20992. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  20993. }
  20994. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  20995. pp$1.regexp_eatAtomEscape = function(state) {
  20996. if (
  20997. this.regexp_eatBackReference(state) ||
  20998. this.regexp_eatCharacterClassEscape(state) ||
  20999. this.regexp_eatCharacterEscape(state) ||
  21000. (state.switchN && this.regexp_eatKGroupName(state))
  21001. ) {
  21002. return true
  21003. }
  21004. if (state.switchU) {
  21005. // Make the same message as V8.
  21006. if (state.current() === 0x63 /* c */) {
  21007. state.raise("Invalid unicode escape");
  21008. }
  21009. state.raise("Invalid escape");
  21010. }
  21011. return false
  21012. };
  21013. pp$1.regexp_eatBackReference = function(state) {
  21014. var start = state.pos;
  21015. if (this.regexp_eatDecimalEscape(state)) {
  21016. var n = state.lastIntValue;
  21017. if (state.switchU) {
  21018. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  21019. if (n > state.maxBackReference) {
  21020. state.maxBackReference = n;
  21021. }
  21022. return true
  21023. }
  21024. if (n <= state.numCapturingParens) {
  21025. return true
  21026. }
  21027. state.pos = start;
  21028. }
  21029. return false
  21030. };
  21031. pp$1.regexp_eatKGroupName = function(state) {
  21032. if (state.eat(0x6B /* k */)) {
  21033. if (this.regexp_eatGroupName(state)) {
  21034. state.backReferenceNames.push(state.lastStringValue);
  21035. return true
  21036. }
  21037. state.raise("Invalid named reference");
  21038. }
  21039. return false
  21040. };
  21041. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  21042. pp$1.regexp_eatCharacterEscape = function(state) {
  21043. return (
  21044. this.regexp_eatControlEscape(state) ||
  21045. this.regexp_eatCControlLetter(state) ||
  21046. this.regexp_eatZero(state) ||
  21047. this.regexp_eatHexEscapeSequence(state) ||
  21048. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  21049. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  21050. this.regexp_eatIdentityEscape(state)
  21051. )
  21052. };
  21053. pp$1.regexp_eatCControlLetter = function(state) {
  21054. var start = state.pos;
  21055. if (state.eat(0x63 /* c */)) {
  21056. if (this.regexp_eatControlLetter(state)) {
  21057. return true
  21058. }
  21059. state.pos = start;
  21060. }
  21061. return false
  21062. };
  21063. pp$1.regexp_eatZero = function(state) {
  21064. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  21065. state.lastIntValue = 0;
  21066. state.advance();
  21067. return true
  21068. }
  21069. return false
  21070. };
  21071. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  21072. pp$1.regexp_eatControlEscape = function(state) {
  21073. var ch = state.current();
  21074. if (ch === 0x74 /* t */) {
  21075. state.lastIntValue = 0x09; /* \t */
  21076. state.advance();
  21077. return true
  21078. }
  21079. if (ch === 0x6E /* n */) {
  21080. state.lastIntValue = 0x0A; /* \n */
  21081. state.advance();
  21082. return true
  21083. }
  21084. if (ch === 0x76 /* v */) {
  21085. state.lastIntValue = 0x0B; /* \v */
  21086. state.advance();
  21087. return true
  21088. }
  21089. if (ch === 0x66 /* f */) {
  21090. state.lastIntValue = 0x0C; /* \f */
  21091. state.advance();
  21092. return true
  21093. }
  21094. if (ch === 0x72 /* r */) {
  21095. state.lastIntValue = 0x0D; /* \r */
  21096. state.advance();
  21097. return true
  21098. }
  21099. return false
  21100. };
  21101. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  21102. pp$1.regexp_eatControlLetter = function(state) {
  21103. var ch = state.current();
  21104. if (isControlLetter(ch)) {
  21105. state.lastIntValue = ch % 0x20;
  21106. state.advance();
  21107. return true
  21108. }
  21109. return false
  21110. };
  21111. function isControlLetter(ch) {
  21112. return (
  21113. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  21114. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  21115. )
  21116. }
  21117. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  21118. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  21119. if ( forceU === void 0 ) forceU = false;
  21120. var start = state.pos;
  21121. var switchU = forceU || state.switchU;
  21122. if (state.eat(0x75 /* u */)) {
  21123. if (this.regexp_eatFixedHexDigits(state, 4)) {
  21124. var lead = state.lastIntValue;
  21125. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  21126. var leadSurrogateEnd = state.pos;
  21127. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  21128. var trail = state.lastIntValue;
  21129. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  21130. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  21131. return true
  21132. }
  21133. }
  21134. state.pos = leadSurrogateEnd;
  21135. state.lastIntValue = lead;
  21136. }
  21137. return true
  21138. }
  21139. if (
  21140. switchU &&
  21141. state.eat(0x7B /* { */) &&
  21142. this.regexp_eatHexDigits(state) &&
  21143. state.eat(0x7D /* } */) &&
  21144. isValidUnicode(state.lastIntValue)
  21145. ) {
  21146. return true
  21147. }
  21148. if (switchU) {
  21149. state.raise("Invalid unicode escape");
  21150. }
  21151. state.pos = start;
  21152. }
  21153. return false
  21154. };
  21155. function isValidUnicode(ch) {
  21156. return ch >= 0 && ch <= 0x10FFFF
  21157. }
  21158. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  21159. pp$1.regexp_eatIdentityEscape = function(state) {
  21160. if (state.switchU) {
  21161. if (this.regexp_eatSyntaxCharacter(state)) {
  21162. return true
  21163. }
  21164. if (state.eat(0x2F /* / */)) {
  21165. state.lastIntValue = 0x2F; /* / */
  21166. return true
  21167. }
  21168. return false
  21169. }
  21170. var ch = state.current();
  21171. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  21172. state.lastIntValue = ch;
  21173. state.advance();
  21174. return true
  21175. }
  21176. return false
  21177. };
  21178. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  21179. pp$1.regexp_eatDecimalEscape = function(state) {
  21180. state.lastIntValue = 0;
  21181. var ch = state.current();
  21182. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  21183. do {
  21184. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  21185. state.advance();
  21186. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  21187. return true
  21188. }
  21189. return false
  21190. };
  21191. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  21192. pp$1.regexp_eatCharacterClassEscape = function(state) {
  21193. var ch = state.current();
  21194. if (isCharacterClassEscape(ch)) {
  21195. state.lastIntValue = -1;
  21196. state.advance();
  21197. return true
  21198. }
  21199. if (
  21200. state.switchU &&
  21201. this.options.ecmaVersion >= 9 &&
  21202. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  21203. ) {
  21204. state.lastIntValue = -1;
  21205. state.advance();
  21206. if (
  21207. state.eat(0x7B /* { */) &&
  21208. this.regexp_eatUnicodePropertyValueExpression(state) &&
  21209. state.eat(0x7D /* } */)
  21210. ) {
  21211. return true
  21212. }
  21213. state.raise("Invalid property name");
  21214. }
  21215. return false
  21216. };
  21217. function isCharacterClassEscape(ch) {
  21218. return (
  21219. ch === 0x64 /* d */ ||
  21220. ch === 0x44 /* D */ ||
  21221. ch === 0x73 /* s */ ||
  21222. ch === 0x53 /* S */ ||
  21223. ch === 0x77 /* w */ ||
  21224. ch === 0x57 /* W */
  21225. )
  21226. }
  21227. // UnicodePropertyValueExpression ::
  21228. // UnicodePropertyName `=` UnicodePropertyValue
  21229. // LoneUnicodePropertyNameOrValue
  21230. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  21231. var start = state.pos;
  21232. // UnicodePropertyName `=` UnicodePropertyValue
  21233. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  21234. var name = state.lastStringValue;
  21235. if (this.regexp_eatUnicodePropertyValue(state)) {
  21236. var value = state.lastStringValue;
  21237. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  21238. return true
  21239. }
  21240. }
  21241. state.pos = start;
  21242. // LoneUnicodePropertyNameOrValue
  21243. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  21244. var nameOrValue = state.lastStringValue;
  21245. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  21246. return true
  21247. }
  21248. return false
  21249. };
  21250. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  21251. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  21252. { state.raise("Invalid property name"); }
  21253. if (!state.unicodeProperties.nonBinary[name].test(value))
  21254. { state.raise("Invalid property value"); }
  21255. };
  21256. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  21257. if (!state.unicodeProperties.binary.test(nameOrValue))
  21258. { state.raise("Invalid property name"); }
  21259. };
  21260. // UnicodePropertyName ::
  21261. // UnicodePropertyNameCharacters
  21262. pp$1.regexp_eatUnicodePropertyName = function(state) {
  21263. var ch = 0;
  21264. state.lastStringValue = "";
  21265. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  21266. state.lastStringValue += codePointToString(ch);
  21267. state.advance();
  21268. }
  21269. return state.lastStringValue !== ""
  21270. };
  21271. function isUnicodePropertyNameCharacter(ch) {
  21272. return isControlLetter(ch) || ch === 0x5F /* _ */
  21273. }
  21274. // UnicodePropertyValue ::
  21275. // UnicodePropertyValueCharacters
  21276. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  21277. var ch = 0;
  21278. state.lastStringValue = "";
  21279. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  21280. state.lastStringValue += codePointToString(ch);
  21281. state.advance();
  21282. }
  21283. return state.lastStringValue !== ""
  21284. };
  21285. function isUnicodePropertyValueCharacter(ch) {
  21286. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  21287. }
  21288. // LoneUnicodePropertyNameOrValue ::
  21289. // UnicodePropertyValueCharacters
  21290. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  21291. return this.regexp_eatUnicodePropertyValue(state)
  21292. };
  21293. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  21294. pp$1.regexp_eatCharacterClass = function(state) {
  21295. if (state.eat(0x5B /* [ */)) {
  21296. state.eat(0x5E /* ^ */);
  21297. this.regexp_classRanges(state);
  21298. if (state.eat(0x5D /* ] */)) {
  21299. return true
  21300. }
  21301. // Unreachable since it threw "unterminated regular expression" error before.
  21302. state.raise("Unterminated character class");
  21303. }
  21304. return false
  21305. };
  21306. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  21307. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  21308. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  21309. pp$1.regexp_classRanges = function(state) {
  21310. while (this.regexp_eatClassAtom(state)) {
  21311. var left = state.lastIntValue;
  21312. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  21313. var right = state.lastIntValue;
  21314. if (state.switchU && (left === -1 || right === -1)) {
  21315. state.raise("Invalid character class");
  21316. }
  21317. if (left !== -1 && right !== -1 && left > right) {
  21318. state.raise("Range out of order in character class");
  21319. }
  21320. }
  21321. }
  21322. };
  21323. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  21324. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  21325. pp$1.regexp_eatClassAtom = function(state) {
  21326. var start = state.pos;
  21327. if (state.eat(0x5C /* \ */)) {
  21328. if (this.regexp_eatClassEscape(state)) {
  21329. return true
  21330. }
  21331. if (state.switchU) {
  21332. // Make the same message as V8.
  21333. var ch$1 = state.current();
  21334. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  21335. state.raise("Invalid class escape");
  21336. }
  21337. state.raise("Invalid escape");
  21338. }
  21339. state.pos = start;
  21340. }
  21341. var ch = state.current();
  21342. if (ch !== 0x5D /* ] */) {
  21343. state.lastIntValue = ch;
  21344. state.advance();
  21345. return true
  21346. }
  21347. return false
  21348. };
  21349. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  21350. pp$1.regexp_eatClassEscape = function(state) {
  21351. var start = state.pos;
  21352. if (state.eat(0x62 /* b */)) {
  21353. state.lastIntValue = 0x08; /* <BS> */
  21354. return true
  21355. }
  21356. if (state.switchU && state.eat(0x2D /* - */)) {
  21357. state.lastIntValue = 0x2D; /* - */
  21358. return true
  21359. }
  21360. if (!state.switchU && state.eat(0x63 /* c */)) {
  21361. if (this.regexp_eatClassControlLetter(state)) {
  21362. return true
  21363. }
  21364. state.pos = start;
  21365. }
  21366. return (
  21367. this.regexp_eatCharacterClassEscape(state) ||
  21368. this.regexp_eatCharacterEscape(state)
  21369. )
  21370. };
  21371. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  21372. pp$1.regexp_eatClassControlLetter = function(state) {
  21373. var ch = state.current();
  21374. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  21375. state.lastIntValue = ch % 0x20;
  21376. state.advance();
  21377. return true
  21378. }
  21379. return false
  21380. };
  21381. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  21382. pp$1.regexp_eatHexEscapeSequence = function(state) {
  21383. var start = state.pos;
  21384. if (state.eat(0x78 /* x */)) {
  21385. if (this.regexp_eatFixedHexDigits(state, 2)) {
  21386. return true
  21387. }
  21388. if (state.switchU) {
  21389. state.raise("Invalid escape");
  21390. }
  21391. state.pos = start;
  21392. }
  21393. return false
  21394. };
  21395. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  21396. pp$1.regexp_eatDecimalDigits = function(state) {
  21397. var start = state.pos;
  21398. var ch = 0;
  21399. state.lastIntValue = 0;
  21400. while (isDecimalDigit(ch = state.current())) {
  21401. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  21402. state.advance();
  21403. }
  21404. return state.pos !== start
  21405. };
  21406. function isDecimalDigit(ch) {
  21407. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  21408. }
  21409. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  21410. pp$1.regexp_eatHexDigits = function(state) {
  21411. var start = state.pos;
  21412. var ch = 0;
  21413. state.lastIntValue = 0;
  21414. while (isHexDigit(ch = state.current())) {
  21415. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  21416. state.advance();
  21417. }
  21418. return state.pos !== start
  21419. };
  21420. function isHexDigit(ch) {
  21421. return (
  21422. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  21423. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  21424. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  21425. )
  21426. }
  21427. function hexToInt(ch) {
  21428. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  21429. return 10 + (ch - 0x41 /* A */)
  21430. }
  21431. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  21432. return 10 + (ch - 0x61 /* a */)
  21433. }
  21434. return ch - 0x30 /* 0 */
  21435. }
  21436. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  21437. // Allows only 0-377(octal) i.e. 0-255(decimal).
  21438. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  21439. if (this.regexp_eatOctalDigit(state)) {
  21440. var n1 = state.lastIntValue;
  21441. if (this.regexp_eatOctalDigit(state)) {
  21442. var n2 = state.lastIntValue;
  21443. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  21444. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  21445. } else {
  21446. state.lastIntValue = n1 * 8 + n2;
  21447. }
  21448. } else {
  21449. state.lastIntValue = n1;
  21450. }
  21451. return true
  21452. }
  21453. return false
  21454. };
  21455. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  21456. pp$1.regexp_eatOctalDigit = function(state) {
  21457. var ch = state.current();
  21458. if (isOctalDigit(ch)) {
  21459. state.lastIntValue = ch - 0x30; /* 0 */
  21460. state.advance();
  21461. return true
  21462. }
  21463. state.lastIntValue = 0;
  21464. return false
  21465. };
  21466. function isOctalDigit(ch) {
  21467. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  21468. }
  21469. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  21470. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  21471. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  21472. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  21473. var start = state.pos;
  21474. state.lastIntValue = 0;
  21475. for (var i = 0; i < length; ++i) {
  21476. var ch = state.current();
  21477. if (!isHexDigit(ch)) {
  21478. state.pos = start;
  21479. return false
  21480. }
  21481. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  21482. state.advance();
  21483. }
  21484. return true
  21485. };
  21486. // Object type used to represent tokens. Note that normally, tokens
  21487. // simply exist as properties on the parser object. This is only
  21488. // used for the onToken callback and the external tokenizer.
  21489. var Token = function Token(p) {
  21490. this.type = p.type;
  21491. this.value = p.value;
  21492. this.start = p.start;
  21493. this.end = p.end;
  21494. if (p.options.locations)
  21495. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  21496. if (p.options.ranges)
  21497. { this.range = [p.start, p.end]; }
  21498. };
  21499. // ## Tokenizer
  21500. var pp = Parser.prototype;
  21501. // Move to the next token
  21502. pp.next = function(ignoreEscapeSequenceInKeyword) {
  21503. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  21504. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  21505. if (this.options.onToken)
  21506. { this.options.onToken(new Token(this)); }
  21507. this.lastTokEnd = this.end;
  21508. this.lastTokStart = this.start;
  21509. this.lastTokEndLoc = this.endLoc;
  21510. this.lastTokStartLoc = this.startLoc;
  21511. this.nextToken();
  21512. };
  21513. pp.getToken = function() {
  21514. this.next();
  21515. return new Token(this)
  21516. };
  21517. // If we're in an ES6 environment, make parsers iterable
  21518. if (typeof Symbol !== "undefined")
  21519. { pp[Symbol.iterator] = function() {
  21520. var this$1$1 = this;
  21521. return {
  21522. next: function () {
  21523. var token = this$1$1.getToken();
  21524. return {
  21525. done: token.type === types$1.eof,
  21526. value: token
  21527. }
  21528. }
  21529. }
  21530. }; }
  21531. // Toggle strict mode. Re-reads the next number or string to please
  21532. // pedantic tests (`"use strict"; 010;` should fail).
  21533. // Read a single token, updating the parser object's token-related
  21534. // properties.
  21535. pp.nextToken = function() {
  21536. var curContext = this.curContext();
  21537. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  21538. this.start = this.pos;
  21539. if (this.options.locations) { this.startLoc = this.curPosition(); }
  21540. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  21541. if (curContext.override) { return curContext.override(this) }
  21542. else { this.readToken(this.fullCharCodeAtPos()); }
  21543. };
  21544. pp.readToken = function(code) {
  21545. // Identifier or keyword. '\uXXXX' sequences are allowed in
  21546. // identifiers, so '\' also dispatches to that.
  21547. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  21548. { return this.readWord() }
  21549. return this.getTokenFromCode(code)
  21550. };
  21551. pp.fullCharCodeAtPos = function() {
  21552. var code = this.input.charCodeAt(this.pos);
  21553. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  21554. var next = this.input.charCodeAt(this.pos + 1);
  21555. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  21556. };
  21557. pp.skipBlockComment = function() {
  21558. var startLoc = this.options.onComment && this.curPosition();
  21559. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  21560. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  21561. this.pos = end + 2;
  21562. if (this.options.locations) {
  21563. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  21564. ++this.curLine;
  21565. pos = this.lineStart = nextBreak;
  21566. }
  21567. }
  21568. if (this.options.onComment)
  21569. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  21570. startLoc, this.curPosition()); }
  21571. };
  21572. pp.skipLineComment = function(startSkip) {
  21573. var start = this.pos;
  21574. var startLoc = this.options.onComment && this.curPosition();
  21575. var ch = this.input.charCodeAt(this.pos += startSkip);
  21576. while (this.pos < this.input.length && !isNewLine(ch)) {
  21577. ch = this.input.charCodeAt(++this.pos);
  21578. }
  21579. if (this.options.onComment)
  21580. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  21581. startLoc, this.curPosition()); }
  21582. };
  21583. // Called at the start of the parse and after every token. Skips
  21584. // whitespace and comments, and.
  21585. pp.skipSpace = function() {
  21586. loop: while (this.pos < this.input.length) {
  21587. var ch = this.input.charCodeAt(this.pos);
  21588. switch (ch) {
  21589. case 32: case 160: // ' '
  21590. ++this.pos;
  21591. break
  21592. case 13:
  21593. if (this.input.charCodeAt(this.pos + 1) === 10) {
  21594. ++this.pos;
  21595. }
  21596. case 10: case 8232: case 8233:
  21597. ++this.pos;
  21598. if (this.options.locations) {
  21599. ++this.curLine;
  21600. this.lineStart = this.pos;
  21601. }
  21602. break
  21603. case 47: // '/'
  21604. switch (this.input.charCodeAt(this.pos + 1)) {
  21605. case 42: // '*'
  21606. this.skipBlockComment();
  21607. break
  21608. case 47:
  21609. this.skipLineComment(2);
  21610. break
  21611. default:
  21612. break loop
  21613. }
  21614. break
  21615. default:
  21616. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  21617. ++this.pos;
  21618. } else {
  21619. break loop
  21620. }
  21621. }
  21622. }
  21623. };
  21624. // Called at the end of every token. Sets `end`, `val`, and
  21625. // maintains `context` and `exprAllowed`, and skips the space after
  21626. // the token, so that the next one's `start` will point at the
  21627. // right position.
  21628. pp.finishToken = function(type, val) {
  21629. this.end = this.pos;
  21630. if (this.options.locations) { this.endLoc = this.curPosition(); }
  21631. var prevType = this.type;
  21632. this.type = type;
  21633. this.value = val;
  21634. this.updateContext(prevType);
  21635. };
  21636. // ### Token reading
  21637. // This is the function that is called to fetch the next token. It
  21638. // is somewhat obscure, because it works in character codes rather
  21639. // than characters, and because operator parsing has been inlined
  21640. // into it.
  21641. //
  21642. // All in the name of speed.
  21643. //
  21644. pp.readToken_dot = function() {
  21645. var next = this.input.charCodeAt(this.pos + 1);
  21646. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  21647. var next2 = this.input.charCodeAt(this.pos + 2);
  21648. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  21649. this.pos += 3;
  21650. return this.finishToken(types$1.ellipsis)
  21651. } else {
  21652. ++this.pos;
  21653. return this.finishToken(types$1.dot)
  21654. }
  21655. };
  21656. pp.readToken_slash = function() { // '/'
  21657. var next = this.input.charCodeAt(this.pos + 1);
  21658. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  21659. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21660. return this.finishOp(types$1.slash, 1)
  21661. };
  21662. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  21663. var next = this.input.charCodeAt(this.pos + 1);
  21664. var size = 1;
  21665. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  21666. // exponentiation operator ** and **=
  21667. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  21668. ++size;
  21669. tokentype = types$1.starstar;
  21670. next = this.input.charCodeAt(this.pos + 2);
  21671. }
  21672. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  21673. return this.finishOp(tokentype, size)
  21674. };
  21675. pp.readToken_pipe_amp = function(code) { // '|&'
  21676. var next = this.input.charCodeAt(this.pos + 1);
  21677. if (next === code) {
  21678. if (this.options.ecmaVersion >= 12) {
  21679. var next2 = this.input.charCodeAt(this.pos + 2);
  21680. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  21681. }
  21682. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  21683. }
  21684. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21685. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  21686. };
  21687. pp.readToken_caret = function() { // '^'
  21688. var next = this.input.charCodeAt(this.pos + 1);
  21689. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21690. return this.finishOp(types$1.bitwiseXOR, 1)
  21691. };
  21692. pp.readToken_plus_min = function(code) { // '+-'
  21693. var next = this.input.charCodeAt(this.pos + 1);
  21694. if (next === code) {
  21695. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  21696. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  21697. // A `-->` line comment
  21698. this.skipLineComment(3);
  21699. this.skipSpace();
  21700. return this.nextToken()
  21701. }
  21702. return this.finishOp(types$1.incDec, 2)
  21703. }
  21704. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21705. return this.finishOp(types$1.plusMin, 1)
  21706. };
  21707. pp.readToken_lt_gt = function(code) { // '<>'
  21708. var next = this.input.charCodeAt(this.pos + 1);
  21709. var size = 1;
  21710. if (next === code) {
  21711. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  21712. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  21713. return this.finishOp(types$1.bitShift, size)
  21714. }
  21715. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  21716. this.input.charCodeAt(this.pos + 3) === 45) {
  21717. // `<!--`, an XML-style comment that should be interpreted as a line comment
  21718. this.skipLineComment(4);
  21719. this.skipSpace();
  21720. return this.nextToken()
  21721. }
  21722. if (next === 61) { size = 2; }
  21723. return this.finishOp(types$1.relational, size)
  21724. };
  21725. pp.readToken_eq_excl = function(code) { // '=!'
  21726. var next = this.input.charCodeAt(this.pos + 1);
  21727. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  21728. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  21729. this.pos += 2;
  21730. return this.finishToken(types$1.arrow)
  21731. }
  21732. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  21733. };
  21734. pp.readToken_question = function() { // '?'
  21735. var ecmaVersion = this.options.ecmaVersion;
  21736. if (ecmaVersion >= 11) {
  21737. var next = this.input.charCodeAt(this.pos + 1);
  21738. if (next === 46) {
  21739. var next2 = this.input.charCodeAt(this.pos + 2);
  21740. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  21741. }
  21742. if (next === 63) {
  21743. if (ecmaVersion >= 12) {
  21744. var next2$1 = this.input.charCodeAt(this.pos + 2);
  21745. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  21746. }
  21747. return this.finishOp(types$1.coalesce, 2)
  21748. }
  21749. }
  21750. return this.finishOp(types$1.question, 1)
  21751. };
  21752. pp.readToken_numberSign = function() { // '#'
  21753. var ecmaVersion = this.options.ecmaVersion;
  21754. var code = 35; // '#'
  21755. if (ecmaVersion >= 13) {
  21756. ++this.pos;
  21757. code = this.fullCharCodeAtPos();
  21758. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  21759. return this.finishToken(types$1.privateId, this.readWord1())
  21760. }
  21761. }
  21762. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  21763. };
  21764. pp.getTokenFromCode = function(code) {
  21765. switch (code) {
  21766. // The interpretation of a dot depends on whether it is followed
  21767. // by a digit or another two dots.
  21768. case 46: // '.'
  21769. return this.readToken_dot()
  21770. // Punctuation tokens.
  21771. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  21772. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  21773. case 59: ++this.pos; return this.finishToken(types$1.semi)
  21774. case 44: ++this.pos; return this.finishToken(types$1.comma)
  21775. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  21776. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  21777. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  21778. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  21779. case 58: ++this.pos; return this.finishToken(types$1.colon)
  21780. case 96: // '`'
  21781. if (this.options.ecmaVersion < 6) { break }
  21782. ++this.pos;
  21783. return this.finishToken(types$1.backQuote)
  21784. case 48: // '0'
  21785. var next = this.input.charCodeAt(this.pos + 1);
  21786. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  21787. if (this.options.ecmaVersion >= 6) {
  21788. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  21789. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  21790. }
  21791. // Anything else beginning with a digit is an integer, octal
  21792. // number, or float.
  21793. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  21794. return this.readNumber(false)
  21795. // Quotes produce strings.
  21796. case 34: case 39: // '"', "'"
  21797. return this.readString(code)
  21798. // Operators are parsed inline in tiny state machines. '=' (61) is
  21799. // often referred to. `finishOp` simply skips the amount of
  21800. // characters it is given as second argument, and returns a token
  21801. // of the type given by its first argument.
  21802. case 47: // '/'
  21803. return this.readToken_slash()
  21804. case 37: case 42: // '%*'
  21805. return this.readToken_mult_modulo_exp(code)
  21806. case 124: case 38: // '|&'
  21807. return this.readToken_pipe_amp(code)
  21808. case 94: // '^'
  21809. return this.readToken_caret()
  21810. case 43: case 45: // '+-'
  21811. return this.readToken_plus_min(code)
  21812. case 60: case 62: // '<>'
  21813. return this.readToken_lt_gt(code)
  21814. case 61: case 33: // '=!'
  21815. return this.readToken_eq_excl(code)
  21816. case 63: // '?'
  21817. return this.readToken_question()
  21818. case 126: // '~'
  21819. return this.finishOp(types$1.prefix, 1)
  21820. case 35: // '#'
  21821. return this.readToken_numberSign()
  21822. }
  21823. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  21824. };
  21825. pp.finishOp = function(type, size) {
  21826. var str = this.input.slice(this.pos, this.pos + size);
  21827. this.pos += size;
  21828. return this.finishToken(type, str)
  21829. };
  21830. pp.readRegexp = function() {
  21831. var escaped, inClass, start = this.pos;
  21832. for (;;) {
  21833. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  21834. var ch = this.input.charAt(this.pos);
  21835. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  21836. if (!escaped) {
  21837. if (ch === "[") { inClass = true; }
  21838. else if (ch === "]" && inClass) { inClass = false; }
  21839. else if (ch === "/" && !inClass) { break }
  21840. escaped = ch === "\\";
  21841. } else { escaped = false; }
  21842. ++this.pos;
  21843. }
  21844. var pattern = this.input.slice(start, this.pos);
  21845. ++this.pos;
  21846. var flagsStart = this.pos;
  21847. var flags = this.readWord1();
  21848. if (this.containsEsc) { this.unexpected(flagsStart); }
  21849. // Validate pattern
  21850. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  21851. state.reset(start, pattern, flags);
  21852. this.validateRegExpFlags(state);
  21853. this.validateRegExpPattern(state);
  21854. // Create Literal#value property value.
  21855. var value = null;
  21856. try {
  21857. value = new RegExp(pattern, flags);
  21858. } catch (e) {
  21859. // ESTree requires null if it failed to instantiate RegExp object.
  21860. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  21861. }
  21862. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  21863. };
  21864. // Read an integer in the given radix. Return null if zero digits
  21865. // were read, the integer value otherwise. When `len` is given, this
  21866. // will return `null` unless the integer has exactly `len` digits.
  21867. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  21868. // `len` is used for character escape sequences. In that case, disallow separators.
  21869. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  21870. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  21871. // and isn't fraction part nor exponent part. In that case, if the first digit
  21872. // is zero then disallow separators.
  21873. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  21874. var start = this.pos, total = 0, lastCode = 0;
  21875. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  21876. var code = this.input.charCodeAt(this.pos), val = (void 0);
  21877. if (allowSeparators && code === 95) {
  21878. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  21879. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  21880. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  21881. lastCode = code;
  21882. continue
  21883. }
  21884. if (code >= 97) { val = code - 97 + 10; } // a
  21885. else if (code >= 65) { val = code - 65 + 10; } // A
  21886. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  21887. else { val = Infinity; }
  21888. if (val >= radix) { break }
  21889. lastCode = code;
  21890. total = total * radix + val;
  21891. }
  21892. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  21893. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  21894. return total
  21895. };
  21896. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  21897. if (isLegacyOctalNumericLiteral) {
  21898. return parseInt(str, 8)
  21899. }
  21900. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  21901. return parseFloat(str.replace(/_/g, ""))
  21902. }
  21903. function stringToBigInt(str) {
  21904. if (typeof BigInt !== "function") {
  21905. return null
  21906. }
  21907. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  21908. return BigInt(str.replace(/_/g, ""))
  21909. }
  21910. pp.readRadixNumber = function(radix) {
  21911. var start = this.pos;
  21912. this.pos += 2; // 0x
  21913. var val = this.readInt(radix);
  21914. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  21915. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  21916. val = stringToBigInt(this.input.slice(start, this.pos));
  21917. ++this.pos;
  21918. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  21919. return this.finishToken(types$1.num, val)
  21920. };
  21921. // Read an integer, octal integer, or floating-point number.
  21922. pp.readNumber = function(startsWithDot) {
  21923. var start = this.pos;
  21924. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  21925. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  21926. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  21927. var next = this.input.charCodeAt(this.pos);
  21928. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  21929. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  21930. ++this.pos;
  21931. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  21932. return this.finishToken(types$1.num, val$1)
  21933. }
  21934. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  21935. if (next === 46 && !octal) { // '.'
  21936. ++this.pos;
  21937. this.readInt(10);
  21938. next = this.input.charCodeAt(this.pos);
  21939. }
  21940. if ((next === 69 || next === 101) && !octal) { // 'eE'
  21941. next = this.input.charCodeAt(++this.pos);
  21942. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  21943. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  21944. }
  21945. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  21946. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  21947. return this.finishToken(types$1.num, val)
  21948. };
  21949. // Read a string value, interpreting backslash-escapes.
  21950. pp.readCodePoint = function() {
  21951. var ch = this.input.charCodeAt(this.pos), code;
  21952. if (ch === 123) { // '{'
  21953. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  21954. var codePos = ++this.pos;
  21955. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  21956. ++this.pos;
  21957. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  21958. } else {
  21959. code = this.readHexChar(4);
  21960. }
  21961. return code
  21962. };
  21963. pp.readString = function(quote) {
  21964. var out = "", chunkStart = ++this.pos;
  21965. for (;;) {
  21966. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  21967. var ch = this.input.charCodeAt(this.pos);
  21968. if (ch === quote) { break }
  21969. if (ch === 92) { // '\'
  21970. out += this.input.slice(chunkStart, this.pos);
  21971. out += this.readEscapedChar(false);
  21972. chunkStart = this.pos;
  21973. } else if (ch === 0x2028 || ch === 0x2029) {
  21974. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  21975. ++this.pos;
  21976. if (this.options.locations) {
  21977. this.curLine++;
  21978. this.lineStart = this.pos;
  21979. }
  21980. } else {
  21981. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  21982. ++this.pos;
  21983. }
  21984. }
  21985. out += this.input.slice(chunkStart, this.pos++);
  21986. return this.finishToken(types$1.string, out)
  21987. };
  21988. // Reads template string tokens.
  21989. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  21990. pp.tryReadTemplateToken = function() {
  21991. this.inTemplateElement = true;
  21992. try {
  21993. this.readTmplToken();
  21994. } catch (err) {
  21995. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  21996. this.readInvalidTemplateToken();
  21997. } else {
  21998. throw err
  21999. }
  22000. }
  22001. this.inTemplateElement = false;
  22002. };
  22003. pp.invalidStringToken = function(position, message) {
  22004. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  22005. throw INVALID_TEMPLATE_ESCAPE_ERROR
  22006. } else {
  22007. this.raise(position, message);
  22008. }
  22009. };
  22010. pp.readTmplToken = function() {
  22011. var out = "", chunkStart = this.pos;
  22012. for (;;) {
  22013. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  22014. var ch = this.input.charCodeAt(this.pos);
  22015. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  22016. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  22017. if (ch === 36) {
  22018. this.pos += 2;
  22019. return this.finishToken(types$1.dollarBraceL)
  22020. } else {
  22021. ++this.pos;
  22022. return this.finishToken(types$1.backQuote)
  22023. }
  22024. }
  22025. out += this.input.slice(chunkStart, this.pos);
  22026. return this.finishToken(types$1.template, out)
  22027. }
  22028. if (ch === 92) { // '\'
  22029. out += this.input.slice(chunkStart, this.pos);
  22030. out += this.readEscapedChar(true);
  22031. chunkStart = this.pos;
  22032. } else if (isNewLine(ch)) {
  22033. out += this.input.slice(chunkStart, this.pos);
  22034. ++this.pos;
  22035. switch (ch) {
  22036. case 13:
  22037. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  22038. case 10:
  22039. out += "\n";
  22040. break
  22041. default:
  22042. out += String.fromCharCode(ch);
  22043. break
  22044. }
  22045. if (this.options.locations) {
  22046. ++this.curLine;
  22047. this.lineStart = this.pos;
  22048. }
  22049. chunkStart = this.pos;
  22050. } else {
  22051. ++this.pos;
  22052. }
  22053. }
  22054. };
  22055. // Reads a template token to search for the end, without validating any escape sequences
  22056. pp.readInvalidTemplateToken = function() {
  22057. for (; this.pos < this.input.length; this.pos++) {
  22058. switch (this.input[this.pos]) {
  22059. case "\\":
  22060. ++this.pos;
  22061. break
  22062. case "$":
  22063. if (this.input[this.pos + 1] !== "{") {
  22064. break
  22065. }
  22066. // falls through
  22067. case "`":
  22068. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  22069. // no default
  22070. }
  22071. }
  22072. this.raise(this.start, "Unterminated template");
  22073. };
  22074. // Used to read escaped characters
  22075. pp.readEscapedChar = function(inTemplate) {
  22076. var ch = this.input.charCodeAt(++this.pos);
  22077. ++this.pos;
  22078. switch (ch) {
  22079. case 110: return "\n" // 'n' -> '\n'
  22080. case 114: return "\r" // 'r' -> '\r'
  22081. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  22082. case 117: return codePointToString(this.readCodePoint()) // 'u'
  22083. case 116: return "\t" // 't' -> '\t'
  22084. case 98: return "\b" // 'b' -> '\b'
  22085. case 118: return "\u000b" // 'v' -> '\u000b'
  22086. case 102: return "\f" // 'f' -> '\f'
  22087. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  22088. case 10: // ' \n'
  22089. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  22090. return ""
  22091. case 56:
  22092. case 57:
  22093. if (this.strict) {
  22094. this.invalidStringToken(
  22095. this.pos - 1,
  22096. "Invalid escape sequence"
  22097. );
  22098. }
  22099. if (inTemplate) {
  22100. var codePos = this.pos - 1;
  22101. this.invalidStringToken(
  22102. codePos,
  22103. "Invalid escape sequence in template string"
  22104. );
  22105. }
  22106. default:
  22107. if (ch >= 48 && ch <= 55) {
  22108. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  22109. var octal = parseInt(octalStr, 8);
  22110. if (octal > 255) {
  22111. octalStr = octalStr.slice(0, -1);
  22112. octal = parseInt(octalStr, 8);
  22113. }
  22114. this.pos += octalStr.length - 1;
  22115. ch = this.input.charCodeAt(this.pos);
  22116. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  22117. this.invalidStringToken(
  22118. this.pos - 1 - octalStr.length,
  22119. inTemplate
  22120. ? "Octal literal in template string"
  22121. : "Octal literal in strict mode"
  22122. );
  22123. }
  22124. return String.fromCharCode(octal)
  22125. }
  22126. if (isNewLine(ch)) {
  22127. // Unicode new line characters after \ get removed from output in both
  22128. // template literals and strings
  22129. return ""
  22130. }
  22131. return String.fromCharCode(ch)
  22132. }
  22133. };
  22134. // Used to read character escape sequences ('\x', '\u', '\U').
  22135. pp.readHexChar = function(len) {
  22136. var codePos = this.pos;
  22137. var n = this.readInt(16, len);
  22138. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  22139. return n
  22140. };
  22141. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  22142. // to whether the word contained a '\u' escape.
  22143. //
  22144. // Incrementally adds only escaped chars, adding other chunks as-is
  22145. // as a micro-optimization.
  22146. pp.readWord1 = function() {
  22147. this.containsEsc = false;
  22148. var word = "", first = true, chunkStart = this.pos;
  22149. var astral = this.options.ecmaVersion >= 6;
  22150. while (this.pos < this.input.length) {
  22151. var ch = this.fullCharCodeAtPos();
  22152. if (isIdentifierChar(ch, astral)) {
  22153. this.pos += ch <= 0xffff ? 1 : 2;
  22154. } else if (ch === 92) { // "\"
  22155. this.containsEsc = true;
  22156. word += this.input.slice(chunkStart, this.pos);
  22157. var escStart = this.pos;
  22158. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  22159. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  22160. ++this.pos;
  22161. var esc = this.readCodePoint();
  22162. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  22163. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  22164. word += codePointToString(esc);
  22165. chunkStart = this.pos;
  22166. } else {
  22167. break
  22168. }
  22169. first = false;
  22170. }
  22171. return word + this.input.slice(chunkStart, this.pos)
  22172. };
  22173. // Read an identifier or keyword token. Will check for reserved
  22174. // words when necessary.
  22175. pp.readWord = function() {
  22176. var word = this.readWord1();
  22177. var type = types$1.name;
  22178. if (this.keywords.test(word)) {
  22179. type = keywords[word];
  22180. }
  22181. return this.finishToken(type, word)
  22182. };
  22183. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  22184. var version = "8.8.2";
  22185. Parser.acorn = {
  22186. Parser: Parser,
  22187. version: version,
  22188. defaultOptions: defaultOptions,
  22189. Position: Position,
  22190. SourceLocation: SourceLocation,
  22191. getLineInfo: getLineInfo,
  22192. Node: Node,
  22193. TokenType: TokenType,
  22194. tokTypes: types$1,
  22195. keywordTypes: keywords,
  22196. TokContext: TokContext,
  22197. tokContexts: types,
  22198. isIdentifierChar: isIdentifierChar,
  22199. isIdentifierStart: isIdentifierStart,
  22200. Token: Token,
  22201. isNewLine: isNewLine,
  22202. lineBreak: lineBreak,
  22203. lineBreakG: lineBreakG,
  22204. nonASCIIwhitespace: nonASCIIwhitespace
  22205. };
  22206. // The main exported interface (under `self.acorn` when in the
  22207. // browser) is a `parse` function that takes a code string and
  22208. // returns an abstract syntax tree as specified by [Mozilla parser
  22209. // API][api].
  22210. //
  22211. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  22212. function parse(input, options) {
  22213. return Parser.parse(input, options)
  22214. }
  22215. // This function tries to parse a single expression at a given
  22216. // offset in a string. Useful for parsing mixed-language formats
  22217. // that embed JavaScript expressions.
  22218. function parseExpressionAt(input, pos, options) {
  22219. return Parser.parseExpressionAt(input, pos, options)
  22220. }
  22221. // Acorn is organized as a tokenizer and a recursive-descent parser.
  22222. // The `tokenizer` export provides an interface to the tokenizer.
  22223. function tokenizer(input, options) {
  22224. return Parser.tokenizer(input, options)
  22225. }
  22226. const _acorn = /*#__PURE__*/Object.defineProperty({
  22227. __proto__: null,
  22228. Node,
  22229. Parser,
  22230. Position,
  22231. SourceLocation,
  22232. TokContext,
  22233. Token,
  22234. TokenType,
  22235. defaultOptions,
  22236. getLineInfo,
  22237. isIdentifierChar,
  22238. isIdentifierStart,
  22239. isNewLine,
  22240. keywordTypes: keywords,
  22241. lineBreak,
  22242. lineBreakG,
  22243. nonASCIIwhitespace,
  22244. parse,
  22245. parseExpressionAt,
  22246. tokContexts: types,
  22247. tokTypes: types$1,
  22248. tokenizer,
  22249. version
  22250. }, Symbol.toStringTag, { value: 'Module' });
  22251. function flru (max) {
  22252. var num, curr, prev;
  22253. var limit = max || 1;
  22254. function keep(key, value) {
  22255. if (++num > limit) {
  22256. prev = curr;
  22257. reset(1);
  22258. ++num;
  22259. }
  22260. curr[key] = value;
  22261. }
  22262. function reset(isPartial) {
  22263. num = 0;
  22264. curr = Object.create(null);
  22265. isPartial || (prev=Object.create(null));
  22266. }
  22267. reset();
  22268. return {
  22269. clear: reset,
  22270. has: function (key) {
  22271. return curr[key] !== void 0 || prev[key] !== void 0;
  22272. },
  22273. get: function (key) {
  22274. var val = curr[key];
  22275. if (val !== void 0) return val;
  22276. if ((val=prev[key]) !== void 0) {
  22277. keep(key, val);
  22278. return val;
  22279. }
  22280. },
  22281. set: function (key, value) {
  22282. if (curr[key] !== void 0) {
  22283. curr[key] = value;
  22284. } else {
  22285. keep(key, value);
  22286. }
  22287. }
  22288. };
  22289. }
  22290. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions) {
  22291. let skipped = null;
  22292. let replaceContext = null;
  22293. if (skip) {
  22294. skipped = new Set();
  22295. for (const skippedCall of skip) {
  22296. if (source === skippedCall.source && importer === skippedCall.importer) {
  22297. skipped.add(skippedCall.plugin);
  22298. }
  22299. }
  22300. replaceContext = (pluginContext, plugin) => ({
  22301. ...pluginContext,
  22302. resolve: (source, importer, { assertions, custom, isEntry, skipSelf } = BLANK) => moduleLoaderResolveId(source, importer, custom, isEntry, assertions || EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip)
  22303. });
  22304. }
  22305. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { assertions, custom: customOptions, isEntry }], replaceContext, skipped);
  22306. }
  22307. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions) {
  22308. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions);
  22309. if (pluginResult != null) {
  22310. const [resolveIdResult, plugin] = pluginResult;
  22311. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  22312. return {
  22313. ...resolveIdResult,
  22314. resolvedBy: plugin.name
  22315. };
  22316. }
  22317. if (typeof resolveIdResult === 'string') {
  22318. return {
  22319. id: resolveIdResult,
  22320. resolvedBy: plugin.name
  22321. };
  22322. }
  22323. return resolveIdResult;
  22324. }
  22325. // external modules (non-entry modules that start with neither '.' or '/')
  22326. // are skipped at this stage.
  22327. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  22328. return null;
  22329. // `resolve` processes paths from right to left, prepending them until an
  22330. // absolute path is created. Absolute importees therefore shortcircuit the
  22331. // resolve call and require no special handing on our part.
  22332. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  22333. return addJsExtensionIfNecessary(importer ? node_path.resolve(node_path.dirname(importer), source) : node_path.resolve(source), preserveSymlinks);
  22334. }
  22335. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  22336. return ((await findFile(file, preserveSymlinks)) ??
  22337. (await findFile(file + '.mjs', preserveSymlinks)) ??
  22338. (await findFile(file + '.js', preserveSymlinks)));
  22339. }
  22340. async function findFile(file, preserveSymlinks) {
  22341. try {
  22342. const stats = await promises.lstat(file);
  22343. if (!preserveSymlinks && stats.isSymbolicLink())
  22344. return await findFile(await promises.realpath(file), preserveSymlinks);
  22345. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  22346. // check case
  22347. const name = node_path.basename(file);
  22348. const files = await promises.readdir(node_path.dirname(file));
  22349. if (files.includes(name))
  22350. return file;
  22351. }
  22352. }
  22353. catch {
  22354. // suppress
  22355. }
  22356. }
  22357. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  22358. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  22359. function createPluginCache(cache) {
  22360. return {
  22361. delete(id) {
  22362. return delete cache[id];
  22363. },
  22364. get(id) {
  22365. const item = cache[id];
  22366. if (!item)
  22367. return;
  22368. item[0] = 0;
  22369. return item[1];
  22370. },
  22371. has(id) {
  22372. const item = cache[id];
  22373. if (!item)
  22374. return false;
  22375. item[0] = 0;
  22376. return true;
  22377. },
  22378. set(id, value) {
  22379. cache[id] = [0, value];
  22380. }
  22381. };
  22382. }
  22383. function getTrackedPluginCache(pluginCache, onUse) {
  22384. return {
  22385. delete(id) {
  22386. onUse();
  22387. return pluginCache.delete(id);
  22388. },
  22389. get(id) {
  22390. onUse();
  22391. return pluginCache.get(id);
  22392. },
  22393. has(id) {
  22394. onUse();
  22395. return pluginCache.has(id);
  22396. },
  22397. set(id, value) {
  22398. onUse();
  22399. return pluginCache.set(id, value);
  22400. }
  22401. };
  22402. }
  22403. const NO_CACHE = {
  22404. delete() {
  22405. return false;
  22406. },
  22407. get() {
  22408. return undefined;
  22409. },
  22410. has() {
  22411. return false;
  22412. },
  22413. set() { }
  22414. };
  22415. function uncacheablePluginError(pluginName) {
  22416. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  22417. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  22418. return error(errorAnonymousPluginCache());
  22419. }
  22420. return error(errorDuplicatePluginName(pluginName));
  22421. }
  22422. function getCacheForUncacheablePlugin(pluginName) {
  22423. return {
  22424. delete() {
  22425. return uncacheablePluginError(pluginName);
  22426. },
  22427. get() {
  22428. return uncacheablePluginError(pluginName);
  22429. },
  22430. has() {
  22431. return uncacheablePluginError(pluginName);
  22432. },
  22433. set() {
  22434. return uncacheablePluginError(pluginName);
  22435. }
  22436. };
  22437. }
  22438. async function transform(source, module, pluginDriver, warn) {
  22439. const id = module.id;
  22440. const sourcemapChain = [];
  22441. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  22442. const originalCode = source.code;
  22443. let ast = source.ast;
  22444. const transformDependencies = [];
  22445. const emittedFiles = [];
  22446. let customTransformCache = false;
  22447. const useCustomTransformCache = () => (customTransformCache = true);
  22448. let pluginName = '';
  22449. const currentSource = source.code;
  22450. function transformReducer(previousCode, result, plugin) {
  22451. let code;
  22452. let map;
  22453. if (typeof result === 'string') {
  22454. code = result;
  22455. }
  22456. else if (result && typeof result === 'object') {
  22457. module.updateOptions(result);
  22458. if (result.code == null) {
  22459. if (result.map || result.ast) {
  22460. warn(errorNoTransformMapOrAstWithoutCode(plugin.name));
  22461. }
  22462. return previousCode;
  22463. }
  22464. ({ code, map, ast } = result);
  22465. }
  22466. else {
  22467. return previousCode;
  22468. }
  22469. // strict null check allows 'null' maps to not be pushed to the chain,
  22470. // while 'undefined' gets the missing map warning
  22471. if (map !== null) {
  22472. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  22473. missing: true,
  22474. plugin: plugin.name
  22475. });
  22476. }
  22477. return code;
  22478. }
  22479. let code;
  22480. try {
  22481. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  22482. pluginName = plugin.name;
  22483. return {
  22484. ...pluginContext,
  22485. addWatchFile(id) {
  22486. transformDependencies.push(id);
  22487. pluginContext.addWatchFile(id);
  22488. },
  22489. cache: customTransformCache
  22490. ? pluginContext.cache
  22491. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  22492. emitFile(emittedFile) {
  22493. emittedFiles.push(emittedFile);
  22494. return pluginDriver.emitFile(emittedFile);
  22495. },
  22496. error(error_, pos) {
  22497. if (typeof error_ === 'string')
  22498. error_ = { message: error_ };
  22499. if (pos)
  22500. augmentCodeLocation(error_, pos, currentSource, id);
  22501. error_.id = id;
  22502. error_.hook = 'transform';
  22503. return pluginContext.error(error_);
  22504. },
  22505. getCombinedSourcemap() {
  22506. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  22507. if (!combinedMap) {
  22508. const magicString = new MagicString(originalCode);
  22509. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  22510. }
  22511. if (originalSourcemap !== combinedMap) {
  22512. originalSourcemap = combinedMap;
  22513. sourcemapChain.length = 0;
  22514. }
  22515. return new SourceMap({
  22516. ...combinedMap,
  22517. file: null,
  22518. sourcesContent: combinedMap.sourcesContent
  22519. });
  22520. },
  22521. setAssetSource() {
  22522. return this.error(errorInvalidSetAssetSourceCall());
  22523. },
  22524. warn(warning, pos) {
  22525. if (typeof warning === 'string')
  22526. warning = { message: warning };
  22527. if (pos)
  22528. augmentCodeLocation(warning, pos, currentSource, id);
  22529. warning.id = id;
  22530. warning.hook = 'transform';
  22531. pluginContext.warn(warning);
  22532. }
  22533. };
  22534. });
  22535. }
  22536. catch (error_) {
  22537. return error(errorPluginError(error_, pluginName, { hook: 'transform', id }));
  22538. }
  22539. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  22540. emittedFiles.length > 0)
  22541. module.transformFiles = emittedFiles;
  22542. return {
  22543. ast,
  22544. code,
  22545. customTransformCache,
  22546. originalCode,
  22547. originalSourcemap,
  22548. sourcemapChain,
  22549. transformDependencies
  22550. };
  22551. }
  22552. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  22553. class ModuleLoader {
  22554. constructor(graph, modulesById, options, pluginDriver) {
  22555. this.graph = graph;
  22556. this.modulesById = modulesById;
  22557. this.options = options;
  22558. this.pluginDriver = pluginDriver;
  22559. this.implicitEntryModules = new Set();
  22560. this.indexedEntryModules = [];
  22561. this.latestLoadModulesPromise = Promise.resolve();
  22562. this.moduleLoadPromises = new Map();
  22563. this.modulesWithLoadedDependencies = new Set();
  22564. this.nextChunkNamePriority = 0;
  22565. this.nextEntryModuleIndex = 0;
  22566. this.resolveId = async (source, importer, customOptions, isEntry, assertions, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  22567. ? false
  22568. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, assertions), importer, source), assertions);
  22569. this.hasModuleSideEffects = options.treeshake
  22570. ? options.treeshake.moduleSideEffects
  22571. : () => true;
  22572. }
  22573. async addAdditionalModules(unresolvedModules) {
  22574. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  22575. await this.awaitLoadModulesPromise();
  22576. return result;
  22577. }
  22578. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  22579. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  22580. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  22581. const firstChunkNamePriority = this.nextChunkNamePriority;
  22582. this.nextChunkNamePriority += unresolvedEntryModules.length;
  22583. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  22584. for (const [index, entryModule] of entryModules.entries()) {
  22585. entryModule.isUserDefinedEntryPoint =
  22586. entryModule.isUserDefinedEntryPoint || isUserDefined;
  22587. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  22588. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  22589. if (existingIndexedModule) {
  22590. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  22591. }
  22592. else {
  22593. this.indexedEntryModules.push({
  22594. index: firstEntryModuleIndex + index,
  22595. module: entryModule
  22596. });
  22597. }
  22598. }
  22599. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  22600. return entryModules;
  22601. }));
  22602. await this.awaitLoadModulesPromise();
  22603. return {
  22604. entryModules: this.indexedEntryModules.map(({ module }) => module),
  22605. implicitEntryModules: [...this.implicitEntryModules],
  22606. newEntryModules
  22607. };
  22608. }
  22609. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  22610. const unresolvedModule = {
  22611. fileName: fileName || null,
  22612. id,
  22613. importer,
  22614. name: name || null
  22615. };
  22616. const module = implicitlyLoadedAfterOneOf
  22617. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  22618. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  22619. if (preserveSignature != null) {
  22620. module.preserveSignature = preserveSignature;
  22621. }
  22622. return module;
  22623. }
  22624. async preloadModule(resolvedId) {
  22625. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  22626. return module.info;
  22627. }
  22628. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  22629. const chunkNamePriority = this.nextChunkNamePriority++;
  22630. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  22631. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  22632. if (!entryModule.info.isEntry) {
  22633. this.implicitEntryModules.add(entryModule);
  22634. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  22635. for (const module of implicitlyLoadedAfterModules) {
  22636. entryModule.implicitlyLoadedAfter.add(module);
  22637. }
  22638. for (const dependant of entryModule.implicitlyLoadedAfter) {
  22639. dependant.implicitlyLoadedBefore.add(entryModule);
  22640. }
  22641. }
  22642. return entryModule;
  22643. }));
  22644. }
  22645. async addModuleSource(id, importer, module) {
  22646. let source;
  22647. try {
  22648. source = await this.graph.fileOperationQueue.run(async () => (await this.pluginDriver.hookFirst('load', [id])) ?? (await promises.readFile(id, 'utf8')));
  22649. }
  22650. catch (error_) {
  22651. let message = `Could not load ${id}`;
  22652. if (importer)
  22653. message += ` (imported by ${relativeId(importer)})`;
  22654. message += `: ${error_.message}`;
  22655. error_.message = message;
  22656. throw error_;
  22657. }
  22658. const sourceDescription = typeof source === 'string'
  22659. ? { code: source }
  22660. : source != null && typeof source === 'object' && typeof source.code === 'string'
  22661. ? source
  22662. : error(errorBadLoader(id));
  22663. const cachedModule = this.graph.cachedModules.get(id);
  22664. if (cachedModule &&
  22665. !cachedModule.customTransformCache &&
  22666. cachedModule.originalCode === sourceDescription.code &&
  22667. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  22668. {
  22669. ast: cachedModule.ast,
  22670. code: cachedModule.code,
  22671. id: cachedModule.id,
  22672. meta: cachedModule.meta,
  22673. moduleSideEffects: cachedModule.moduleSideEffects,
  22674. resolvedSources: cachedModule.resolvedIds,
  22675. syntheticNamedExports: cachedModule.syntheticNamedExports
  22676. }
  22677. ]))) {
  22678. if (cachedModule.transformFiles) {
  22679. for (const emittedFile of cachedModule.transformFiles)
  22680. this.pluginDriver.emitFile(emittedFile);
  22681. }
  22682. module.setSource(cachedModule);
  22683. }
  22684. else {
  22685. module.updateOptions(sourceDescription);
  22686. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  22687. }
  22688. }
  22689. async awaitLoadModulesPromise() {
  22690. let startingPromise;
  22691. do {
  22692. startingPromise = this.latestLoadModulesPromise;
  22693. await startingPromise;
  22694. } while (startingPromise !== this.latestLoadModulesPromise);
  22695. }
  22696. extendLoadModulesPromise(loadNewModulesPromise) {
  22697. this.latestLoadModulesPromise = Promise.all([
  22698. loadNewModulesPromise,
  22699. this.latestLoadModulesPromise
  22700. ]);
  22701. this.latestLoadModulesPromise.catch(() => {
  22702. /* Avoid unhandled Promise rejections */
  22703. });
  22704. return loadNewModulesPromise;
  22705. }
  22706. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  22707. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  22708. if (resolvedId === null)
  22709. return null;
  22710. if (typeof resolvedId === 'string') {
  22711. dynamicImport.resolution = resolvedId;
  22712. return null;
  22713. }
  22714. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  22715. })));
  22716. for (const dependency of dependencies) {
  22717. if (dependency) {
  22718. module.dynamicDependencies.add(dependency);
  22719. dependency.dynamicImporters.push(module.id);
  22720. }
  22721. }
  22722. }
  22723. // If this is a preload, then this method always waits for the dependencies of
  22724. // the module to be resolved.
  22725. // Otherwise, if the module does not exist, it waits for the module and all
  22726. // its dependencies to be loaded.
  22727. // Otherwise, it returns immediately.
  22728. async fetchModule({ assertions, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  22729. const existingModule = this.modulesById.get(id);
  22730. if (existingModule instanceof Module) {
  22731. if (importer && doAssertionsDiffer(assertions, existingModule.info.assertions)) {
  22732. this.options.onwarn(errorInconsistentImportAssertions(existingModule.info.assertions, assertions, id, importer));
  22733. }
  22734. await this.handleExistingModule(existingModule, isEntry, isPreload);
  22735. return existingModule;
  22736. }
  22737. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, assertions);
  22738. this.modulesById.set(id, module);
  22739. this.graph.watchFiles[id] = true;
  22740. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  22741. this.getResolveStaticDependencyPromises(module),
  22742. this.getResolveDynamicImportPromises(module),
  22743. loadAndResolveDependenciesPromise
  22744. ]);
  22745. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  22746. loadAndResolveDependenciesPromise.catch(() => {
  22747. /* avoid unhandled promise rejections */
  22748. });
  22749. this.moduleLoadPromises.set(module, loadPromise);
  22750. const resolveDependencyPromises = await loadPromise;
  22751. if (!isPreload) {
  22752. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  22753. }
  22754. else if (isPreload === RESOLVE_DEPENDENCIES) {
  22755. await loadAndResolveDependenciesPromise;
  22756. }
  22757. return module;
  22758. }
  22759. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  22760. if (this.modulesWithLoadedDependencies.has(module)) {
  22761. return;
  22762. }
  22763. this.modulesWithLoadedDependencies.add(module);
  22764. await Promise.all([
  22765. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  22766. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  22767. ]);
  22768. module.linkImports();
  22769. // To handle errors when resolving dependencies or in moduleParsed
  22770. await loadAndResolveDependenciesPromise;
  22771. }
  22772. fetchResolvedDependency(source, importer, resolvedId) {
  22773. if (resolvedId.external) {
  22774. const { assertions, external, id, moduleSideEffects, meta } = resolvedId;
  22775. let externalModule = this.modulesById.get(id);
  22776. if (!externalModule) {
  22777. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id), assertions);
  22778. this.modulesById.set(id, externalModule);
  22779. }
  22780. else if (!(externalModule instanceof ExternalModule)) {
  22781. return error(errorInternalIdCannotBeExternal(source, importer));
  22782. }
  22783. else if (doAssertionsDiffer(externalModule.info.assertions, assertions)) {
  22784. this.options.onwarn(errorInconsistentImportAssertions(externalModule.info.assertions, assertions, source, importer));
  22785. }
  22786. return Promise.resolve(externalModule);
  22787. }
  22788. return this.fetchModule(resolvedId, importer, false, false);
  22789. }
  22790. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  22791. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  22792. module.dependencies.add(dependency);
  22793. dependency.importers.push(module.id);
  22794. }
  22795. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  22796. for (const dependency of module.dependencies) {
  22797. if (dependency instanceof Module) {
  22798. dependency.importedFromNotTreeshaken = true;
  22799. }
  22800. }
  22801. }
  22802. }
  22803. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  22804. const { makeAbsoluteExternalsRelative } = this.options;
  22805. if (resolveIdResult) {
  22806. if (typeof resolveIdResult === 'object') {
  22807. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  22808. return {
  22809. ...resolveIdResult,
  22810. external: external &&
  22811. (external === 'relative' ||
  22812. !isAbsolute(resolveIdResult.id) ||
  22813. (external === true &&
  22814. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  22815. 'absolute')
  22816. };
  22817. }
  22818. const external = this.options.external(resolveIdResult, importer, true);
  22819. return {
  22820. external: external &&
  22821. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  22822. 'absolute'),
  22823. id: external && makeAbsoluteExternalsRelative
  22824. ? normalizeRelativeExternalId(resolveIdResult, importer)
  22825. : resolveIdResult
  22826. };
  22827. }
  22828. const id = makeAbsoluteExternalsRelative
  22829. ? normalizeRelativeExternalId(source, importer)
  22830. : source;
  22831. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  22832. return null;
  22833. }
  22834. return {
  22835. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  22836. id
  22837. };
  22838. }
  22839. getResolveDynamicImportPromises(module) {
  22840. return module.dynamicImports.map(async (dynamicImport) => {
  22841. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  22842. ? dynamicImport.argument
  22843. : dynamicImport.argument.esTreeNode, module.id, getAssertionsFromImportExpression(dynamicImport.node));
  22844. if (resolvedId && typeof resolvedId === 'object') {
  22845. dynamicImport.id = resolvedId.id;
  22846. }
  22847. return [dynamicImport, resolvedId];
  22848. });
  22849. }
  22850. getResolveStaticDependencyPromises(module) {
  22851. // eslint-disable-next-line unicorn/prefer-spread
  22852. return Array.from(module.sourcesWithAssertions, async ([source, assertions]) => [
  22853. source,
  22854. (module.resolvedIds[source] =
  22855. module.resolvedIds[source] ||
  22856. this.handleInvalidResolvedId(await this.resolveId(source, module.id, EMPTY_OBJECT, false, assertions), source, module.id, assertions))
  22857. ]);
  22858. }
  22859. getResolvedIdWithDefaults(resolvedId, assertions) {
  22860. if (!resolvedId) {
  22861. return null;
  22862. }
  22863. const external = resolvedId.external || false;
  22864. return {
  22865. assertions: resolvedId.assertions || assertions,
  22866. external,
  22867. id: resolvedId.id,
  22868. meta: resolvedId.meta || {},
  22869. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  22870. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  22871. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  22872. };
  22873. }
  22874. async handleExistingModule(module, isEntry, isPreload) {
  22875. const loadPromise = this.moduleLoadPromises.get(module);
  22876. if (isPreload) {
  22877. return isPreload === RESOLVE_DEPENDENCIES
  22878. ? waitForDependencyResolution(loadPromise)
  22879. : loadPromise;
  22880. }
  22881. if (isEntry) {
  22882. module.info.isEntry = true;
  22883. this.implicitEntryModules.delete(module);
  22884. for (const dependant of module.implicitlyLoadedAfter) {
  22885. dependant.implicitlyLoadedBefore.delete(module);
  22886. }
  22887. module.implicitlyLoadedAfter.clear();
  22888. }
  22889. return this.fetchModuleDependencies(module, ...(await loadPromise));
  22890. }
  22891. handleInvalidResolvedId(resolvedId, source, importer, assertions) {
  22892. if (resolvedId === null) {
  22893. if (isRelative(source)) {
  22894. return error(errorUnresolvedImport(source, importer));
  22895. }
  22896. this.options.onwarn(errorUnresolvedImportTreatedAsExternal(source, importer));
  22897. return {
  22898. assertions,
  22899. external: true,
  22900. id: source,
  22901. meta: {},
  22902. moduleSideEffects: this.hasModuleSideEffects(source, true),
  22903. resolvedBy: 'rollup',
  22904. syntheticNamedExports: false
  22905. };
  22906. }
  22907. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  22908. this.options.onwarn(errorExternalSyntheticExports(source, importer));
  22909. }
  22910. return resolvedId;
  22911. }
  22912. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  22913. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT);
  22914. if (resolveIdResult == null) {
  22915. return error(implicitlyLoadedBefore === null
  22916. ? errorUnresolvedEntry(unresolvedId)
  22917. : errorUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  22918. }
  22919. if (resolveIdResult === false ||
  22920. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  22921. return error(implicitlyLoadedBefore === null
  22922. ? errorEntryCannotBeExternal(unresolvedId)
  22923. : errorImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  22924. }
  22925. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  22926. ? resolveIdResult
  22927. : { id: resolveIdResult }, EMPTY_OBJECT), undefined, isEntry, false);
  22928. }
  22929. async resolveDynamicImport(module, specifier, importer, assertions) {
  22930. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  22931. specifier,
  22932. importer,
  22933. { assertions }
  22934. ]);
  22935. if (typeof specifier !== 'string') {
  22936. if (typeof resolution === 'string') {
  22937. return resolution;
  22938. }
  22939. if (!resolution) {
  22940. return null;
  22941. }
  22942. return this.getResolvedIdWithDefaults(resolution, assertions);
  22943. }
  22944. if (resolution == null) {
  22945. const existingResolution = module.resolvedIds[specifier];
  22946. if (existingResolution) {
  22947. if (doAssertionsDiffer(existingResolution.assertions, assertions)) {
  22948. this.options.onwarn(errorInconsistentImportAssertions(existingResolution.assertions, assertions, specifier, importer));
  22949. }
  22950. return existingResolution;
  22951. }
  22952. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false, assertions), specifier, module.id, assertions));
  22953. }
  22954. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), assertions), specifier, importer, assertions);
  22955. }
  22956. }
  22957. function normalizeRelativeExternalId(source, importer) {
  22958. return isRelative(source)
  22959. ? importer
  22960. ? node_path.resolve(importer, '..', source)
  22961. : node_path.resolve(source)
  22962. : source;
  22963. }
  22964. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  22965. if (fileName !== null) {
  22966. module.chunkFileNames.add(fileName);
  22967. }
  22968. else if (name !== null) {
  22969. // Always keep chunkNames sorted by priority
  22970. let namePosition = 0;
  22971. while (module.chunkNames[namePosition]?.priority < priority)
  22972. namePosition++;
  22973. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  22974. }
  22975. }
  22976. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  22977. return (makeAbsoluteExternalsRelative === true ||
  22978. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  22979. !isAbsolute(id));
  22980. }
  22981. async function waitForDependencyResolution(loadPromise) {
  22982. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  22983. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  22984. }
  22985. class GlobalScope extends Scope$1 {
  22986. constructor() {
  22987. super();
  22988. this.parent = null;
  22989. this.variables.set('undefined', new UndefinedVariable());
  22990. }
  22991. findVariable(name) {
  22992. let variable = this.variables.get(name);
  22993. if (!variable) {
  22994. variable = new GlobalVariable(name);
  22995. this.variables.set(name, variable);
  22996. }
  22997. return variable;
  22998. }
  22999. }
  23000. function getSourceHash(source) {
  23001. return createHash().update(source).digest('hex');
  23002. }
  23003. function generateAssetFileName(name, source, sourceHash, outputOptions, bundle) {
  23004. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  23005. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  23006. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  23007. : outputOptions.assetFileNames, 'output.assetFileNames', {
  23008. ext: () => node_path.extname(emittedName).slice(1),
  23009. extname: () => node_path.extname(emittedName),
  23010. hash: size => sourceHash.slice(0, Math.max(0, size || defaultHashSize)),
  23011. name: () => emittedName.slice(0, Math.max(0, emittedName.length - node_path.extname(emittedName).length))
  23012. }), bundle);
  23013. }
  23014. function reserveFileNameInBundle(fileName, { bundle }, warn) {
  23015. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  23016. warn(errorFileNameConflict(fileName));
  23017. }
  23018. else {
  23019. bundle[fileName] = FILE_PLACEHOLDER;
  23020. }
  23021. }
  23022. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  23023. function hasValidType(emittedFile) {
  23024. return Boolean(emittedFile &&
  23025. emittedFileTypes.has(emittedFile.type));
  23026. }
  23027. function hasValidName(emittedFile) {
  23028. const validatedName = emittedFile.fileName || emittedFile.name;
  23029. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  23030. }
  23031. function getValidSource(source, emittedFile, fileReferenceId) {
  23032. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  23033. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  23034. 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.`));
  23035. }
  23036. return source;
  23037. }
  23038. function getAssetFileName(file, referenceId) {
  23039. if (typeof file.fileName !== 'string') {
  23040. return error(errorAssetNotFinalisedForFileName(file.name || referenceId));
  23041. }
  23042. return file.fileName;
  23043. }
  23044. function getChunkFileName(file, facadeChunkByModule) {
  23045. if (file.fileName) {
  23046. return file.fileName;
  23047. }
  23048. if (facadeChunkByModule) {
  23049. return facadeChunkByModule.get(file.module).getFileName();
  23050. }
  23051. return error(errorChunkNotGeneratedForFileName(file.fileName || file.name));
  23052. }
  23053. class FileEmitter {
  23054. constructor(graph, options, baseFileEmitter) {
  23055. this.graph = graph;
  23056. this.options = options;
  23057. this.facadeChunkByModule = null;
  23058. this.nextIdBase = 1;
  23059. this.output = null;
  23060. this.outputFileEmitters = [];
  23061. this.emitFile = (emittedFile) => {
  23062. if (!hasValidType(emittedFile)) {
  23063. return error(errorFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  23064. }
  23065. if (emittedFile.type === 'prebuilt-chunk') {
  23066. return this.emitPrebuiltChunk(emittedFile);
  23067. }
  23068. if (!hasValidName(emittedFile)) {
  23069. return error(errorFailedValidation(`The "fileName" or "name" properties of emitted chunks and assets must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
  23070. }
  23071. if (emittedFile.type === 'chunk') {
  23072. return this.emitChunk(emittedFile);
  23073. }
  23074. return this.emitAsset(emittedFile);
  23075. };
  23076. this.finaliseAssets = () => {
  23077. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  23078. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  23079. return error(errorNoAssetSourceSet(emittedFile.name || referenceId));
  23080. }
  23081. };
  23082. this.getFileName = (fileReferenceId) => {
  23083. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  23084. if (!emittedFile)
  23085. return error(errorFileReferenceIdNotFoundForFilename(fileReferenceId));
  23086. if (emittedFile.type === 'chunk') {
  23087. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  23088. }
  23089. if (emittedFile.type === 'prebuilt-chunk') {
  23090. return emittedFile.fileName;
  23091. }
  23092. return getAssetFileName(emittedFile, fileReferenceId);
  23093. };
  23094. this.setAssetSource = (referenceId, requestedSource) => {
  23095. const consumedFile = this.filesByReferenceId.get(referenceId);
  23096. if (!consumedFile)
  23097. return error(errorAssetReferenceIdNotFoundForSetSource(referenceId));
  23098. if (consumedFile.type !== 'asset') {
  23099. return error(errorFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  23100. }
  23101. if (consumedFile.source !== undefined) {
  23102. return error(errorAssetSourceAlreadySet(consumedFile.name || referenceId));
  23103. }
  23104. const source = getValidSource(requestedSource, consumedFile, referenceId);
  23105. if (this.output) {
  23106. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  23107. }
  23108. else {
  23109. consumedFile.source = source;
  23110. for (const emitter of this.outputFileEmitters) {
  23111. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  23112. }
  23113. }
  23114. };
  23115. this.setChunkInformation = (facadeChunkByModule) => {
  23116. this.facadeChunkByModule = facadeChunkByModule;
  23117. };
  23118. this.setOutputBundle = (bundle, outputOptions) => {
  23119. const output = (this.output = {
  23120. bundle,
  23121. fileNamesBySource: new Map(),
  23122. outputOptions
  23123. });
  23124. for (const emittedFile of this.filesByReferenceId.values()) {
  23125. if (emittedFile.fileName) {
  23126. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onwarn);
  23127. }
  23128. }
  23129. const consumedAssetsByHash = new Map();
  23130. for (const consumedFile of this.filesByReferenceId.values()) {
  23131. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  23132. if (consumedFile.fileName) {
  23133. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  23134. }
  23135. else {
  23136. const sourceHash = getSourceHash(consumedFile.source);
  23137. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  23138. }
  23139. }
  23140. else if (consumedFile.type === 'prebuilt-chunk') {
  23141. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  23142. }
  23143. }
  23144. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  23145. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  23146. }
  23147. };
  23148. this.filesByReferenceId = baseFileEmitter
  23149. ? new Map(baseFileEmitter.filesByReferenceId)
  23150. : new Map();
  23151. baseFileEmitter?.addOutputFileEmitter(this);
  23152. }
  23153. addOutputFileEmitter(outputFileEmitter) {
  23154. this.outputFileEmitters.push(outputFileEmitter);
  23155. }
  23156. assignReferenceId(file, idBase) {
  23157. let referenceId = idBase;
  23158. do {
  23159. referenceId = createHash().update(referenceId).digest('hex').slice(0, 8);
  23160. } while (this.filesByReferenceId.has(referenceId) ||
  23161. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  23162. file.referenceId = referenceId;
  23163. this.filesByReferenceId.set(referenceId, file);
  23164. for (const { filesByReferenceId } of this.outputFileEmitters) {
  23165. filesByReferenceId.set(referenceId, file);
  23166. }
  23167. return referenceId;
  23168. }
  23169. createPrebuiltChunk(prebuiltChunk) {
  23170. return {
  23171. code: prebuiltChunk.code,
  23172. dynamicImports: [],
  23173. exports: prebuiltChunk.exports || [],
  23174. facadeModuleId: null,
  23175. fileName: prebuiltChunk.fileName,
  23176. implicitlyLoadedBefore: [],
  23177. importedBindings: {},
  23178. imports: [],
  23179. isDynamicEntry: false,
  23180. isEntry: false,
  23181. isImplicitEntry: false,
  23182. map: prebuiltChunk.map || null,
  23183. moduleIds: [],
  23184. modules: {},
  23185. name: prebuiltChunk.fileName,
  23186. referencedFiles: [],
  23187. type: 'chunk'
  23188. };
  23189. }
  23190. emitAsset(emittedAsset) {
  23191. const source = emittedAsset.source === undefined
  23192. ? undefined
  23193. : getValidSource(emittedAsset.source, emittedAsset, null);
  23194. const consumedAsset = {
  23195. fileName: emittedAsset.fileName,
  23196. name: emittedAsset.name,
  23197. needsCodeReference: !!emittedAsset.needsCodeReference,
  23198. referenceId: '',
  23199. source,
  23200. type: 'asset'
  23201. };
  23202. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  23203. if (this.output) {
  23204. this.emitAssetWithReferenceId(consumedAsset, this.output);
  23205. }
  23206. else {
  23207. for (const fileEmitter of this.outputFileEmitters) {
  23208. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  23209. }
  23210. }
  23211. return referenceId;
  23212. }
  23213. emitAssetWithReferenceId(consumedAsset, output) {
  23214. const { fileName, source } = consumedAsset;
  23215. if (fileName) {
  23216. reserveFileNameInBundle(fileName, output, this.options.onwarn);
  23217. }
  23218. if (source !== undefined) {
  23219. this.finalizeAdditionalAsset(consumedAsset, source, output);
  23220. }
  23221. }
  23222. emitChunk(emittedChunk) {
  23223. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  23224. return error(errorInvalidRollupPhaseForChunkEmission());
  23225. }
  23226. if (typeof emittedChunk.id !== 'string') {
  23227. return error(errorFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  23228. }
  23229. const consumedChunk = {
  23230. fileName: emittedChunk.fileName,
  23231. module: null,
  23232. name: emittedChunk.name || emittedChunk.id,
  23233. referenceId: '',
  23234. type: 'chunk'
  23235. };
  23236. this.graph.moduleLoader
  23237. .emitChunk(emittedChunk)
  23238. .then(module => (consumedChunk.module = module))
  23239. .catch(() => {
  23240. // Avoid unhandled Promise rejection as the error will be thrown later
  23241. // once module loading has finished
  23242. });
  23243. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  23244. }
  23245. emitPrebuiltChunk(emitPrebuiltChunk) {
  23246. if (typeof emitPrebuiltChunk.code !== 'string') {
  23247. return error(errorFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  23248. }
  23249. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  23250. isPathFragment(emitPrebuiltChunk.fileName)) {
  23251. return error(errorFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  23252. }
  23253. const consumedPrebuiltChunk = {
  23254. code: emitPrebuiltChunk.code,
  23255. exports: emitPrebuiltChunk.exports,
  23256. fileName: emitPrebuiltChunk.fileName,
  23257. map: emitPrebuiltChunk.map,
  23258. referenceId: '',
  23259. type: 'prebuilt-chunk'
  23260. };
  23261. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  23262. if (this.output) {
  23263. this.output.bundle[consumedPrebuiltChunk.fileName] =
  23264. this.createPrebuiltChunk(consumedPrebuiltChunk);
  23265. }
  23266. return referenceId;
  23267. }
  23268. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySource, outputOptions }) {
  23269. let { fileName, needsCodeReference, referenceId } = consumedFile;
  23270. // Deduplicate assets if an explicit fileName is not provided
  23271. if (!fileName) {
  23272. const sourceHash = getSourceHash(source);
  23273. fileName = fileNamesBySource.get(sourceHash);
  23274. if (!fileName) {
  23275. fileName = generateAssetFileName(consumedFile.name, source, sourceHash, outputOptions, bundle);
  23276. fileNamesBySource.set(sourceHash, fileName);
  23277. }
  23278. }
  23279. // We must not modify the original assets to avoid interaction between outputs
  23280. const assetWithFileName = { ...consumedFile, fileName, source };
  23281. this.filesByReferenceId.set(referenceId, assetWithFileName);
  23282. const existingAsset = bundle[fileName];
  23283. if (existingAsset?.type === 'asset') {
  23284. existingAsset.needsCodeReference && (existingAsset.needsCodeReference = needsCodeReference);
  23285. }
  23286. else {
  23287. bundle[fileName] = {
  23288. fileName,
  23289. name: consumedFile.name,
  23290. needsCodeReference,
  23291. source,
  23292. type: 'asset'
  23293. };
  23294. }
  23295. }
  23296. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySource, outputOptions }) {
  23297. let fileName = '';
  23298. let usedConsumedFile;
  23299. let needsCodeReference = true;
  23300. for (const consumedFile of consumedFiles) {
  23301. needsCodeReference && (needsCodeReference = consumedFile.needsCodeReference);
  23302. const assetFileName = generateAssetFileName(consumedFile.name, consumedFile.source, sourceHash, outputOptions, bundle);
  23303. if (!fileName ||
  23304. assetFileName.length < fileName.length ||
  23305. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  23306. fileName = assetFileName;
  23307. usedConsumedFile = consumedFile;
  23308. }
  23309. }
  23310. fileNamesBySource.set(sourceHash, fileName);
  23311. for (const consumedFile of consumedFiles) {
  23312. // We must not modify the original assets to avoid interaction between outputs
  23313. const assetWithFileName = { ...consumedFile, fileName };
  23314. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  23315. }
  23316. bundle[fileName] = {
  23317. fileName,
  23318. name: usedConsumedFile.name,
  23319. needsCodeReference,
  23320. source: usedConsumedFile.source,
  23321. type: 'asset'
  23322. };
  23323. }
  23324. }
  23325. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  23326. let cacheable = true;
  23327. if (typeof plugin.cacheKey !== 'string') {
  23328. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  23329. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  23330. existingPluginNames.has(plugin.name)) {
  23331. cacheable = false;
  23332. }
  23333. else {
  23334. existingPluginNames.add(plugin.name);
  23335. }
  23336. }
  23337. let cacheInstance;
  23338. if (!pluginCache) {
  23339. cacheInstance = NO_CACHE;
  23340. }
  23341. else if (cacheable) {
  23342. const cacheKey = plugin.cacheKey || plugin.name;
  23343. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  23344. }
  23345. else {
  23346. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  23347. }
  23348. return {
  23349. addWatchFile(id) {
  23350. if (graph.phase >= BuildPhase.GENERATE) {
  23351. return this.error(errorInvalidRollupPhaseForAddWatchFile());
  23352. }
  23353. graph.watchFiles[id] = true;
  23354. },
  23355. cache: cacheInstance,
  23356. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  23357. error(error_) {
  23358. return error(errorPluginError(error_, plugin.name));
  23359. },
  23360. getFileName: fileEmitter.getFileName,
  23361. getModuleIds: () => graph.modulesById.keys(),
  23362. getModuleInfo: graph.getModuleInfo,
  23363. getWatchFiles: () => Object.keys(graph.watchFiles),
  23364. load(resolvedId) {
  23365. return graph.moduleLoader.preloadModule(resolvedId);
  23366. },
  23367. meta: {
  23368. rollupVersion: version$1,
  23369. watchMode: graph.watchMode
  23370. },
  23371. get moduleIds() {
  23372. function* wrappedModuleIds() {
  23373. // We are wrapping this in a generator to only show the message once we are actually iterating
  23374. 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);
  23375. yield* moduleIds;
  23376. }
  23377. const moduleIds = graph.modulesById.keys();
  23378. return wrappedModuleIds();
  23379. },
  23380. parse: graph.contextParse.bind(graph),
  23381. resolve(source, importer, { assertions, custom, isEntry, skipSelf } = BLANK) {
  23382. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, assertions || EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  23383. },
  23384. setAssetSource: fileEmitter.setAssetSource,
  23385. warn(warning) {
  23386. if (typeof warning === 'string')
  23387. warning = { message: warning };
  23388. if (warning.code)
  23389. warning.pluginCode = warning.code;
  23390. warning.code = 'PLUGIN_WARNING';
  23391. warning.plugin = plugin.name;
  23392. options.onwarn(warning);
  23393. }
  23394. };
  23395. }
  23396. // This will make sure no input hook is omitted
  23397. const inputHookNames = {
  23398. buildEnd: 1,
  23399. buildStart: 1,
  23400. closeBundle: 1,
  23401. closeWatcher: 1,
  23402. load: 1,
  23403. moduleParsed: 1,
  23404. options: 1,
  23405. resolveDynamicImport: 1,
  23406. resolveId: 1,
  23407. shouldTransformCachedModule: 1,
  23408. transform: 1,
  23409. watchChange: 1
  23410. };
  23411. const inputHooks = Object.keys(inputHookNames);
  23412. class PluginDriver {
  23413. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  23414. this.graph = graph;
  23415. this.options = options;
  23416. this.pluginCache = pluginCache;
  23417. this.sortedPlugins = new Map();
  23418. this.unfulfilledActions = new Set();
  23419. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  23420. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  23421. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  23422. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  23423. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  23424. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  23425. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  23426. const existingPluginNames = new Set();
  23427. this.pluginContexts = new Map(this.plugins.map(plugin => [
  23428. plugin,
  23429. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  23430. ]));
  23431. if (basePluginDriver) {
  23432. for (const plugin of userPlugins) {
  23433. for (const hook of inputHooks) {
  23434. if (hook in plugin) {
  23435. options.onwarn(errorInputHookInOutputPlugin(plugin.name, hook));
  23436. }
  23437. }
  23438. }
  23439. }
  23440. }
  23441. createOutputPluginDriver(plugins) {
  23442. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  23443. }
  23444. getUnfulfilledHookActions() {
  23445. return this.unfulfilledActions;
  23446. }
  23447. // chains, first non-null result stops and returns
  23448. hookFirst(hookName, parameters, replaceContext, skipped) {
  23449. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  23450. }
  23451. // chains, first non-null result stops and returns result and last plugin
  23452. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  23453. for (const plugin of this.getSortedPlugins(hookName)) {
  23454. if (skipped?.has(plugin))
  23455. continue;
  23456. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  23457. if (result != null)
  23458. return [result, plugin];
  23459. }
  23460. return null;
  23461. }
  23462. // chains synchronously, first non-null result stops and returns
  23463. hookFirstSync(hookName, parameters, replaceContext) {
  23464. for (const plugin of this.getSortedPlugins(hookName)) {
  23465. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  23466. if (result != null)
  23467. return result;
  23468. }
  23469. return null;
  23470. }
  23471. // parallel, ignores returns
  23472. async hookParallel(hookName, parameters, replaceContext) {
  23473. const parallelPromises = [];
  23474. for (const plugin of this.getSortedPlugins(hookName)) {
  23475. if (plugin[hookName].sequential) {
  23476. await Promise.all(parallelPromises);
  23477. parallelPromises.length = 0;
  23478. await this.runHook(hookName, parameters, plugin, replaceContext);
  23479. }
  23480. else {
  23481. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  23482. }
  23483. }
  23484. await Promise.all(parallelPromises);
  23485. }
  23486. // chains, reduces returned value, handling the reduced value as the first hook argument
  23487. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  23488. let promise = Promise.resolve(argument0);
  23489. for (const plugin of this.getSortedPlugins(hookName)) {
  23490. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  23491. }
  23492. return promise;
  23493. }
  23494. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  23495. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  23496. for (const plugin of this.getSortedPlugins(hookName)) {
  23497. const parameters = [argument0, ...rest];
  23498. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  23499. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  23500. }
  23501. return argument0;
  23502. }
  23503. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  23504. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  23505. const results = [];
  23506. const parallelResults = [];
  23507. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  23508. if (plugin[hookName].sequential) {
  23509. results.push(...(await Promise.all(parallelResults)));
  23510. parallelResults.length = 0;
  23511. results.push(await this.runHook(hookName, parameters, plugin));
  23512. }
  23513. else {
  23514. parallelResults.push(this.runHook(hookName, parameters, plugin));
  23515. }
  23516. }
  23517. results.push(...(await Promise.all(parallelResults)));
  23518. return results.reduce(reducer, await initialValue);
  23519. }
  23520. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  23521. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  23522. let accumulator = initialValue;
  23523. for (const plugin of this.getSortedPlugins(hookName)) {
  23524. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  23525. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  23526. }
  23527. return accumulator;
  23528. }
  23529. // chains, ignores returns
  23530. hookSeq(hookName, parameters, replaceContext) {
  23531. let promise = Promise.resolve();
  23532. for (const plugin of this.getSortedPlugins(hookName)) {
  23533. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  23534. }
  23535. return promise.then(noReturn);
  23536. }
  23537. getSortedPlugins(hookName, validateHandler) {
  23538. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  23539. }
  23540. // Implementation signature
  23541. runHook(hookName, parameters, plugin, replaceContext) {
  23542. // We always filter for plugins that support the hook before running it
  23543. const hook = plugin[hookName];
  23544. const handler = typeof hook === 'object' ? hook.handler : hook;
  23545. let context = this.pluginContexts.get(plugin);
  23546. if (replaceContext) {
  23547. context = replaceContext(context, plugin);
  23548. }
  23549. let action = null;
  23550. return Promise.resolve()
  23551. .then(() => {
  23552. if (typeof handler !== 'function') {
  23553. return handler;
  23554. }
  23555. // eslint-disable-next-line @typescript-eslint/ban-types
  23556. const hookResult = handler.apply(context, parameters);
  23557. if (!hookResult?.then) {
  23558. // short circuit for non-thenables and non-Promises
  23559. return hookResult;
  23560. }
  23561. // Track pending hook actions to properly error out when
  23562. // unfulfilled promises cause rollup to abruptly and confusingly
  23563. // exit with a successful 0 return code but without producing any
  23564. // output, errors or warnings.
  23565. action = [plugin.name, hookName, parameters];
  23566. this.unfulfilledActions.add(action);
  23567. // Although it would be more elegant to just return hookResult here
  23568. // and put the .then() handler just above the .catch() handler below,
  23569. // doing so would subtly change the defacto async event dispatch order
  23570. // which at least one test and some plugins in the wild may depend on.
  23571. return Promise.resolve(hookResult).then(result => {
  23572. // action was fulfilled
  23573. this.unfulfilledActions.delete(action);
  23574. return result;
  23575. });
  23576. })
  23577. .catch(error_ => {
  23578. if (action !== null) {
  23579. // action considered to be fulfilled since error being handled
  23580. this.unfulfilledActions.delete(action);
  23581. }
  23582. return error(errorPluginError(error_, plugin.name, { hook: hookName }));
  23583. });
  23584. }
  23585. /**
  23586. * Run a sync plugin hook and return the result.
  23587. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  23588. * @param args Arguments passed to the plugin hook.
  23589. * @param plugin The acutal plugin
  23590. * @param replaceContext When passed, the plugin context can be overridden.
  23591. */
  23592. runHookSync(hookName, parameters, plugin, replaceContext) {
  23593. const hook = plugin[hookName];
  23594. const handler = typeof hook === 'object' ? hook.handler : hook;
  23595. let context = this.pluginContexts.get(plugin);
  23596. if (replaceContext) {
  23597. context = replaceContext(context, plugin);
  23598. }
  23599. try {
  23600. // eslint-disable-next-line @typescript-eslint/ban-types
  23601. return handler.apply(context, parameters);
  23602. }
  23603. catch (error_) {
  23604. return error(errorPluginError(error_, plugin.name, { hook: hookName }));
  23605. }
  23606. }
  23607. }
  23608. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  23609. const pre = [];
  23610. const normal = [];
  23611. const post = [];
  23612. for (const plugin of plugins) {
  23613. const hook = plugin[hookName];
  23614. if (hook) {
  23615. if (typeof hook === 'object') {
  23616. validateHandler(hook.handler, hookName, plugin);
  23617. if (hook.order === 'pre') {
  23618. pre.push(plugin);
  23619. continue;
  23620. }
  23621. if (hook.order === 'post') {
  23622. post.push(plugin);
  23623. continue;
  23624. }
  23625. }
  23626. else {
  23627. validateHandler(hook, hookName, plugin);
  23628. }
  23629. normal.push(plugin);
  23630. }
  23631. }
  23632. return [...pre, ...normal, ...post];
  23633. }
  23634. function validateFunctionPluginHandler(handler, hookName, plugin) {
  23635. if (typeof handler !== 'function') {
  23636. error(errorInvalidFunctionPluginHook(hookName, plugin.name));
  23637. }
  23638. }
  23639. function validateAddonPluginHandler(handler, hookName, plugin) {
  23640. if (typeof handler !== 'string' && typeof handler !== 'function') {
  23641. return error(errorInvalidAddonPluginHook(hookName, plugin.name));
  23642. }
  23643. }
  23644. function noReturn() { }
  23645. class Queue {
  23646. constructor(maxParallel) {
  23647. this.maxParallel = maxParallel;
  23648. this.queue = [];
  23649. this.workerCount = 0;
  23650. }
  23651. run(task) {
  23652. return new Promise((resolve, reject) => {
  23653. this.queue.push({ reject, resolve, task });
  23654. this.work();
  23655. });
  23656. }
  23657. async work() {
  23658. if (this.workerCount >= this.maxParallel)
  23659. return;
  23660. this.workerCount++;
  23661. let entry;
  23662. while ((entry = this.queue.shift())) {
  23663. const { reject, resolve, task } = entry;
  23664. try {
  23665. const result = await task();
  23666. resolve(result);
  23667. }
  23668. catch (error) {
  23669. reject(error);
  23670. }
  23671. }
  23672. this.workerCount--;
  23673. }
  23674. }
  23675. function normalizeEntryModules(entryModules) {
  23676. if (Array.isArray(entryModules)) {
  23677. return entryModules.map(id => ({
  23678. fileName: null,
  23679. id,
  23680. implicitlyLoadedAfter: [],
  23681. importer: undefined,
  23682. name: null
  23683. }));
  23684. }
  23685. return Object.entries(entryModules).map(([name, id]) => ({
  23686. fileName: null,
  23687. id,
  23688. implicitlyLoadedAfter: [],
  23689. importer: undefined,
  23690. name
  23691. }));
  23692. }
  23693. class Graph {
  23694. constructor(options, watcher) {
  23695. this.options = options;
  23696. this.astLru = flru(5);
  23697. this.cachedModules = new Map();
  23698. this.deoptimizationTracker = new PathTracker();
  23699. this.entryModules = [];
  23700. this.modulesById = new Map();
  23701. this.needsTreeshakingPass = false;
  23702. this.phase = BuildPhase.LOAD_AND_PARSE;
  23703. this.scope = new GlobalScope();
  23704. this.watchFiles = Object.create(null);
  23705. this.watchMode = false;
  23706. this.externalModules = [];
  23707. this.implicitEntryModules = [];
  23708. this.modules = [];
  23709. this.getModuleInfo = (moduleId) => {
  23710. const foundModule = this.modulesById.get(moduleId);
  23711. if (!foundModule)
  23712. return null;
  23713. return foundModule.info;
  23714. };
  23715. if (options.cache !== false) {
  23716. if (options.cache?.modules) {
  23717. for (const module of options.cache.modules)
  23718. this.cachedModules.set(module.id, module);
  23719. }
  23720. this.pluginCache = options.cache?.plugins || Object.create(null);
  23721. // increment access counter
  23722. for (const name in this.pluginCache) {
  23723. const cache = this.pluginCache[name];
  23724. for (const value of Object.values(cache))
  23725. value[0]++;
  23726. }
  23727. }
  23728. if (watcher) {
  23729. this.watchMode = true;
  23730. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  23731. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  23732. watcher.onCurrentRun('change', handleChange);
  23733. watcher.onCurrentRun('close', handleClose);
  23734. }
  23735. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  23736. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  23737. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  23738. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  23739. this.pureFunctions = getPureFunctions(options);
  23740. }
  23741. async build() {
  23742. timeStart('generate module graph', 2);
  23743. await this.generateModuleGraph();
  23744. timeEnd('generate module graph', 2);
  23745. timeStart('sort and bind modules', 2);
  23746. this.phase = BuildPhase.ANALYSE;
  23747. this.sortModules();
  23748. timeEnd('sort and bind modules', 2);
  23749. timeStart('mark included statements', 2);
  23750. this.includeStatements();
  23751. timeEnd('mark included statements', 2);
  23752. this.phase = BuildPhase.GENERATE;
  23753. }
  23754. contextParse(code, options = {}) {
  23755. const onCommentOrig = options.onComment;
  23756. const comments = [];
  23757. options.onComment =
  23758. onCommentOrig && typeof onCommentOrig == 'function'
  23759. ? (block, text, start, end, ...parameters) => {
  23760. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  23761. return onCommentOrig.call(options, block, text, start, end, ...parameters);
  23762. }
  23763. : comments;
  23764. const ast = this.acornParser.parse(code, {
  23765. ...this.options.acorn,
  23766. ...options
  23767. });
  23768. if (typeof onCommentOrig == 'object') {
  23769. onCommentOrig.push(...comments);
  23770. }
  23771. options.onComment = onCommentOrig;
  23772. addAnnotations(comments, ast, code);
  23773. return ast;
  23774. }
  23775. getCache() {
  23776. // handle plugin cache eviction
  23777. for (const name in this.pluginCache) {
  23778. const cache = this.pluginCache[name];
  23779. let allDeleted = true;
  23780. for (const [key, value] of Object.entries(cache)) {
  23781. if (value[0] >= this.options.experimentalCacheExpiry)
  23782. delete cache[key];
  23783. else
  23784. allDeleted = false;
  23785. }
  23786. if (allDeleted)
  23787. delete this.pluginCache[name];
  23788. }
  23789. return {
  23790. modules: this.modules.map(module => module.toJSON()),
  23791. plugins: this.pluginCache
  23792. };
  23793. }
  23794. async generateModuleGraph() {
  23795. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  23796. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  23797. if (this.entryModules.length === 0) {
  23798. throw new Error('You must supply options.input to rollup');
  23799. }
  23800. for (const module of this.modulesById.values()) {
  23801. if (module instanceof Module) {
  23802. this.modules.push(module);
  23803. }
  23804. else {
  23805. this.externalModules.push(module);
  23806. }
  23807. }
  23808. }
  23809. includeStatements() {
  23810. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  23811. for (const module of entryModules) {
  23812. markModuleAndImpureDependenciesAsExecuted(module);
  23813. }
  23814. if (this.options.treeshake) {
  23815. let treeshakingPass = 1;
  23816. do {
  23817. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  23818. this.needsTreeshakingPass = false;
  23819. for (const module of this.modules) {
  23820. if (module.isExecuted) {
  23821. if (module.info.moduleSideEffects === 'no-treeshake') {
  23822. module.includeAllInBundle();
  23823. }
  23824. else {
  23825. module.include();
  23826. }
  23827. }
  23828. }
  23829. if (treeshakingPass === 1) {
  23830. // We only include exports after the first pass to avoid issues with
  23831. // the TDZ detection logic
  23832. for (const module of entryModules) {
  23833. if (module.preserveSignature !== false) {
  23834. module.includeAllExports(false);
  23835. this.needsTreeshakingPass = true;
  23836. }
  23837. }
  23838. }
  23839. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  23840. } while (this.needsTreeshakingPass);
  23841. }
  23842. else {
  23843. for (const module of this.modules)
  23844. module.includeAllInBundle();
  23845. }
  23846. for (const externalModule of this.externalModules)
  23847. externalModule.warnUnusedImports();
  23848. for (const module of this.implicitEntryModules) {
  23849. for (const dependant of module.implicitlyLoadedAfter) {
  23850. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  23851. error(errorImplicitDependantIsNotIncluded(dependant));
  23852. }
  23853. }
  23854. }
  23855. }
  23856. sortModules() {
  23857. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  23858. for (const cyclePath of cyclePaths) {
  23859. this.options.onwarn(errorCircularDependency(cyclePath));
  23860. }
  23861. this.modules = orderedModules;
  23862. for (const module of this.modules) {
  23863. module.bindReferences();
  23864. }
  23865. this.warnForMissingExports();
  23866. }
  23867. warnForMissingExports() {
  23868. for (const module of this.modules) {
  23869. for (const importDescription of module.importDescriptions.values()) {
  23870. if (importDescription.name !== '*' &&
  23871. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  23872. module.warn(errorMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  23873. }
  23874. }
  23875. }
  23876. }
  23877. }
  23878. function formatAction([pluginName, hookName, parameters]) {
  23879. const action = `(${pluginName}) ${hookName}`;
  23880. const s = JSON.stringify;
  23881. switch (hookName) {
  23882. case 'resolveId': {
  23883. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  23884. }
  23885. case 'load': {
  23886. return `${action} ${s(parameters[0])}`;
  23887. }
  23888. case 'transform': {
  23889. return `${action} ${s(parameters[1])}`;
  23890. }
  23891. case 'shouldTransformCachedModule': {
  23892. return `${action} ${s(parameters[0].id)}`;
  23893. }
  23894. case 'moduleParsed': {
  23895. return `${action} ${s(parameters[0].id)}`;
  23896. }
  23897. }
  23898. return action;
  23899. }
  23900. let handleBeforeExit = null;
  23901. const rejectByPluginDriver = new Map();
  23902. async function catchUnfinishedHookActions(pluginDriver, callback) {
  23903. const emptyEventLoopPromise = new Promise((_, reject) => {
  23904. rejectByPluginDriver.set(pluginDriver, reject);
  23905. if (!handleBeforeExit) {
  23906. // We only ever create a single event listener to avoid max listener and
  23907. // other issues
  23908. handleBeforeExit = () => {
  23909. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  23910. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  23911. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  23912. [...unfulfilledActions].map(formatAction).join('\n')));
  23913. }
  23914. };
  23915. process$1.once('beforeExit', handleBeforeExit);
  23916. }
  23917. });
  23918. try {
  23919. return await Promise.race([callback(), emptyEventLoopPromise]);
  23920. }
  23921. finally {
  23922. rejectByPluginDriver.delete(pluginDriver);
  23923. if (rejectByPluginDriver.size === 0) {
  23924. process$1.off('beforeExit', handleBeforeExit);
  23925. handleBeforeExit = null;
  23926. }
  23927. }
  23928. }
  23929. const leftCurlyBrace = "{".charCodeAt(0);
  23930. const space = " ".charCodeAt(0);
  23931. const keyword = "assert";
  23932. const FUNC_STATEMENT = 1, FUNC_NULLABLE_ID = 4;
  23933. function importAssertions(Parser) {
  23934. // Use supplied version acorn version if present, to avoid
  23935. // reference mismatches due to different acorn versions. This
  23936. // allows this plugin to be used with Rollup which supplies
  23937. // its own internal version of acorn and thereby sidesteps
  23938. // the package manager.
  23939. const acorn = Parser.acorn || _acorn;
  23940. const { tokTypes: tt, TokenType } = acorn;
  23941. return class extends Parser {
  23942. constructor(...args) {
  23943. super(...args);
  23944. this.assertToken = new TokenType(keyword);
  23945. }
  23946. _codeAt(i) {
  23947. return this.input.charCodeAt(i);
  23948. }
  23949. _eat(t) {
  23950. if (this.type !== t) {
  23951. this.unexpected();
  23952. }
  23953. this.next();
  23954. }
  23955. readToken(code) {
  23956. let i = 0;
  23957. for (; i < keyword.length; i++) {
  23958. if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) {
  23959. return super.readToken(code);
  23960. }
  23961. }
  23962. // ensure that the keyword is at the correct location
  23963. // ie `assert{...` or `assert {...`
  23964. for (;; i++) {
  23965. if (this._codeAt(this.pos + i) === leftCurlyBrace) {
  23966. // Found '{'
  23967. break;
  23968. } else if (this._codeAt(this.pos + i) === space) {
  23969. // white space is allowed between `assert` and `{`, so continue.
  23970. continue;
  23971. } else {
  23972. return super.readToken(code);
  23973. }
  23974. }
  23975. // If we're inside a dynamic import expression we'll parse
  23976. // the `assert` keyword as a standard object property name
  23977. // ie `import(""./foo.json", { assert: { type: "json" } })`
  23978. if (this.type.label === "{") {
  23979. return super.readToken(code);
  23980. }
  23981. this.pos += keyword.length;
  23982. return this.finishToken(this.assertToken);
  23983. }
  23984. parseDynamicImport(node) {
  23985. this.next(); // skip `(`
  23986. // Parse node.source.
  23987. node.source = this.parseMaybeAssign();
  23988. if (this.eat(tt.comma)) {
  23989. const obj = this.parseObj(false);
  23990. node.arguments = [obj];
  23991. }
  23992. this._eat(tt.parenR);
  23993. return this.finishNode(node, "ImportExpression");
  23994. }
  23995. // ported from acorn/src/statement.js pp.parseExport
  23996. parseExport(node, exports) {
  23997. this.next();
  23998. // export * from '...'
  23999. if (this.eat(tt.star)) {
  24000. if (this.options.ecmaVersion >= 11) {
  24001. if (this.eatContextual("as")) {
  24002. node.exported = this.parseIdent(true);
  24003. this.checkExport(exports, node.exported.name, this.lastTokStart);
  24004. } else {
  24005. node.exported = null;
  24006. }
  24007. }
  24008. this.expectContextual("from");
  24009. if (this.type !== tt.string) { this.unexpected(); }
  24010. node.source = this.parseExprAtom();
  24011. if (this.type === this.assertToken || this.type === tt._with) {
  24012. this.next();
  24013. const assertions = this.parseImportAssertions();
  24014. if (assertions) {
  24015. node.assertions = assertions;
  24016. }
  24017. }
  24018. this.semicolon();
  24019. return this.finishNode(node, "ExportAllDeclaration")
  24020. }
  24021. if (this.eat(tt._default)) { // export default ...
  24022. this.checkExport(exports, "default", this.lastTokStart);
  24023. var isAsync;
  24024. if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
  24025. var fNode = this.startNode();
  24026. this.next();
  24027. if (isAsync) { this.next(); }
  24028. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  24029. } else if (this.type === tt._class) {
  24030. var cNode = this.startNode();
  24031. node.declaration = this.parseClass(cNode, "nullableID");
  24032. } else {
  24033. node.declaration = this.parseMaybeAssign();
  24034. this.semicolon();
  24035. }
  24036. return this.finishNode(node, "ExportDefaultDeclaration")
  24037. }
  24038. // export var|const|let|function|class ...
  24039. if (this.shouldParseExportStatement()) {
  24040. node.declaration = this.parseStatement(null);
  24041. if (node.declaration.type === "VariableDeclaration")
  24042. { this.checkVariableExport(exports, node.declaration.declarations); }
  24043. else
  24044. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  24045. node.specifiers = [];
  24046. node.source = null;
  24047. } else { // export { x, y as z } [from '...']
  24048. node.declaration = null;
  24049. node.specifiers = this.parseExportSpecifiers(exports);
  24050. if (this.eatContextual("from")) {
  24051. if (this.type !== tt.string) { this.unexpected(); }
  24052. node.source = this.parseExprAtom();
  24053. if (this.type === this.assertToken || this.type === tt._with) {
  24054. this.next();
  24055. const assertions = this.parseImportAssertions();
  24056. if (assertions) {
  24057. node.assertions = assertions;
  24058. }
  24059. }
  24060. } else {
  24061. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  24062. // check for keywords used as local names
  24063. var spec = list[i];
  24064. this.checkUnreserved(spec.local);
  24065. // check if export is defined
  24066. this.checkLocalExport(spec.local);
  24067. }
  24068. node.source = null;
  24069. }
  24070. this.semicolon();
  24071. }
  24072. return this.finishNode(node, "ExportNamedDeclaration")
  24073. }
  24074. parseImport(node) {
  24075. this.next();
  24076. // import '...'
  24077. if (this.type === tt.string) {
  24078. node.specifiers = [];
  24079. node.source = this.parseExprAtom();
  24080. } else {
  24081. node.specifiers = this.parseImportSpecifiers();
  24082. this.expectContextual("from");
  24083. node.source =
  24084. this.type === tt.string ? this.parseExprAtom() : this.unexpected();
  24085. }
  24086. if (this.type === this.assertToken || this.type == tt._with) {
  24087. this.next();
  24088. const assertions = this.parseImportAssertions();
  24089. if (assertions) {
  24090. node.assertions = assertions;
  24091. }
  24092. }
  24093. this.semicolon();
  24094. return this.finishNode(node, "ImportDeclaration");
  24095. }
  24096. parseImportAssertions() {
  24097. this._eat(tt.braceL);
  24098. const attrs = this.parseAssertEntries();
  24099. this._eat(tt.braceR);
  24100. return attrs;
  24101. }
  24102. parseAssertEntries() {
  24103. const attrs = [];
  24104. const attrNames = new Set();
  24105. do {
  24106. if (this.type === tt.braceR) {
  24107. break;
  24108. }
  24109. const node = this.startNode();
  24110. // parse AssertionKey : IdentifierName, StringLiteral
  24111. let assertionKeyNode;
  24112. if (this.type === tt.string) {
  24113. assertionKeyNode = this.parseLiteral(this.value);
  24114. } else {
  24115. assertionKeyNode = this.parseIdent(true);
  24116. }
  24117. this.next();
  24118. node.key = assertionKeyNode;
  24119. // check if we already have an entry for an attribute
  24120. // if a duplicate entry is found, throw an error
  24121. // for now this logic will come into play only when someone declares `type` twice
  24122. if (attrNames.has(node.key.name)) {
  24123. this.raise(this.pos, "Duplicated key in assertions");
  24124. }
  24125. attrNames.add(node.key.name);
  24126. if (this.type !== tt.string) {
  24127. this.raise(
  24128. this.pos,
  24129. "Only string is supported as an assertion value"
  24130. );
  24131. }
  24132. node.value = this.parseLiteral(this.value);
  24133. attrs.push(this.finishNode(node, "ImportAttribute"));
  24134. } while (this.eat(tt.comma));
  24135. return attrs;
  24136. }
  24137. };
  24138. }
  24139. async function normalizeInputOptions(config) {
  24140. // These are options that may trigger special warnings or behaviour later
  24141. // if the user did not select an explicit value
  24142. const unsetOptions = new Set();
  24143. const context = config.context ?? 'undefined';
  24144. const onwarn = getOnwarn(config);
  24145. const strictDeprecations = config.strictDeprecations || false;
  24146. const maxParallelFileOps = getmaxParallelFileOps(config, onwarn, strictDeprecations);
  24147. const options = {
  24148. acorn: getAcorn(config),
  24149. acornInjectPlugins: getAcornInjectPlugins(config),
  24150. cache: getCache(config),
  24151. context,
  24152. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  24153. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  24154. external: getIdMatcher(config.external),
  24155. inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
  24156. input: getInput(config),
  24157. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  24158. manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
  24159. maxParallelFileOps,
  24160. maxParallelFileReads: maxParallelFileOps,
  24161. moduleContext: getModuleContext(config, context),
  24162. onwarn,
  24163. perf: config.perf || false,
  24164. plugins: await normalizePluginOption(config.plugins),
  24165. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  24166. preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
  24167. preserveSymlinks: config.preserveSymlinks || false,
  24168. shimMissingExports: config.shimMissingExports || false,
  24169. strictDeprecations,
  24170. treeshake: getTreeshake(config)
  24171. };
  24172. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  24173. return { options, unsetOptions };
  24174. }
  24175. const getOnwarn = (config) => {
  24176. const { onwarn } = config;
  24177. return onwarn
  24178. ? warning => {
  24179. warning.toString = () => {
  24180. let warningString = '';
  24181. if (warning.plugin)
  24182. warningString += `(${warning.plugin} plugin) `;
  24183. if (warning.loc)
  24184. warningString += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  24185. warningString += warning.message;
  24186. return warningString;
  24187. };
  24188. onwarn(warning, defaultOnWarn);
  24189. }
  24190. : defaultOnWarn;
  24191. };
  24192. const getAcorn = (config) => ({
  24193. ecmaVersion: 'latest',
  24194. sourceType: 'module',
  24195. ...config.acorn
  24196. });
  24197. const getAcornInjectPlugins = (config) => [
  24198. importAssertions,
  24199. ...ensureArray$1(config.acornInjectPlugins)
  24200. ];
  24201. const getCache = (config) => config.cache === true // `true` is the default
  24202. ? undefined
  24203. : config.cache?.cache || config.cache;
  24204. const getIdMatcher = (option) => {
  24205. if (option === true) {
  24206. return () => true;
  24207. }
  24208. if (typeof option === 'function') {
  24209. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  24210. }
  24211. if (option) {
  24212. const ids = new Set();
  24213. const matchers = [];
  24214. for (const value of ensureArray$1(option)) {
  24215. if (value instanceof RegExp) {
  24216. matchers.push(value);
  24217. }
  24218. else {
  24219. ids.add(value);
  24220. }
  24221. }
  24222. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  24223. }
  24224. return () => false;
  24225. };
  24226. const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
  24227. const configInlineDynamicImports = config.inlineDynamicImports;
  24228. if (configInlineDynamicImports) {
  24229. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', URL_OUTPUT_INLINEDYNAMICIMPORTS, true, warn, strictDeprecations);
  24230. }
  24231. return configInlineDynamicImports;
  24232. };
  24233. const getInput = (config) => {
  24234. const configInput = config.input;
  24235. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  24236. };
  24237. const getManualChunks$1 = (config, warn, strictDeprecations) => {
  24238. const configManualChunks = config.manualChunks;
  24239. if (configManualChunks) {
  24240. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', URL_OUTPUT_MANUALCHUNKS, true, warn, strictDeprecations);
  24241. }
  24242. return configManualChunks;
  24243. };
  24244. const getmaxParallelFileOps = (config, warn, strictDeprecations) => {
  24245. const maxParallelFileReads = config.maxParallelFileReads;
  24246. if (typeof maxParallelFileReads === 'number') {
  24247. warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', URL_MAXPARALLELFILEOPS, true, warn, strictDeprecations);
  24248. }
  24249. const maxParallelFileOps = config.maxParallelFileOps ?? maxParallelFileReads;
  24250. if (typeof maxParallelFileOps === 'number') {
  24251. if (maxParallelFileOps <= 0)
  24252. return Infinity;
  24253. return maxParallelFileOps;
  24254. }
  24255. return 20;
  24256. };
  24257. const getModuleContext = (config, context) => {
  24258. const configModuleContext = config.moduleContext;
  24259. if (typeof configModuleContext === 'function') {
  24260. return id => configModuleContext(id) ?? context;
  24261. }
  24262. if (configModuleContext) {
  24263. const contextByModuleId = Object.create(null);
  24264. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  24265. contextByModuleId[node_path.resolve(key)] = moduleContext;
  24266. }
  24267. return id => contextByModuleId[id] ?? context;
  24268. }
  24269. return () => context;
  24270. };
  24271. const getPreserveModules$1 = (config, warn, strictDeprecations) => {
  24272. const configPreserveModules = config.preserveModules;
  24273. if (configPreserveModules) {
  24274. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', URL_OUTPUT_PRESERVEMODULES, true, warn, strictDeprecations);
  24275. }
  24276. return configPreserveModules;
  24277. };
  24278. const getTreeshake = (config) => {
  24279. const configTreeshake = config.treeshake;
  24280. if (configTreeshake === false) {
  24281. return false;
  24282. }
  24283. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ');
  24284. return {
  24285. annotations: configWithPreset.annotations !== false,
  24286. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  24287. manualPureFunctions: configWithPreset.manualPureFunctions ?? EMPTY_ARRAY,
  24288. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  24289. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  24290. ? 'always'
  24291. : configWithPreset.propertyReadSideEffects !== false,
  24292. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  24293. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  24294. };
  24295. };
  24296. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  24297. if (typeof moduleSideEffectsOption === 'boolean') {
  24298. return () => moduleSideEffectsOption;
  24299. }
  24300. if (moduleSideEffectsOption === 'no-external') {
  24301. return (_id, external) => !external;
  24302. }
  24303. if (typeof moduleSideEffectsOption === 'function') {
  24304. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  24305. }
  24306. if (Array.isArray(moduleSideEffectsOption)) {
  24307. const ids = new Set(moduleSideEffectsOption);
  24308. return id => ids.has(id);
  24309. }
  24310. if (moduleSideEffectsOption) {
  24311. error(errorInvalidOption('treeshake.moduleSideEffects', URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  24312. }
  24313. return () => true;
  24314. };
  24315. // https://datatracker.ietf.org/doc/html/rfc2396
  24316. // eslint-disable-next-line no-control-regex
  24317. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$&*+,:;<=>?[\]^`{|}\u007F]/g;
  24318. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  24319. function sanitizeFileName(name) {
  24320. const match = DRIVE_LETTER_REGEX.exec(name);
  24321. const driveLetter = match ? match[0] : '';
  24322. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  24323. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  24324. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  24325. }
  24326. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  24327. // These are options that may trigger special warnings or behaviour later
  24328. // if the user did not select an explicit value
  24329. const unsetOptions = new Set(unsetInputOptions);
  24330. const compact = config.compact || false;
  24331. const format = getFormat(config);
  24332. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  24333. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  24334. const file = getFile(config, preserveModules, inputOptions);
  24335. const preferConst = getPreferConst(config, inputOptions);
  24336. const generatedCode = getGeneratedCode(config, preferConst);
  24337. const outputOptions = {
  24338. amd: getAmd(config),
  24339. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  24340. banner: getAddon(config, 'banner'),
  24341. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  24342. compact,
  24343. dir: getDir(config, file),
  24344. dynamicImportFunction: getDynamicImportFunction(config, inputOptions, format),
  24345. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  24346. entryFileNames: getEntryFileNames(config, unsetOptions),
  24347. esModule: config.esModule ?? 'if-default-prop',
  24348. experimentalDeepDynamicChunkOptimization: getExperimentalDeepDynamicChunkOptimization(config, inputOptions),
  24349. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  24350. exports: getExports(config, unsetOptions),
  24351. extend: config.extend || false,
  24352. externalImportAssertions: config.externalImportAssertions ?? true,
  24353. externalLiveBindings: config.externalLiveBindings ?? true,
  24354. file,
  24355. footer: getAddon(config, 'footer'),
  24356. format,
  24357. freeze: config.freeze ?? true,
  24358. generatedCode,
  24359. globals: config.globals || {},
  24360. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  24361. indent: getIndent(config, compact),
  24362. inlineDynamicImports,
  24363. interop: getInterop(config),
  24364. intro: getAddon(config, 'intro'),
  24365. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  24366. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  24367. name: config.name,
  24368. namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
  24369. noConflict: config.noConflict || false,
  24370. outro: getAddon(config, 'outro'),
  24371. paths: config.paths || {},
  24372. plugins: await normalizePluginOption(config.plugins),
  24373. preferConst,
  24374. preserveModules,
  24375. preserveModulesRoot: getPreserveModulesRoot(config),
  24376. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  24377. ? config.sanitizeFileName
  24378. : config.sanitizeFileName === false
  24379. ? id => id
  24380. : sanitizeFileName,
  24381. sourcemap: config.sourcemap || false,
  24382. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  24383. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  24384. sourcemapFile: config.sourcemapFile,
  24385. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  24386. ? config.sourcemapIgnoreList
  24387. : config.sourcemapIgnoreList === false
  24388. ? () => false
  24389. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  24390. sourcemapPathTransform: config.sourcemapPathTransform,
  24391. strict: config.strict ?? true,
  24392. systemNullSetters: config.systemNullSetters ?? true,
  24393. validate: config.validate || false
  24394. };
  24395. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  24396. return { options: outputOptions, unsetOptions };
  24397. }
  24398. const getFile = (config, preserveModules, inputOptions) => {
  24399. const { file } = config;
  24400. if (typeof file === 'string') {
  24401. if (preserveModules) {
  24402. return error(errorInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  24403. }
  24404. if (!Array.isArray(inputOptions.input))
  24405. return error(errorInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  24406. }
  24407. return file;
  24408. };
  24409. const getFormat = (config) => {
  24410. const configFormat = config.format;
  24411. switch (configFormat) {
  24412. case undefined:
  24413. case 'es':
  24414. case 'esm':
  24415. case 'module': {
  24416. return 'es';
  24417. }
  24418. case 'cjs':
  24419. case 'commonjs': {
  24420. return 'cjs';
  24421. }
  24422. case 'system':
  24423. case 'systemjs': {
  24424. return 'system';
  24425. }
  24426. case 'amd':
  24427. case 'iife':
  24428. case 'umd': {
  24429. return configFormat;
  24430. }
  24431. default: {
  24432. return error(errorInvalidOption('output.format', URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  24433. }
  24434. }
  24435. };
  24436. const getInlineDynamicImports = (config, inputOptions) => {
  24437. const inlineDynamicImports = (config.inlineDynamicImports ?? inputOptions.inlineDynamicImports) || false;
  24438. const { input } = inputOptions;
  24439. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  24440. return error(errorInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  24441. }
  24442. return inlineDynamicImports;
  24443. };
  24444. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  24445. const preserveModules = (config.preserveModules ?? inputOptions.preserveModules) || false;
  24446. if (preserveModules) {
  24447. if (inlineDynamicImports) {
  24448. return error(errorInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  24449. }
  24450. if (inputOptions.preserveEntrySignatures === false) {
  24451. return error(errorInvalidOption('preserveEntrySignatures', URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  24452. }
  24453. }
  24454. return preserveModules;
  24455. };
  24456. const getPreferConst = (config, inputOptions) => {
  24457. const configPreferConst = config.preferConst;
  24458. if (configPreferConst != null) {
  24459. warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, URL_OUTPUT_GENERATEDCODE_CONSTBINDINGS, true, inputOptions);
  24460. }
  24461. return !!configPreferConst;
  24462. };
  24463. const getPreserveModulesRoot = (config) => {
  24464. const { preserveModulesRoot } = config;
  24465. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  24466. return undefined;
  24467. }
  24468. return node_path.resolve(preserveModulesRoot);
  24469. };
  24470. const getAmd = (config) => {
  24471. const mergedOption = {
  24472. autoId: false,
  24473. basePath: '',
  24474. define: 'define',
  24475. forceJsExtensionForImports: false,
  24476. ...config.amd
  24477. };
  24478. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  24479. return error(errorInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  24480. }
  24481. if (mergedOption.basePath && !mergedOption.autoId) {
  24482. return error(errorInvalidOption('output.amd.basePath', URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  24483. }
  24484. return mergedOption.autoId
  24485. ? {
  24486. autoId: true,
  24487. basePath: mergedOption.basePath,
  24488. define: mergedOption.define,
  24489. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  24490. }
  24491. : {
  24492. autoId: false,
  24493. define: mergedOption.define,
  24494. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  24495. id: mergedOption.id
  24496. };
  24497. };
  24498. const getAddon = (config, name) => {
  24499. const configAddon = config[name];
  24500. if (typeof configAddon === 'function') {
  24501. return configAddon;
  24502. }
  24503. return () => configAddon || '';
  24504. };
  24505. // eslint-disable-next-line unicorn/prevent-abbreviations
  24506. const getDir = (config, file) => {
  24507. const { dir } = config;
  24508. if (typeof dir === 'string' && typeof file === 'string') {
  24509. 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'));
  24510. }
  24511. return dir;
  24512. };
  24513. const getDynamicImportFunction = (config, inputOptions, format) => {
  24514. const configDynamicImportFunction = config.dynamicImportFunction;
  24515. if (configDynamicImportFunction) {
  24516. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, URL_RENDERDYNAMICIMPORT, true, inputOptions);
  24517. if (format !== 'es') {
  24518. inputOptions.onwarn(errorInvalidOption('output.dynamicImportFunction', URL_OUTPUT_DYNAMICIMPORTFUNCTION, 'this option is ignored for formats other than "es"'));
  24519. }
  24520. }
  24521. return configDynamicImportFunction;
  24522. };
  24523. const getEntryFileNames = (config, unsetOptions) => {
  24524. const configEntryFileNames = config.entryFileNames;
  24525. if (configEntryFileNames == null) {
  24526. unsetOptions.add('entryFileNames');
  24527. }
  24528. return configEntryFileNames ?? '[name].js';
  24529. };
  24530. function getExperimentalDeepDynamicChunkOptimization(config, inputOptions) {
  24531. const configExperimentalDeepDynamicChunkOptimization = config.experimentalDeepDynamicChunkOptimization;
  24532. if (configExperimentalDeepDynamicChunkOptimization != null) {
  24533. 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);
  24534. }
  24535. return configExperimentalDeepDynamicChunkOptimization || false;
  24536. }
  24537. function getExports(config, unsetOptions) {
  24538. const configExports = config.exports;
  24539. if (configExports == null) {
  24540. unsetOptions.add('exports');
  24541. }
  24542. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  24543. return error(errorInvalidExportOptionValue(configExports));
  24544. }
  24545. return configExports || 'auto';
  24546. }
  24547. const getGeneratedCode = (config, preferConst) => {
  24548. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
  24549. return {
  24550. arrowFunctions: configWithPreset.arrowFunctions === true,
  24551. constBindings: configWithPreset.constBindings === true || preferConst,
  24552. objectShorthand: configWithPreset.objectShorthand === true,
  24553. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  24554. symbols: configWithPreset.symbols === true
  24555. };
  24556. };
  24557. const getIndent = (config, compact) => {
  24558. if (compact) {
  24559. return '';
  24560. }
  24561. const configIndent = config.indent;
  24562. return configIndent === false ? '' : configIndent ?? true;
  24563. };
  24564. const ALLOWED_INTEROP_TYPES = new Set([
  24565. 'compat',
  24566. 'auto',
  24567. 'esModule',
  24568. 'default',
  24569. 'defaultOnly'
  24570. ]);
  24571. const getInterop = (config) => {
  24572. const configInterop = config.interop;
  24573. if (typeof configInterop === 'function') {
  24574. const interopPerId = Object.create(null);
  24575. let defaultInterop = null;
  24576. return id => id === null
  24577. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  24578. : id in interopPerId
  24579. ? interopPerId[id]
  24580. : validateInterop((interopPerId[id] = configInterop(id)));
  24581. }
  24582. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  24583. };
  24584. const validateInterop = (interop) => {
  24585. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  24586. return error(errorInvalidOption('output.interop', URL_OUTPUT_INTEROP,
  24587. // eslint-disable-next-line unicorn/prefer-spread
  24588. `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  24589. }
  24590. return interop;
  24591. };
  24592. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  24593. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  24594. if (configManualChunks) {
  24595. if (inlineDynamicImports) {
  24596. return error(errorInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  24597. }
  24598. if (preserveModules) {
  24599. return error(errorInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  24600. }
  24601. }
  24602. return configManualChunks || {};
  24603. };
  24604. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  24605. const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
  24606. const configNamespaceToStringTag = config.namespaceToStringTag;
  24607. if (configNamespaceToStringTag != null) {
  24608. warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, URL_OUTPUT_GENERATEDCODE_SYMBOLS, true, inputOptions);
  24609. return configNamespaceToStringTag;
  24610. }
  24611. return generatedCode.symbols || false;
  24612. };
  24613. const getSourcemapBaseUrl = (config) => {
  24614. const { sourcemapBaseUrl } = config;
  24615. if (sourcemapBaseUrl) {
  24616. if (isValidUrl(sourcemapBaseUrl)) {
  24617. return addTrailingSlashIfMissed(sourcemapBaseUrl);
  24618. }
  24619. return error(errorInvalidOption('output.sourcemapBaseUrl', URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  24620. }
  24621. };
  24622. function rollup(rawInputOptions) {
  24623. return rollupInternal(rawInputOptions, null);
  24624. }
  24625. async function rollupInternal(rawInputOptions, watcher) {
  24626. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  24627. initialiseTimers(inputOptions);
  24628. const graph = new Graph(inputOptions, watcher);
  24629. // remove the cache object from the memory after graph creation (cache is not used anymore)
  24630. const useCache = rawInputOptions.cache !== false;
  24631. if (rawInputOptions.cache) {
  24632. inputOptions.cache = undefined;
  24633. rawInputOptions.cache = undefined;
  24634. }
  24635. timeStart('BUILD', 1);
  24636. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  24637. try {
  24638. timeStart('initialize', 2);
  24639. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  24640. timeEnd('initialize', 2);
  24641. await graph.build();
  24642. }
  24643. catch (error_) {
  24644. const watchFiles = Object.keys(graph.watchFiles);
  24645. if (watchFiles.length > 0) {
  24646. error_.watchFiles = watchFiles;
  24647. }
  24648. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  24649. await graph.pluginDriver.hookParallel('closeBundle', []);
  24650. throw error_;
  24651. }
  24652. await graph.pluginDriver.hookParallel('buildEnd', []);
  24653. });
  24654. timeEnd('BUILD', 1);
  24655. const result = {
  24656. cache: useCache ? graph.getCache() : undefined,
  24657. async close() {
  24658. if (result.closed)
  24659. return;
  24660. result.closed = true;
  24661. await graph.pluginDriver.hookParallel('closeBundle', []);
  24662. },
  24663. closed: false,
  24664. async generate(rawOutputOptions) {
  24665. if (result.closed)
  24666. return error(errorAlreadyClosed());
  24667. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  24668. },
  24669. watchFiles: Object.keys(graph.watchFiles),
  24670. async write(rawOutputOptions) {
  24671. if (result.closed)
  24672. return error(errorAlreadyClosed());
  24673. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  24674. }
  24675. };
  24676. if (inputOptions.perf)
  24677. result.getTimings = getTimings;
  24678. return result;
  24679. }
  24680. async function getInputOptions(rawInputOptions, watchMode) {
  24681. if (!rawInputOptions) {
  24682. throw new Error('You must supply an options object to rollup');
  24683. }
  24684. const rawPlugins = getSortedValidatedPlugins('options', await normalizePluginOption(rawInputOptions.plugins));
  24685. const { options, unsetOptions } = await normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  24686. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  24687. return { options, unsetOptions };
  24688. }
  24689. function applyOptionHook(watchMode) {
  24690. return async (inputOptions, plugin) => {
  24691. const handler = 'handler' in plugin.options ? plugin.options.handler : plugin.options;
  24692. return ((await handler.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) ||
  24693. inputOptions);
  24694. };
  24695. }
  24696. function normalizePlugins(plugins, anonymousPrefix) {
  24697. for (const [index, plugin] of plugins.entries()) {
  24698. if (!plugin.name) {
  24699. plugin.name = `${anonymousPrefix}${index + 1}`;
  24700. }
  24701. }
  24702. }
  24703. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  24704. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  24705. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  24706. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  24707. const generated = await bundle.generate(isWrite);
  24708. if (isWrite) {
  24709. timeStart('WRITE', 1);
  24710. if (!outputOptions.dir && !outputOptions.file) {
  24711. return error(errorMissingFileOrDirOption());
  24712. }
  24713. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  24714. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  24715. timeEnd('WRITE', 1);
  24716. }
  24717. return createOutput(generated);
  24718. });
  24719. }
  24720. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  24721. if (!rawOutputOptions) {
  24722. throw new Error('You must supply an options object');
  24723. }
  24724. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  24725. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  24726. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  24727. return {
  24728. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  24729. outputPluginDriver
  24730. };
  24731. }
  24732. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  24733. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  24734. const emitError = () => pluginContext.error(errorCannotEmitFromOptionsHook());
  24735. return {
  24736. ...pluginContext,
  24737. emitFile: emitError,
  24738. setAssetSource: emitError
  24739. };
  24740. }), inputOptions, unsetInputOptions);
  24741. }
  24742. function createOutput(outputBundle) {
  24743. return {
  24744. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  24745. };
  24746. }
  24747. var SortingFileType;
  24748. (function (SortingFileType) {
  24749. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  24750. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  24751. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  24752. })(SortingFileType || (SortingFileType = {}));
  24753. function getSortingFileType(file) {
  24754. if (file.type === 'asset') {
  24755. return SortingFileType.ASSET;
  24756. }
  24757. if (file.isEntry) {
  24758. return SortingFileType.ENTRY_CHUNK;
  24759. }
  24760. return SortingFileType.SECONDARY_CHUNK;
  24761. }
  24762. async function writeOutputFile(outputFile, outputOptions) {
  24763. const fileName = node_path.resolve(outputOptions.dir || node_path.dirname(outputOptions.file), outputFile.fileName);
  24764. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  24765. await promises.mkdir(node_path.dirname(fileName), { recursive: true });
  24766. return promises.writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  24767. }
  24768. /**
  24769. * Auxiliary function for defining rollup configuration
  24770. * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
  24771. * @param options
  24772. */
  24773. function defineConfig(options) {
  24774. return options;
  24775. }
  24776. exports.URL_AVOIDING_EVAL = URL_AVOIDING_EVAL;
  24777. exports.URL_NAME_IS_NOT_EXPORTED = URL_NAME_IS_NOT_EXPORTED;
  24778. exports.URL_OUTPUT_EXPORTS = URL_OUTPUT_EXPORTS;
  24779. exports.URL_OUTPUT_GLOBALS = URL_OUTPUT_GLOBALS;
  24780. exports.URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT = URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT;
  24781. exports.URL_THIS_IS_UNDEFINED = URL_THIS_IS_UNDEFINED;
  24782. exports.URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY = URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY;
  24783. exports.URL_WATCH = URL_WATCH;
  24784. exports.bold = bold;
  24785. exports.commandAliases = commandAliases;
  24786. exports.createFilter = createFilter;
  24787. exports.cyan = cyan;
  24788. exports.defineConfig = defineConfig;
  24789. exports.ensureArray = ensureArray$1;
  24790. exports.error = error;
  24791. exports.errorCannotBundleConfigAsEsm = errorCannotBundleConfigAsEsm;
  24792. exports.errorCannotLoadConfigAsCjs = errorCannotLoadConfigAsCjs;
  24793. exports.errorCannotLoadConfigAsEsm = errorCannotLoadConfigAsEsm;
  24794. exports.errorDuplicateImportOptions = errorDuplicateImportOptions;
  24795. exports.errorFailAfterWarnings = errorFailAfterWarnings;
  24796. exports.errorInvalidOption = errorInvalidOption;
  24797. exports.errorMissingConfig = errorMissingConfig;
  24798. exports.errorMissingExternalConfig = errorMissingExternalConfig;
  24799. exports.errorOnlyInlineSourcemapsForStdout = errorOnlyInlineSourcemapsForStdout;
  24800. exports.getAliasName = getAliasName;
  24801. exports.getAugmentedNamespace = getAugmentedNamespace;
  24802. exports.getNewArray = getNewArray;
  24803. exports.getOrCreate = getOrCreate;
  24804. exports.getRollupUrl = getRollupUrl;
  24805. exports.gray = gray;
  24806. exports.green = green;
  24807. exports.handleError = handleError;
  24808. exports.isWatchEnabled = isWatchEnabled;
  24809. exports.mergeOptions = mergeOptions;
  24810. exports.normalizePluginOption = normalizePluginOption;
  24811. exports.picomatch = picomatch;
  24812. exports.printQuotedStringList = printQuotedStringList;
  24813. exports.relativeId = relativeId;
  24814. exports.rollup = rollup;
  24815. exports.rollupInternal = rollupInternal;
  24816. exports.stderr = stderr;
  24817. exports.underline = underline;
  24818. exports.version = version$1;
  24819. exports.yellow = yellow;
  24820. //# sourceMappingURL=rollup.js.map